Compare commits

..
535 Commits
Author SHA1 Message Date
shane d870159c46 @raea/task and docs/plan.feature: a project's plan.org as typed tasks, read and written by task id (#154)
sdk/task reads and writes a project's plan.org (Org mode) as typed tasks: keywords, properties, kinds and views a plugin can add, React hooks and components. docs/plan.feature files the plan work, landed for 0.1.4. The skills submodule moves to raea-skills e249001 (#75: section 0 step 5, open or start the project's plan).
2026-11-14 21:48:16 -05:00
shaneandshinyobjectz 4d7fa914cc Files dragged from the Finder reach the page in raea's window (app.drops) (#153)
The Source page takes files dropped anywhere on it (raea-feed's Source redesign, 0.1.4). In a browser the page's own
drop events carry them; raea's window draws the page natively, so winit's drag-and-drop never reached it. The window
keeps Bevy's FileDragAndDrop messages, whether files are over it and the paths dropped, and the page asks with
app.drops -> {over, dropped}: over while a drag is on the window, then each dropped path once. A drop is the person's
own act, so it is kept with or without --window's live calls.

Test: native::drop_tests (over while dragged, not over once it leaves, the paths handed once in order).

Co-authored-by: shinyobjectz <[email protected]>
2026-11-14 20:44:17 -05:00
shane a4bb6e5c1d raea show --project: ids, not titles (Shane 11-14: "when posting to a feed we should use feed ids or something i consistently see the agents getting them mixed up by name") (#152)
The help says what --project takes now: 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 is the only one and the folder is not in another project. The resolving is the app host's (raea-feed host/show.ts placeOf, integration-014 de50fe7).

skills pinned to raea-skills c293caa (#74): SKILL.md section 0 names a project by WORKSPACE/ID everywhere, and the raea show paragraph passes --project WORKSPACE/ID or the pasted Copy reference.
2026-11-14 20:06:19 -05:00
shinyobjectz 5f65114ce5 docs: fingerprint and libraries run on your own computer, not only a Mac
raea ships for Mac, Windows and Linux, and the fingerprint's encoders run on ONNX Runtime on all three
(systems/columns), so the manual's index, fingerprint page and API guide say "your own computer" where they said
"your Mac". The get-started tutorial keeps its Mac wording until its narration is re-recorded, and the 0.1.2 notes
stay as they shipped. raea.io already serves this text (Pages deploy addc4fdc).
2026-11-14 16:08:16 -08:00
shinyobjectz 87bfda4ed2 skills pin: raea-skills #73 (7e59af0): SKILL.md section 0, settle the workspace and the project before making anything (Shane 11-14: agents start creating and forget to pick a workspace and a project) 2026-11-14 16:06:16 -08:00
shinyobjectz 3b61818eb9 Inline SVG painted by a class draws its colour in raea's window, not black: a fill or stroke a stylesheet or class sets (svg_css_paint, the #45 path) was written into the serialized SVG as its computed value, and a colour's computed syntax is its own (oklch(), lab(), color()), which usvg doesn't parse and draws black. The app's ink tokens are oklch, so a class like stroke-ink-4 or fill-[var(--ink-4)] (the timeline's curve handles, a test chart's labels) drew black on the dark ground; the window's log said "Failed to parse fill value: 'oklch(0.96 0 0)'. Fallback to black." Each such value is now sRGB rgba(), as attributes and currentColor already were; none, currentcolor, rgb() and url() are left as they are. Checked: blitz-dom svg_paint_tests (oklch and lab to rgba, the rest kept), cargo test -p blitz-dom --lib 90 of 90. 2026-11-14 15:43:35 -08:00
shinyobjectz 1680860ff4 raea-io-gen-fit: fit.rs moved out of raea-io-gen into its own crate, re-exported as raea_io_gen::fit so every path stays. raea-io-gen was at its 2000-line crate limit on main, and the picture fallback (Keys) put it at 2095; it is now 1930. route.rs's Keys comment no longer names raea's env file by its literal path, which made skills' files.md stale. Checked: cargo test -p raea-io-gen -p raea-io-gen-fit --lib, 26 and 1 (the same 27 as before). 2026-11-14 15:38:57 -08:00
shinyobjectz 74ce0ff737 raea gen: a picture step on a host with no made.app key goes to fal, then OpenRouter
The app's Images and video now offers made.app, OpenRouter and fal (Shane 11-14: "maybe add openrouter and fal as other image options"). made.app is a key only: its OAuth tokens open its MCP server, never the API raea gen calls. So a person who signs in to OpenRouter or adds a fal key there, and has no made.app key, needs raea gen to use it: before, every picture step that named no model went to made and failed asking for MADE_API_KEY.

route.rs: the policy knows which picture services this host has a key for (Keys::here: MADE_API_KEY, FAL_KEY, OPENROUTER_API_KEY, from the environment and ~/.raea/env; cli.rs fills it in). With no made.app key, image.generate goes to fal's fal-ai/nano-banana-2 (made's own default for pictures) and image.edit to its /edit endpoint, else to OpenRouter's google/gemini-3.1-flash-image, each with a note saying why. A made.app key here, a step that names its model, and every other op route as before; with none of the three keys a picture step still goes to made, which asks for its key. The fal and OpenRouter backends already made pictures (hosted.rs).

Tests: tests_keys.rs (made first when its key is here, fal then OpenRouter without it, an edit to fal's edit endpoint, video and named models unchanged); cargo test -p raea-io-gen --lib 27 of 27.
2026-11-14 15:34:27 -08:00
shinyobjectz 90891cc86f skills pin: raea-skills #72 (cd4cddb) for 0.1.4. SKILL.md's sources comments name only paths in the public tree: apps/site/public/install and docs/targets.feature are dropped, since the strict skills gate checks each one exists and failed in a clean export of main 2026-11-14 13:56:20 -08:00
shinyobjectz bb7dc3b79f #131: what an R3F scene throws is the composition's error, and three's PMREMGenerator no longer takes the scene with it. The scene renders under raea's own error boundary (sdk/r3f session.ts Caught): a throw while rendering, in an effect or a ref is thrown out of the <R3F> drawing it, the root ended, so the render is refused naming it as a throw outside R3F is ("REFUSED the composition threw at frame 0: Error: mesh threw", exit 1). R3F's own root only reported it (reportError, else a stack without its message), drew nothing and the render ended with 0 errors. PMREMGenerator (pmrem.ts): fromEquirectangular of a panorama raea loads is that panorama, lighting the scene as scene.environment; fromScene (RoomEnvironment) and fromCubemap are left out with a warning naming them, the scene drawn without them (it threw in _sceneToCubeUV inside the stand-in renderer). Checked: both of the issue's repros (the box now draws, the throw now refuses), sdk/r3f test/errors.test.tsx 4/4, the r3f suite 54/55 (the one failure is coverage.test's Skybox/Lightmap raea-web parity cases, unrelated and failing before). docs/r3f.feature R3F15 2026-11-14 13:44:37 -08:00
shinyobjectz d6d7a520a7 #151: a package that imports raea shares the composition's SDK. A package in the project's node_modules (or the person's plugins) importing "raea", "raea/<module>" or "@raea/<package>" resolves to the work folder's copy of that module, where the composition's own imports were pointed (engine/bundle edit.rs sdk_copy, by sdk/tsconfig.base.json's paths), so one SDK and one Clock. A package isn't rewritten as the edit's own files are, so its import resolved nothing and Rolldown left raea an outside global: 0.1.3 refused it before the first frame with "Can't find variable: raea" while the same file by a relative path drew. Checked: the issue's repro (vk-parts) refused with 0.1.3's shipped bundler, draws the bar at frame 29's width with this one; engine/bundle/tests/bundle.rs a_package_importing_the_sdk_gets_the_work_folders_copy (8/8 pass). docs/ecosystem.feature EC13 2026-11-14 13:42:16 -08:00
shinyobjectz c05dfc946e Ellipsis cuts only text that doesn't fit (0.1.4, Shane's test window: onboarding's face picker drew Frog as "Fr…" and Dog as "D…"). blitz-paint measured where an ellipsis goes against the box's rounded content width, which can be up to a pixel narrower than the text the box shrink-wraps, since each edge rounds on its own; past half a pixel over, a word that fits was cut. The ellipsis and a line clamp's end now use the unrounded content width the text was laid out in. bench/ellipsis-fit/check.sh renders shrink-wrapped labels with ellipsis and with clip and wants them byte-identical, and a word wider than its box to differ; it fails on the raea before this 2026-11-14 13:39:55 -08:00
shinyobjectz c3b2108412 release.yml: Windows builds openh264-sys2 every time instead of taking it from the cache volume's target/. v0.1.4-rc1's Windows job restored target/, compiled only raea-cli, and failed to link raea.exe on 135 of openh264's SIMD routines (WaverageChromaFilter8_sse2 and the rest), the failure 0.1.3-rc4's Chocolatey nasm left: a build whose assembly never reached the rlib stays fresh to cargo. Its C++ still comes from sccache 2026-11-14 13:18:02 -08:00
shinyobjectz 2fe9f13908 skills pin: raea-skills #71 for 0.1.4 (storage_status, storage_plan, storage_trash and footage_add taught, the SOP for old video, and cli.md, feed.md and files.md regenerated against main's help and the 0.1.4 feed app). sdk/guides/craft/motion/rendering.md takes the skill copy's text, so the copy check holds: keep a replaced version, never rm a render, name versions -vN, and send old video through storage_plan and the person's yes to storage_trash 2026-11-14 12:56:35 -08:00
shinyobjectz 1c93300361 raea.root is never ~/Studio by default: with none set, a workspace someone names goes in ~/Documents/raea (or ~/raea under iCloud), and ~/Studio, the root on raea's own Mac before 11-10, is no one else's (Shane 11-14: "no internal no studio, its up to the user to set their workspace"). raea-feed's host says the same (integration-014 c01686e); raea's own Mac keeps ~/Studio through raea.root. 2026-11-14 12:29:46 -08:00
shinyobjectz ef5761d300 dmg: a failed Finder layout stops the build. The osascript ran inside an echo's $(...), where set -e never sees it fail, so dmg.sh reported ok on an image with no picture and Finder's default places (the check found it by forcing the layout script to error) 2026-11-14 12:09:56 -08:00
shinyobjectz 37652ae571 dmg: raea's Mac installer window, drawn by raea
tools/release/dmg makes the Mac download as a disk image: raea.app beside an Applications link in a Finder window
laid out over raea's own picture. background.tsx is one WGSL shader (ShaderMesh) rendered by raea: paper, a pixel
falloff Bayer-dithered into the corners, the cat leaping from the app toward Applications as dithered onion skins,
the rest of its arc as dots with a pixel arrowhead, and a second cat asleep in the corner. render.sh renders it at
1x and 2x into one multi-resolution TIFF (tiffutil -cathidpicheck), committed as background.tiff; --loop renders
the same scene moving (the leap, 3 s at 60 fps), since Finder only ever shows a window's picture still.

dmg.sh APP OUT.dmg [--volname] [--sign ID [--keychain]] [--notarize ENV]: a writable HFS+ image, the app copied in
with ditto, layout.applescript has Finder set the window (680x440 content, icon view, no toolbar, 128 px icons,
the picture, each icon's place) so Finder writes the .DS_Store, then the app's icon as the volume's, then ULFO.
Finder on macOS 27 deletes a .VolumeIcon.icns and clears the custom-icon flag when it opens the volume, so the icon
goes in after the layout. Labels are drawn black over any picture in both appearances, so the window stays light.
check.sh mounts an image read-only and checks its files, the layout's picture and the window Finder reads back.
Built and checked here with a stand-in app; nothing signed or notarized.
2026-11-14 12:09:56 -08:00
shinyobjectz 0ed836095e SK13: raea-cli stays under its 2000 lines (origin/main had it at 1999). Where each agent reads skills moves to apps/tools agent_skills.rs (folder, agents, AGENTS), beside agent_mcp, agent_hooks and agent_grokbot; raea skills install and raea doctor read it there. Grok Bot's install step is agent_grokbot::stage: the preface in the staged SKILL.md, refused over the 256 KB Grok Bot's Add new skill takes (MAX_SKILL), and the links; its test moves with it, and raea-cli's skill test checks the shipped SKILL.md with its preface fits. The preface is written in with_preface, its one caller, and ask takes the folder (both were structural twins of other code: dupes). raea-cli 1975 lines; cargo check -p raea-app-tools -p raea-cli --tests passes; the unit tests weren't run here (a debug test build of apps/tools needs the whole engine, about 15 GB, and filled the disk) 2026-11-14 12:09:48 -08:00
shinyobjectz b1b47b7cfa SK13: the manual's raea skill and raea skills pages name grokbot among --agent's values, and say how its copy is staged (regenerated from raea's help with tools/manual-ref/cli.ts gen; L1's manual reference step failed on them) 2026-11-14 12:09:48 -08:00
shinyobjectz c939b27aee SK13: Grok Bot as a raea skills install target. Grok Bot (xAI's desktop agent, /Applications/Grok Bot.app 1.1.0) keeps its skills and MCP servers on a computer of its own in the cloud and has no hooks, CLI or ACP; what reaches this Mac is its Execution on this computer. So raea skills install --agent grokbot stages raea's skill in ~/.raea/grokbot/skills (RAEA_GROKBOT_HOME), stamped, with a preface after the front matter saying raea runs on the person's Mac and how to run it there, and prints Grok Bot's own links that finish it: grokbot://app/v1/settings?id=local-execution and a prompt link, filled in but not sent, asking the Bot to make the skill from the staged file (or Skills, Add new skill, Upload file). No MCP server: Grok Bot would run its command on its own computer. apps/tools agent_grokbot.rs holds the folder, the preface, the links (encoded as Grok Bot encodes its own, within its 1000 and 2048 character limits) and the closing text; engine/cli skill.rs adds the agent and splits install_into for a test. Not built here: cargo test -p raea-app-tools agent_grokbot and the engine/cli skill tests need the integrator's lane build. 2026-11-14 12:09:48 -08:00
shinyobjectz 0ef7287fde HW0a: raea-page-sound's layer (runtime, as raea-page-stage and raea-page-window: it builds on raea-runtime-js and the mixer) 2026-11-14 09:15:19 -08:00
shinyobjectz fce94e630b HW2b: the switches' thumbs centred, 2 px all round, in Chrome and in raea's window (Shane 11-14: "slightly off center"; a thumb has no skirt and its groove is shaded evenly, as a well's lit lip read a pixel low). Shane 11-14: the kit goes into 0.1.4 2026-11-14 09:10:41 -08:00
shinyobjectz 2a38cbc2df HW: docs/hardware.feature's status as built and measured (11-14): HW0 to HW4 built; HW0b 200 presses 0 late on the mixer and 40 presses 0 late in raea's window; HW1b loudest voice -22 dB; HW2b matched by eye, the ui-parity run to do; HW5 open 2026-11-14 08:52:54 -08:00
shinyobjectz 2ce68890b8 HW0b: a fired sound is heard within the mixer's head. systems/mix tests/fire.rs opens the real output device muted (RAEA_AUDIO_MUTE=1) with a tap, fires 200 presses 15 ms apart through Live::fire, the graph with the first only as raea/tone's fire() sends it: 0 of their events reached the audio thread late, and the tap (the limiter's output, before the mute) holds 200 presses. Ignored by default, as it opens a device: cargo test -p raea-sys-mix --release --test fire -- --ignored. Also raea/tone's Meter.getValue is number | Float32Array, so FFT and Waveform (bins) type-check: sdk/audio's tsc had two errors there 2026-11-14 08:44:33 -08:00
shinyobjectz 4c392f60d6 HW0a: a page plays a sound now, on raea's mixer. raea's window has no Web Audio graph (sdk/ui platform audio.ts leaves AudioContext out), so a page's interaction sounds had no way to be heard: only a composition reached the mixer, a frame at a time. Live::fire (systems/mix live/fire.rs) plays raea/tone events at the clock's now plus the head plus their own time, building the graph when it changes; raea-page-sound (engine/page/sound) is the page's sound.fire and sound.report calls, a mixer of the page's own on a thread that opens the device on the first fire and rests its stream after 10 s idle; raea/tone's fire(play) runs play as <Sfx> runs a game's one-shot and sends its events, and the graph when it changed, to sound.fire (a browser gets no sound and one console line). Spec: docs/hardware.feature (Shane 11-14: a dark kit of our own, SPEC-01's idiom, its sounds on raea/tone and Firewheel) 2026-11-14 08:27:12 -08:00
shinyobjectz b4e8310f1f TL13a: where the drag's frame goes with the fine restyle. docs/timeline.feature: RAEA_TWIN_SYNC_LIGHT again gained nothing in four interleaved rounds (drag over still 0.62-0.67 with it, 0.65-0.67 without); a macOS sample of the page host's main thread through a 4 s drag: the page's JavaScript for the pointer event 18%, paint 18%, the snapshot of every element's box 11%, the twins' boxes taken before each event 7% and each frame 5%, Stylo's restyle 2.5% (28% before). The drag adds about 2 ms to an 18-19 ms still frame, so an incremental snapshot and paint are what is left 2026-11-14 08:25:32 -08:00
shinyobjectz 9cffd0bf0a TL13a: raea-page-host restyles finely by default. Each attribute set or cleared restyles what Stylo's snapshot invalidation finds and each ancestor itself, not the element's parent's whole subtree; RAEA_FINE_RESTYLE=0 brings back Blitz's own way, and other binaries keep it off unless set. Proven before it was made the default: ui-parity full with it on is 269/271, the same two cases failing as with it off (p15-media canvas-text and img-downscale); the app's timeline suite in a headless raea window with it on passes 53 of 54 (TL10d skips itself there); the 400-clip drag in that window ran at 48-50 fps against 38-41 without, the window's still rate 52-55. The page host sets it in main before any thread starts, as --root's RAEA_PAGE_ROOT is. docs/timeline.feature TL13a has the numbers 2026-11-14 08:09:22 -08:00
shinyobjectz d190585622 TL13a: under RAEA_FINE_RESTYLE each ancestor of a changed element is matched again, itself only. Stylo's snapshot invalidation doesn't reach an ancestor whose :has() reads the changed element: basecoat's .field > label:has(input:checked) kept its unchecked look under the trial (ui-parity p18-dom/lib-basecoat, 268/271 against 269/271 off). Without the trial the parent's whole subtree restyle hid that. The mutator's set_attribute and clear_attribute now add RESTYLE_SELF to every ancestor under the trial, which re-matches :has() on any of them without restyling their subtrees (a track's every clip, TL13a). Unset, nothing changes 2026-11-14 07:50:17 -08:00
shinyobjectz 912c957c9f TL13a: the page's layout snapshot writes its numbers in place. snapshot.rs num made a String of each number with format! before pushing it; a frame writes every element's 17 numbers (about 50,000 with 400 timeline clips) for the JS's layout. write! into the snapshot gives the same bytes without an allocation each 2026-11-14 07:31:09 -08:00
shinyobjectz 2b9f1ad862 TL13a: under RAEA_FINE_RESTYLE the snapshot names the attribute that changed. blitz-dom's snapshot listed as changed only the attributes the element had when it was taken, so an attribute being added (data-state appearing) or a second one changed before the flush was never among them, and the trial's invalidation, which reads only what changed, left [data-state=open]'s elements unstyled: ui-parity 266/271 with the trial on against 269/271 off (p14-forms/select-keys, p18-dom/lib-basecoat, p18-dom/lib-radix). The mutator adds each set or cleared attribute's name to the snapshot under the trial; unset, nothing changes 2026-11-14 07:25:59 -08:00
shinyobjectz b1bfc9ba41 TL13a: RAEA_TWIN_SYNC_LIGHT read once per twins pass, at its top, in place of a cached closure of its own (the closure was a near copy of material clay.rs's, a new dupes group); the same answer, one env read per event's sync 2026-11-14 07:19:28 -08:00
shinyobjectz d5b8b9ab35 TL13a: a page's rects taken with less work. blitz-dom transformed_rect first walks the containing-block chain without matrix math and answers None at once when no node on it has a transform or projection (the full walk then never multiplies a non-identity in and returns None too, so every answer is the same); it was the busiest leaf of a 400-clip timeline drag in raea's window, as every element's rect is taken each frame for the twins' boxes and the JS layout snapshot. raea-runtime-twins: RAEA_TWIN_SYNC_LIGHT=1 (a trial, off by default) has an event's sync_twins keep a kept twin's box rather than take every element's rect again on each pointer move: layout has not run since the frame's own twins pass took them, and that pass takes them again after this frame's layout; a new twin still takes its box at once. Unset, the sync takes every box as before 2026-11-14 07:14:46 -08:00
shinyobjectz a10d64ab75 TL13a: RAEA_FINE_RESTYLE measured. docs/timeline.feature: the 400-clip drag in a headless raea window, three rounds alternating, 37, 47 and 49 fps with the trial on (median frame 25.0, 19.2, 18.9 ms) against 31, 34 and 38 off (34.6, 30.4, 27.9 ms), the window's still rate 51-57. Not yet the window's rate, and not the default until ui-parity passes with it on (no disk for its build). One profiled drag with it on points at the rect walk next 2026-11-14 07:08:59 -08:00
shinyobjectz 1f3a058ba0 TL9b: the timeline's Send followed to the agent. docs/timeline.feature status: in raea-feed PR #19 (faf00e2) a composition's cutout, on Send, finishes the version on the host and then posts the item's own session a prompt holding the cutout's words, with nothing sent before Send and no prompt when the composition's tell is skipped; live on Claude over ACP (d63098e, e2e/timeline-live.spec.ts), the agent's first act was a search for the v2 composition and its matte 2026-11-14 07:04:31 -08:00
shinyobjectz c4550ad6ba TL7l, TL7m: a composition's footage cut out. raea's <Video> takes a matte (sdk/video media.tsx, VideoMatte exported from raea/video): a folder of PNG mattes in the media folder (m00001.png on), the file's rate, one each every frames and how many; it wears the one its source time is on (data-source-time, so trims, playbackRate, speed curves and loops follow) as its mask-image, sized and placed as its objectFit and objectPosition place the picture, the last past the end, and refuses it with framing or punchIn (the engine places those). Blitz paints raster mask-images as it paints backgrounds, and raea's render loads each frame's: a 3 s face clip's Vision mattes worn this way kept on every frame what that frame's matte keeps (overlap 0.92 at least, 0.972 on average; the uncut composition 0.53). sdk/timeline copies.ts: a media row's cutout (the matte prop's numbers, data-matte, data-brush-at, data-brush-strokes) is its clip's matte props as a film's (matte, matted, and matteFps, matteEvery, matteCount), and a set of those is the host's new cutout edit (raea-feed 2c59ec6: the host mattes the whole of what the <Video> plays into its media folder's matte/ and writes the prop; Stabilise and Retouch are refused while it is on). Conformance: 4 new Video matte tests in cutout.test.tsx. The manual's video, raea, index and editor pages regenerated (pbr.md's drift left out) 2026-11-14 06:50:28 -08:00
shinyobjectz afe2150d19 TL7n: a composition's footage retouched. sdk/timeline's composition copies move into src/copies.ts (heard, steady and now retouch: Copied, CopyEdit, copyProps, copyEdits; read.ts extends and delegates to it, nothing new exported). A media row carries retouch (of and the amounts above 0) when its <Video> plays a retouched copy; its clip's props are its own file, the copy (retouched) and the four amounts, as a film's clip has them, and a set of those is the host's new retouch edit (raea-feed de9a67d: the host retouches the <Video>'s whole file into its media folder's retouch/ and the edit writes src={staticFile(copy)} data-retouch-of and data-retouch-<amount>, the src as it was when off). Held steady too, the retouch is made from the steadied copy and comes off to it, and the clip's steadied prop is that copy (the copy under the retouch); Stabilise is refused while Retouch is on. A real 3 s face clip retouched in 4.3 s, a face on all 90 frames, and raea's render of the edited composition is the copy's own frame (0 apart; the file's is 1.4). Copies, moves and mattes are read and made at the rate the frames' times sit on (a 30/1 clip probed 29.97 had made a copy that drew a frame behind). The manual's editor page regenerated (pbr.md's drift left out) 2026-11-14 06:35:06 -08:00
shinyobjectz a77d68ef93 TL7k: a composition's footage held steady. sdk/timeline: a media row carries steady (of, level) when its <Video> plays a steadied copy; its clip's props are its own file and the copy (file, stabilise, steadied), and a set of those on footage is the host's new steady edit (raea-feed 7600f78: the host reads the <Video>'s whole file, keeps the moves in its media folder's steady/ and has raea render a copy with each frame's move as the player wears it; the edit writes src={staticFile(copy)} data-steady-of data-steady, the src as it was when off). A 2 s clip shaken along a known path steadied for real in 3.4 s, its frame-to-frame shake 7.49 px to 2.12 at 320 px; a copy with no moves is its file's every frame. The manual's editor page regenerated (pbr.md's drift left out) 2026-11-14 06:17:39 -08:00
shinyobjectz fad2dbcbf4 TL8d: a composition's <Audio> has its noise reduced and its voice changed. sdk/timeline: a media row carries its file (its staticFile path) and, when it plays a copy, what the copy was made from and how (heard: of, denoise, voice); its clip's props are its own file and the copy (file, voiced, denoise, voice), as a film's sound clip has them; a set of those props on an <Audio> is the host's new heard edit (raea-feed 9094259 writes src={staticFile(copy)} data-voice-of data-denoise data-voice, and the src as it was when both are off). Each voice's copy is as loud as its source now (the voices had moved a line with pauses -12.5 to +8.6 dB). raea renders the result: a scratch composition's line at 105 Hz voiced, 140 its own. The manual's editor page regenerated (pbr.md's drift is the paint lane's, left out) 2026-11-14 06:05:51 -08:00
shinyobjectz f9129e758c TL13a: the stage clause measured: an edit on the scene's stage by 88 ms (median of 16, sound upper bounds that count a capture's read back; 81 to 113, 15 within 100), against about 1,050 ms when only the file opened again showed it; the playhead kept, a cut clip's length kept; the engine's two gaps (props on a paused stage, the reopen's second on the stage thread) filed 2026-11-14 05:48:42 -08:00
shinyobjectz b95a9fab63 TL13a: a sequence retimed live: the stage's props carry __raeaSequences (each named Sequence's from and length), which a Sequence takes over its own until the file it was written into opens again. domReads listens for raea-props in both runtimes (lite hands its bridge's addEventListener over as __raeaListen, since its entry gives domReads none). raea-feed b7e1514 sends them as an edit is let go and seeks a paused stage again so it draws them (set_props on a paused stage isn't drawn until something steps it, an engine gap); 16 edits on the stage in raea's window by 88 ms (median of sound upper bounds that each count a capture's ~78 ms read back), the playhead held through each reopening 2026-11-14 05:48:18 -08:00
shinyobjectz af752e3a27 TL13a: the window drag told apart: a carried clip lost the pointer's capture (fixed in raea-feed 957f292); what is left is the page host's frame after a step, Blitz's widened restyle first (RAEA_FINE_RESTYLE, not yet measured) 2026-11-14 04:41:00 -08:00
shinyobjectz 85d331898f TL13a: RAEA_FINE_RESTYLE, a trial (off by default): an attribute set or cleared restyles what Stylo's snapshot invalidation finds, not the element's and its parent's whole subtrees
blitz-dom's set_attribute and clear_attribute add restyle_subtree() to the element and to its parent (an upstream TODO: make it fine grained) on top of the snapshot they take, which Stylo's traversal already diffs against the selectors that read the attribute (siblings and ancestors included). So a style change restyled every sibling's whole subtree: in raea feed's timeline (TL13a), a clip dragged along a track restyled every clip on its track each step, and Stylo's restyle was 28% of raea's window's main thread through the drag (a macOS sample of raea-page-host, 400 clips on 12 tracks). With RAEA_FINE_RESTYLE=1 the two subtree hints are left out: the snapshot's invalidation decides, and a style attribute keeps its RESTYLE_STYLE_ATTRIBUTE (its own declarations replaced, as Servo does). Unset, nothing changes. Not yet measured with it on: the release build that would ran the disk out (3 GB free); it is measured, and run against ui-parity, before it is proposed as the default.

Checked: cargo check -p blitz-dom; L0 on the file passes but for three steps other lanes' applied work fails in the shared tree (dupes' repo-wide count, raea-runtime-segments' layer, pbr.md's manual reference).
2026-11-14 04:36:00 -08:00
shinyobjectz 8e5f1d449c TL7n: footage retouched (CapCut's Retouch) filed and built: four sliders applied, faces found by Vision and retouched by Core Image on the host into a copy with the part's own sound, which the player shows in the clip's place once it has the frame; counts 49 in Chrome, 47 of 49 in the window; Not yet emptied 2026-11-14 03:44:13 -08:00
shinyobjectz daa81ca944 TL7m: footage cut out by what is brushed over it (CapCut's Custom cutout): strokes on the picture, Vision's subject instances under them followed through the clip; Not yet is Retouch; 48 browser tests 2026-11-14 03:05:22 -08:00
shinyobjectz 03e3b77578 TL7l: footage cut out (CapCut's Auto cutout): Apple's Vision mattes each frame on the host, the player wears them over the clip's own mask; Not yet is brushed cutout and Retouch; 47 browser tests 2026-11-14 02:44:39 -08:00
shinyobjectz c486a7fe16 TL7k: footage held steady (CapCut's Stabilize), filed and marked built (raea-feed PR #19 d440e5e: the clip's shake read by the host from its own file, host/shake.ts phase correlation over a grid of blocks, the path smoothed by its level, each frame's move and one zoom kept under media/stabilise and worn by the player under the clip's placement). The inspector's Not yet is now auto and brushed cutout, and Retouch; 46 Chrome tests, 44 of 46 in the window 2026-11-14 02:22:24 -08:00
shinyobjectz 78cb452725 TL8d: a sound's noise reduced and its voice changed, filed and marked built (raea-feed PR #19 183c005: a copy of the clip's own sound made on the host by host/dsp.ts, kept under media/voice, which the clip plays; both off, its own again). The inspector's Not yet is now stabilise, auto and brushed cutout, and Retouch; 45 Chrome tests, 43 of 45 in the window 2026-11-14 02:02:20 -08:00
shinyobjectz 29a3763ecf TL7j: a text's words read aloud, filed and built in raea-feed PR #19 (raea gen speech on the host, kept by the words' hash, a sound clip from the text's start) 2026-11-14 01:39:32 -08:00
shinyobjectz e4a0552663 TL7i: a mask's handles dragged on the picture, filed and built in raea-feed PR #19; a file from Media over the film takes its own vignette (TL7g) and its key's colour from its own file (TL7h) 2026-11-14 01:27:15 -08:00
shinyobjectz 08c70a8318 TL7h: the key's colour picked from the picture, filed and built in raea-feed PR #19 (read by the host from the clip's file, since raea's window has no canvas to read); TL7g's built entry and its Send line corrected 2026-11-14 01:16:21 -08:00
shinyobjectz d3762acbf1 TL7g: FilterStep's tag and attrs described, the manual regenerated with them 2026-11-14 01:00:22 -08:00
shinyobjectz d0e99b0d46 TL7g: skills pin to raea-skills #70 (9739d8d), the raea/editor exports line naming the Adjust and key exports (ADJUSTS, ADJUST_PROPS, KEY_NAMES, KEYABLE, adjustOf, adjustLook, propsAt and the rest) 2026-11-14 00:59:08 -08:00
shinyobjectz 494b395442 TL7g: a clip's own Adjust in the timeline. sdk/timeline adjust.ts: a clip's Adjust as its props (adjustBrightness..adjustGrain, 0 as shot; ADJUST_PROPS), read as the kinds not 0 (adjustOf), written whole (adjustProps), its errors, and the preview's look (adjustLook: the filter's id and steps, the vignette's background). read.ts: a sequence's <Nudge adjust> read back as the clip's props and written by the set edit with the rest of its placement; each kind keyed as adjust.<kind>. The app (raea-feed PR #19 8cab9ce): the row's adjust panel of twelve sliders, keyed, with reset; the picture wearing it as one filter after the key and a vignette layer; the host reading and writing <Nudge adjust>; Send saying it. Tests: 106 timeline SDK; 40 browser tests in Chrome, 38 of 40 in raea's window, two skipping themselves; the manual regenerated; the inspector bullet's Not yet without Adjust 2026-11-14 00:48:11 -08:00
shinyobjectz fa884594a6 TL5a, TL7g: a mask's, a key's and a crop's numbers keyed, and a part's own Adjust in the SDK. sdk/video nudge.tsx: <Nudge keys> takes dotted names (NUDGE_KEYED: mask.x..mask.round, chroma.strength, chroma.shadow, crop.left..crop.bottom, adjust.<kind>), each set into its still mask, key or crop (a mask or key it keys must be given; an adjustment starts as shot), a curve that overshoots held inside the value's range. sdk/video adjust.ts: CapCut's Adjust (brightness, contrast, saturation, exposure, sharpen, highlights, shadows, temperature, tint, fade, vignette, grain) as one SVG filter (a tone table, saturate and a warmth matrix, a 3x3 sharpen, a fractal noise added about its middle, its seed the frame) and a vignette layer; <Nudge adjust> draws them after its chroma key. A probe in raea and in Chrome: tone, colour, sharpen and vignette within 0.4% RMSE, grain the same strength (sd 0.0307 against 0.0308), its noise pattern raea's own. sdk/timeline: KEY_NAMES and KEYABLE (a clip's prop to its <Nudge keys> name, maskFeather to mask.feather), read back and written by them; propsAt, a clip's props at a frame with its keyed ones there. Tests: 25 Nudge keys and cutout, 12 adjust conformance, 99 timeline SDK; the counts (39 browser tests in Chrome, 37 of 39 in raea's window, raea-feed PR #19 e2d005b); the manual regenerated 2026-11-14 00:37:58 -08:00
shinyobjectz 5b93a70f70 TL7f: the timeline's mask, blend and key in the app (raea-feed PR #19, 4af65e9: a slider of its own track, since raea's window doesn't move a range input), the counts (38 browser tests in Chrome; 36 of the 38 in raea's window, two skipping themselves), maskStyle's prefixed properties set first so Chrome's standard mask-composite wins, and the skills pin to raea-skills #69 (6eb2cf3), the raea/editor reference naming the cutout exports 2026-11-14 00:22:23 -08:00
shinyobjectz a36df13992 TL7f: a part's mask, blend and chroma key, CapCut's Mask, Basic's Blend and Cutout's Chroma key. sdk/video cutout.ts: a mask is an SVG mask image laid over the frame (line, mirror, circle, rect, heart, star; turned, feathered by a blur no larger than the frame and its reach, inverted by excluding it from a solid layer), a blend is CSS's mix-blend-mode (CapCut's modes CSS has, Add as plus-lighter, then difference and exclusion), a chroma key an SVG filter whose colour matrix makes the key's hue transparent (strength, and shadow letting the screen's darker parts through half seen). <Nudge mask blend chroma> draws them; a masked part is placed in a full-frame layer so the mask moves with it. raea's renderer draws all three as Chrome does (a probe of a keyed green panel, a feathered heart, an inverted turned star and a screen blend; an SVG <mask> for inverting overran Vello's buffers, so it is mask-composite). sdk/timeline cutout.ts: a clip's cutout as props (mask, maskX..maskInvert, blend, keyColor, keyStrength, keyShadow), taken off by their plain values, the preview's look (cutoutLook) and its errors; a sequence's <Nudge> read back with them and written whole by the nudge edit. 18 conformance tests, 97 SDK tests; the manual regenerated 2026-11-13 23:52:40 -08:00
shinyobjectz 1190ab6953 TL7e: skills pin to raea-skills #68 (1d6530e), the raea/editor exports line naming COMBOS and COMBO_KINDS 2026-11-13 23:38:52 -08:00
shinyobjectz 5ab9285ed3 FT3e: a session started outside raea opens as a chat in raea (FT3e), and its bubble says who is on what, folded until opened (FT3f), filed with their status: built for 0.1.4 in raea-feed #25, stacked on #24, neither merged 2026-11-13 23:38:12 -08:00
shinyobjectz 3185fa5adb TL7e: the timeline's counts after Combo: 37 browser tests in Chrome, all passing; in a headless raea window 35 pass and the voice test and TL10d skip themselves there with their reasons 2026-11-13 23:07:40 -08:00
shinyobjectz 9f553d6ecc TL7e: a clip's Combo animation, CapCut's third kind. sdk/video edges.ts gains COMBOS, seven waves (pulse, sway, float, shake, swing, spin, flicker), each a property's values over one cycle eased between, comboStyle and joinStyles; <Transition combo={{ kind, frames }}> moves the part throughout with its in and out. sdk/timeline: Clip.combo { kind, length } (a cycle's frames: the clip's length plays it once, fewer loop it), the set op's combo, animStyle drawing it from the palette's combos, a plugin's Combos as data (timeline.combos, checked), and a composition's <Transition combo> as an edge op with side combo, read back. fromSequences now reads a sequence's in and out that no cut's transition takes as the clip's own In and Out (TL7d), so they survive the host's re-read. 90 SDK tests, 5 Transition conformance tests; the manual regenerated 2026-11-13 23:03:35 -08:00
shinyobjectz acb4aa404d TL14b: a sound's own tracks (fromTracks, clipEdits) move from sdk/timeline read.ts to sounds.ts, which keeps read.ts under its 500 lines 2026-11-13 22:49:40 -08:00
shinyobjectz 26d094c341 TL7d: skills pin to raea-skills c98c9d6 (PR 67: reference/sdk.md lists raea/editor's animStyle) 2026-11-13 22:47:46 -08:00
shinyobjectz 773047de9e TL7d: the scenario (a clip's own In and Out, CapCut's Animation tab; Combo not built) and its status; the timeline's counts: 36 in Chrome, 33 of 35 in raea's window, the two left Chrome's alone 2026-11-13 22:47:15 -08:00
shinyobjectz 4a8ad49d60 TL7d: the manual's raea/editor page lists animStyle, Anim, EdgeStyle and a clip's enter and exit 2026-11-13 22:46:14 -08:00
shinyobjectz a393b366ac TL7d: a clip's own In and Out animations (CapCut's Animation tab): Clip.enter and Clip.exit (a kind and its frames), set and taken off by the set operation, never longer than the clip, each kept by its own half when split; in a composition the sequence's <Transition> edge. sdk/video edges.ts holds the kinds and their styles with no React (transitionAt, transitionStyle, edgesStyle), which <Transition> now draws from and sdk/timeline's animStyle previews a film's clip by; CODE_KINDS is its TRANSITION_KINDS. Four tests 2026-11-13 22:45:58 -08:00
shinyobjectz dc148cd3f7 TL7c: the manual's raea/editor page lists captionLines, heard, Said and LineRules (each Said field documented) 2026-11-13 22:36:31 -08:00
shinyobjectz 48c027313d TL7c: skills pin to raea-skills 4f55842 (PR 66: reference/sdk.md lists raea/timeline's captionLines and heard) 2026-11-13 22:35:16 -08:00
shinyobjectz b41c609a02 TL7c: captions made from what is said (CapCut's auto captions): sdk/timeline captions.ts heard() says a film's transcript where the edited cut plays it, captionLines() gathers the words into lines (a sentence's end, a 0.6 s pause, seven words or 42 characters), and the captions operation puts them as caption-style text clips on a Captions track of their own, one edit, undone whole; in a composition each line is a sequence of words (seqEdits). Five tests 2026-11-13 22:32:03 -08:00
shinyobjectz 90975148a0 TL1c, TL2f: the timeline's counts after the window runner's fixes: 34 in Chrome, 31 of 33 in raea's window (the two left Chrome's alone); its keys follow the pointer, since the window matches no :hover for a script 2026-11-13 22:22:34 -08:00
shinyobjectz e658ea89ea TL3j: the project's media added at the playhead, as CapCut's media panel adds it
sdk/timeline: an add carrying a project file (props.asset) maps to the host's new media edit, a sequence holding a <Video>, an <Img> or an <Audio> of it. On the main track with the magnet on, the clips after it move on first and the edit names the clip before it (or after it, at the start), so the host writes it beside that one and what is over the main track stays over it. The magnet now puts an added clip in at the cut nearest where it was put (before the clip it lands in when that is nearer its start), CapCut's insert at the playhead; a paste onto the main track, an add too, lands the same way, and a duplicate keeps its place after its clip. The scenario is filed as TL3j. 77 tests; each new one fails without its rule.
2026-11-13 21:24:59 -08:00
shinyobjectz 3fc0c43af0 TL4c: status (a clip's own sound taken out with Cmd+Shift+S: sdk/timeline's extract, landed in 173e39711; the host's edit and the film's playback in raea-feed PR #19), and the browser test counts: 28 in Chrome, 22 of 27 in a headless raea window 2026-11-13 21:02:37 -08:00
shinyobjectz 173e397113 TL4c: footage's own sound taken out onto a sound track (Cmd+Shift+S in CapCut). sdk/timeline gains the extract operation: a sound clip over the same span, from the same place in the file at the same speed, curve, direction, level and fades (props.of names the footage it came from), the footage marked muted with its level and fades moved to the sound; refused for sound, words, stills and footage already taken out. A clip's muted is read from a muted <Video> (SeqRow.muted), and seqEdits turns the operation into the host's extract edit (the <Video> muted, an <Audio> of its file in a new sequence from at for frames); a sequence holding footage is pointed at its <Video>. The frame cache's look says muted only when set, so kept ranges' keys are unchanged. Reference page regenerated (Clip.muted, SeqRow.muted). Tests: four for the operation and its inverse, one for the composition's edit and its reading back (75 pass) 2026-11-13 20:55:02 -08:00
shinyobjectz 17fa0e5f31 TL10e: status (built in raea-feed PR #19: drafts and a scene's ranges in the proxy store under its one limit, shown and cleared in Settings, a discarded version's frames gone at once) 2026-11-13 20:39:20 -08:00
shinyobjectz 8df1c72a44 TL5c, TL9c, TL10d: status (built in raea-feed PR #19)
A curve shaped by hand saved by name for the workspace (timeline/curves.json in its folder); an agent's editor_edit
made as raea/editor operations in the open timeline's history; play holding on Buffering where a scene's range isn't
kept yet while it is drawn (seen in a headless raea window), and a film saying Buffering when it runs out of data; a
scene's timeline as long as the scene. 25 browser tests in Chrome.
2026-11-13 20:24:03 -08:00
shinyobjectz e3f4c6980e skills pin: raea-skills #65 (the SDK reference follows export *) 2026-11-13 20:01:36 -08:00
shinyobjectz 7ed8faa7a6 TL11b: done (raea/editor, its reference page and example, the skills' SDK reference and the footage guide) 2026-11-13 20:01:21 -08:00
shinyobjectz 283b1ffb87 skills: the SDK reference follows export * (raea/editor, raea/audio, raea/3d and the rest were missing names)
tools/skills.sh gen_sdk listed each sdk/raea/src entry's own exports from Bun's transpiler scan, which gives nothing for
export * from "@raea/<package>". So raea/editor (all of it export *) had no row, raea/audio listed Audio, Tone and music
but not Mix, Speech, song and the rest, and raea/3d, raea/animation, raea/app, raea/math, raea/state, raea/text and
raea/ui were each short. The scan now follows export * through sdk/tsconfig.base.json's paths (and relative paths),
into what those modules re-export in turn, and fails naming the line when a re-export leads to no file.
2026-11-13 20:00:08 -08:00
shinyobjectz e060c09fe2 skills pin: raea-skills #64 (raea/editor in the footage guide) 2026-11-13 19:56:45 -08:00
shinyobjectz 9a93709831 TL11b: raea/editor taught in the footage guide (a composition recut as data: fromRender, applyAll, segmentsOf, and what segments can't say), its page's summary and intro written for a reader 2026-11-13 19:54:20 -08:00
shinyobjectz ca0a14e04c TL11b: mesh.md and sprite.md regenerated (a prop's row moves: raea/editor in the program changes the order the checker lists them in) 2026-11-13 19:53:11 -08:00
shinyobjectz 8fefa2922d TL11b: the timeline SDK as raea/editor, with its reference page. sdk/raea/src/editor.ts re-exports @raea/timeline (raea/timeline was already the Sequence module's), now in sdk/tsconfig.base.json so a bundle copies it; its import of the effect table is @raea/video/effects (a relative path across packages didn't survive a bundle). Every field of its types has a doc comment (85 had none), and docs/manual/examples/edits.tsx builds a timeline, splits it, keys a fade, speeds a half up with the magnet closing the gap, and undoes it all from the inverses 2026-11-13 19:51:33 -08:00
shinyobjectz 96f7e64580 PF4, TL13a notes: the draft scale pays where the GPU does the work (the light sample room's two-range redraw 9.4 s to 8.9 s, a ray-traced shot 1.7 times); the window's 400-clip drag can't be helped by drawing only what is in view, since all 400 are on screen at the timeline's opening fit 2026-11-13 19:42:45 -08:00
shinyobjectz d79c0b8cef timeline spec: 19 of the 21 window-runnable tests pass in a headless raea window, a plugin's snap grid among them 2026-11-13 19:36:59 -08:00
shinyobjectz 81cf2e0386 timeline spec: a snap to a plugin's grid is under a browser test (and each e2e run starts with no plugins installed); drafts and a scene's kept frames drawn at a draft scale 2026-11-13 19:34:01 -08:00
shinyobjectz eed69c7bb2 PF4: a draft drawn at a fraction of its size, laid out at its own. <Composition edit={{ scale }}> registers the smaller size and draws the composition in a box laid out at its width and height (useVideoConfig still says them), scaled down, so a 3D view, whole-frame or in a page element's box, traces fewer pixels and a 2D layout in px keeps every place. The same 61-frame ray-traced 1080p shot warm: 2.75 s at full size, 1.6 to 1.7 s at 0.5. The app's drafts and a scene's kept frames write it in their throwaway source; what ships is never scaled. Registry tests: the smaller size, the declared size inside, scale 1 unchanged, out of range refused 2026-11-13 19:27:08 -08:00
shinyobjectz 271376b898 timeline spec: a plugin's additions seen with a plugin installed, and the drafts' size and clear 2026-11-13 18:46:41 -08:00
shinyobjectz e31056b6ad TL11a, TL13: a plugin's tools and snap grids as data in the timeline SDK; the window's drag told apart (a hit test a step, now gone: 27 to 36 frames a second) and what is left 2026-11-13 18:38:29 -08:00
shinyobjectz 0b7a4203b8 TL13: the timeline measured in a headless raea window: a pick 45 to 59 ms, a split 59 to 64 ms, a drag 27 to 31 frames a second with 400 clips (56 with 48), and what that is and isn't 2026-11-13 18:29:44 -08:00
shinyobjectz 95725896a2 TL7c, TL11a: text styles as data in the timeline SDK (raea's four, a plugin's checked), carried by the writer; the spec's status with the 3D scene's frame store seen through an edit in a raea window 2026-11-13 18:21:37 -08:00
shinyobjectz b476ebb82b Specs: the timeline's tests in a headless raea window (16 of 19), and PF4's finding for drafts (a render can't draw a composition smaller than it says: a draft scale is the next lever) 2026-11-13 18:09:57 -08:00
shinyobjectz fd3a75ce72 skills pin: raea-skills #63 (Effect parts in the footage guide and reference/sdk.md) 2026-11-13 17:59:26 -08:00
shinyobjectz f14232a52e TL11a: a plugin's effects as data: <Effect parts> draws an effect from CSS filter functions (amount 0 to amount 1), the timeline's palette reads them from a plugin's manifest (timeline.effects) and its writer carries them to the composition 2026-11-13 17:58:39 -08:00
shinyobjectz 43cc233f99 TL13: the timeline's first measurements (400 clips on 12 tracks, in Chrome): a pick in 9 to 13 ms, a split in 24 to 27 ms, a drag at 63 to 65 frames a second 2026-11-13 17:51:54 -08:00
shinyobjectz 31f7961287 timeline spec: the status as it stands (copy and paste, an item's own timeline, a sequence's placement and a split under a speed curve are built) 2026-11-13 17:48:07 -08:00
shinyobjectz 1918b36f9e TL3h: a composition's sequence mirrored and cropped: <Nudge mirror crop>, and the timeline's writer for a sequence's still placement (its <Nudge>'s props as they now stand) 2026-11-13 17:43:53 -08:00
shinyobjectz 387f91017c TL8c: in progress: a recording made at the timeline is written as a sequence holding an <Audio> of its file (sdk/timeline's writer); the spec's status as it stands: effects, text, voice, mirror, rotate, crop and the 3D scene's frame store built in raea-feed 2026-11-13 17:40:33 -08:00
shinyobjectz d8b51396fa skills pin: raea-skills #62 (Effect in the footage guide and reference/sdk.md) 2026-11-13 17:30:09 -08:00
shinyobjectz 0a7c064b05 TL7b: in progress: an effect as a clip: <Effect kind amount in out> filters the picture under it for its sequence's frames (blur, mono, sepia, vivid, faded, contrast, bright, dark, invert, hue), one table for the engine and the timeline's preview; the timeline reads a sequence holding one as an effect clip and writes one added 2026-11-13 17:27:57 -08:00
shinyobjectz 3620aa1def TL7c: in progress: a composition's sequence of words is a text clip (renamed, its words change; words added are a new sequence), in the timeline's reader and writer 2026-11-13 17:24:02 -08:00
shinyobjectz b938833097 skills pin: raea-skills #61 (speedCurve in the footage guide and reference/sdk.md) 2026-11-13 17:08:31 -08:00
shinyobjectz 75c3b18c22 footage guide: speedCurve for a speed ramp, and speedLength for its Sequence 2026-11-13 17:07:13 -08:00
shinyobjectz 01076723f4 TL6b: a speed curve on a composition's footage: a <Video>'s or an <Audio>'s speedCurve ([place, speed] points over startFrom to endAt, speedLength the frames it takes), its sound carried through the changing rate as one voice (raea-sys-mix Ev::Rate), and the timeline's reader and writer for a sequence's curve 2026-11-13 17:03:07 -08:00
shinyobjectz bd670d9040 TL3h: in progress: a freeze frame and footage played backward (sdk/timeline)
freeze: a still of the frame under the playhead put into its clip there, the clip split around it and what follows
making room; set reverse: a clip's footage from its last source frame to its first. Playback's mapping gives a
still its one frame at rate 0 and reversed footage its frames going back, both stepped by the timeline's own
clock; a still is ready when its frame is. 63 tests.
2026-11-13 16:54:15 -08:00
shinyobjectz 5c7dac41c2 docs/manual/whats-new/0.1.3.md: raea 0.1.3's notes as the manual's What's new page (published 2026-11-14 00:15 UTC, promoted from v0.1.3-rc7 at f2d0e0335); raea.io serves it since the 0.1.3 site deploy 2026-11-13 16:40:47 -08:00
shinyobjectz f732061d9d TL11a: in progress: a plugin adds kinds of track (sdk/timeline registry.ts): its head's title and whether it stacks over the picture or under it with the sound; raea's five are listed the same way and can't be taken; 60 tests 2026-11-13 16:38:27 -08:00
shinyobjectz d7e3d8b2b2 TL7c: in progress: a film's captions are clips on a text track over its scenes (sdk/timeline fromRender): each line its words and its span, one line at a time, moved and removed with the scene it sits on; 60 tests 2026-11-13 16:36:10 -08:00
shinyobjectz c4d3900d68 TL0d: in progress: a timeline an item declares is read and checked (sdk/timeline readTimeline): tracks of clips over an item's own data, made whole (whole frames, a kind for each track), with why for what isn't well formed; 59 tests 2026-11-13 16:27:10 -08:00
shinyobjectz f130f35870 TL0: in progress: docs/timeline.feature's status after the day: what is built, what is a code edit, what plays live, what is only decided, what isn't built 2026-11-13 16:25:02 -08:00
shinyobjectz 2b7574de39 TL0c, TL8a: in progress: a composition's <Video> and <Audio> are clips of their own (sdk/timeline read.ts)
A row for a <Video> or an <Audio> is a clip on a footage or a sound track under the sequences, where its sequence
plays it, with its place in its file and its level; its level set on the timeline is a host edit of its own, and
a move, a trim or a speed there is refused with why (they are its sequence's). 57 tests.
2026-11-13 16:22:39 -08:00
shinyobjectz bbd658263e PF6, PF8: the 0.1.4 spec with a scene's frame rate while orbiting (57 to 58 a second on the sample room), the Source view's first visit as it really is (0.59 s, 0.29 s with raea-feed #17; the 2.4 to 3.8 s before was the measuring script), the host's project lookup (raea-feed #16) and library posters (raea-feed #15) 2026-11-13 16:18:33 -08:00
shinyobjectz 91731fab14 TL7a: in progress: Transition classed in the taxonomy as raea's own (the video timeline) 2026-11-13 16:10:14 -08:00
shinyobjectz f36ffb903f TL7a: in progress: skills pinned at raea-skills #60 (reference/sdk.md has Transition) 2026-11-13 16:09:03 -08:00
shinyobjectz 0173108f72 TL7a: in progress: <Transition> brings a part in and takes it out, and a transition on a cut is that code
sdk/video transition.tsx (exported from raea): <Transition in={{ kind, frames }} out={{ kind, frames }}> around
what a <Sequence> holds plays over the part's own first and last frames: fade (through black), slide, wipe, zoom.
Nothing outside the two parts changes and the film keeps its length; two parts that only touch have no frames of
each other to mix, so there is no dissolve. sdk/timeline: raea's transitions are those four; a sequence's row
carries how it comes in and goes out, a cut whose two parts match reads back as one transition, and a transition
put on a cut, changed or taken off is two host edits (the part before's out, the part after's in); a kind the
component doesn't draw is refused with why. Tests: conformance/transition.test.tsx (3), sdk/timeline 56. The SDK
reference has <Transition>.
2026-11-13 16:05:51 -08:00
shinyobjectz bb4402e45a Fingerprint's frozen encoders are named the Edit Embedding Zoo (Shane, 11-13: the standard name in the docs, the app and what we publish): SigLIP 2, CLAP, YAMNet, EmbeddingGemma 2 and Depth Anything 3, pinned, on-device and the same for every fingerprint; a fingerprint is what a person trains over it. docs/fingerprint.md says so under What a fingerprint is, and the manual's Fingerprint page names it, with Depth Anything 3 added to its list 2026-11-13 15:42:55 -08:00
shinyobjectz 661adee396 TL3g: in progress: compound clips in sdk/timeline: the picked clips made one clip that holds them (each with the kind of track it came from), moved and trimmed as one, and put back where the compound is; 55 tests 2026-11-13 15:34:24 -08:00
shinyobjectz 73c5c93e9b TL6a: in progress: a speed on a sequence is the host's edit to the footage it holds (sdk/timeline read.ts: a row's speed, the speed edit; another field is refused with why); 53 tests 2026-11-13 15:30:25 -08:00
shinyobjectz 2427d7c9ee TL0: in progress: docs/timeline.feature says what is built, decided and not built after the first day 2026-11-13 15:25:54 -08:00
shinyobjectz e3b048e2d9 TL4c: in progress: a film's scene is its picture and its sound together (fromRender has no separate sound clip), so a cut, a move or a speed takes both, as the player plays them from the one file; 53 tests 2026-11-13 15:23:04 -08:00
shinyobjectz 08f6f621d2 TL10a: in progress: an edited film plays from its own frames (sdk/timeline play.ts)
showing: the main-track clip over a timeline frame, the source frame it shows and the rate (a speed, a curve);
frameOf: the way back from the player's time; next: where the player goes when a clip ends; ready: the timeline
ranges ready to play given the file's buffered ranges. 53 tests. The app's player uses these to play cuts,
moves, trims and speeds at once, with no render.
2026-11-13 15:20:49 -08:00
shinyobjectz 7caf1bb596 TL14b: in progress: a sound's tracks as a timeline, and its clip edits (sdk/timeline read.ts)
fromTracks: the tracks a sound's host lists (clips, notes, lines) as sound tracks; a file clip keeps its place in
its file and its level, notes and lines are shown locked with where they are edited. clipEdits: the file clips
that differ between the timeline as read and as it stands, each span before and after in seconds and dB, as the
sound's hand edit carries them. 49 tests.
2026-11-13 15:17:16 -08:00
shinyobjectz 43bfbad61f TL11a: in progress: what the timeline offers by name, and what a plugin adds (sdk/timeline registry.ts)
raea's transitions (dissolve, fade, wipe, slide) beside its easings and speed curves; readAdds checks a plugin's
additions as its manifest writes them (eases, curves, transitions) and leaves out what isn't well formed or takes
one of raea's names, with why; palette gives everything offered, raea's first. 47 tests.
2026-11-13 15:13:22 -08:00
shinyobjectz beb4ce1200 TL5d: in progress: the SDK reference page with <Nudge>'s keys prop 2026-11-13 15:09:06 -08:00
shinyobjectz 7bfa7f392c TL5d: in progress: <Nudge keys> plays a placed part's properties over time, and a key on a sequence is that edit
sdk/video nudge.tsx: keys={{ scale: [[0, 1], [45, 1.15, [0.2, 0, 0, 1]]] }} on <Nudge>: each property's keys as
[frame, value, ease?], in frames from where the part's time starts (its <Sequence>), eased linear, hold or by a
cubic bezier (sdk/math's); a keyed property wins over its still value; with no keys it is the Nudge it was.
sdk/timeline read.ts: a sequence's row carries its keys, and a key made, moved, eased or removed on it is one
host edit that writes the wrapper's keys whole (x, y, scale, rotate, opacity; another property is refused).
Tests: sdk/raea conformance/nudge-keys.test.tsx (4), sdk/timeline 45.
2026-11-13 15:07:42 -08:00
shinyobjectz 47cf338cd6 TL10: in progress: what the frame store decides, in sdk/timeline cache.ts
changed(before, after): the frames whose picture or sound differ between two states, by what is drawn over each
frame (a clip moved gives its old span and its new one; a split of footage gives none; a name, a lock or a marker
gives none). keyOf: what a kept range is kept under, the same for two states that draw it the same, so an undo
finds its frames again. evict: a closed version's frames first, then the least recently played, never what is
under the playhead while anything else can go. ahead: what to draw next, from the playhead on. 44 tests. The
stage that draws and the store that holds frames aren't built.
2026-11-13 14:52:34 -08:00
shinyobjectz b2a52f6cc1 TL6b: in progress: a clip under a speed curve keeps how many source frames it shows, so the curve taken off gives its exact length back (every preset, tested); a trimmed or split curve clip keeps its share 2026-11-13 14:47:44 -08:00
shinyobjectz c78ded29e8 TL4a: in progress: a dragged main-track clip swaps by the edge it leads with (past its neighbour's middle), as CapCut's does; 37 tests 2026-11-13 14:36:12 -08:00
shinyobjectz 1c3cb953bd TL0c: in progress: a timeline read from a composition's sequences or a film's scenes (sdk/timeline read.ts); seqEdits maps move, trim, split and remove to the host's sequence edits; a move past the film's first frame stops there; 37 tests 2026-11-13 14:29:37 -08:00
shinyobjectz 53a5cc9ca7 TL0: in progress: sdk/timeline, the timeline's model and every edit as an operation
The package (TypeScript, no React, no DOM): tracks, clips, keys, markers and transitions in whole frames (model.ts);
each edit as a pure operation, refused with its reason or answered with its inverse (ops.ts: move, trim, split,
remove and ripple, delete left and right, duplicate, add, speed and curves, keys and their easing, markers, track
heads, transitions, the magnet, snapping and linkage switches); a keyed property's value at a frame through a cubic
bezier (keys.ts); speed curves with CapCut's presets, their length and source time in closed form (speed.ts); what
an edge snaps to (snap.ts). After each operation the timeline is settled: the main track closed while its magnet is
on, what sits over a main clip carried with it while linkage is on, transitions kept only on cuts that still exist.

34 tests (bun test test) for TL0a, TL0b, TL3c to TL3f, TL4a to TL4c, TL5a, TL5c, TL6a and TL6b's model. Not yet:
reading a timeline from a composition (read.ts) and an operation as code edits (edits.ts), groups and compound
clips, and the app's strip drawing this model.
2026-11-13 14:29:37 -08:00
shinyobjectz 3b670e79a5 TL0: the timeline SDK for 0.1.5 filed as scenarios (CapCut's timeline on the composition, edits sent to the agent, keys and curves, the frame store, TL0 to TL14) 2026-11-13 14:29:37 -08:00
shinyobjectz 530ff8e3de A ray-traced mesh gets MikkTSpace tangents only when its material has a normal map
Solari traces a mesh in one layout, tangents included, so every traced mesh without its own had MikkTSpace's made for
it, in one system on one thread. Solari's shader reads a tangent for one thing, a normal map (vendor/bevy_solari
scene/bindings.wesl). A mesh whose material has none now gets a unit vector across each normal, which costs nothing.

A sample of a ray-traced render of a 2.5 s shot (Sticky Feet s04-stoop, 61 frames) had MikkTSpace as 182 of the 402
samples the first frame waited for its models. Before: the models' wait 744 ms, frame 0's sync 1093 ms. After, six
runs: the wait 529 to 632 ms, frame 0's sync 656 to 802 ms. Its steady frames are unchanged (23 ms).
2026-11-13 14:29:33 -08:00
shane f2d0e0335c Merge pull request #150 from shinyobjectz/win-vulkan-loader
Release: install the Vulkan loader on a Windows runner without one
2026-11-13 17:27:53 -05:00
shinyobjectz b4fa9ae676 Release: the Windows render check installs the Vulkan loader when the runner has none
Namespace's Windows image has no vulkan-1.dll, so rc6's check found no adapter ("vulkan drivers/libraries could not
be loaded") although lavapipe was registered. lavapipe.sh now fetches LunarG's runtime components 1.4.328.1
(checksum pinned), copies the loader into System32 when it's missing, and fails at once unless vulkaninfo lists
lavapipe.
2026-11-13 14:19:45 -08:00
shane 5aa6c4cd36 Merge pull request #149 from shinyobjectz/win-nasm-check
Release: the Windows nasm step checks its version without /dev/stderr
2026-11-13 16:19:32 -05:00
shinyobjectz ad8187aefd Release: the Windows nasm step checks its version without /dev/stderr
rc5's Windows job stopped in the nasm step: Git Bash on the runner has no /dev/stderr, so the tee that printed
nasm -v failed. The output is now captured, printed, and matched against the pinned version.
2026-11-13 13:12:11 -08:00
shinyobjectz 1bfd0388b0 docs/lightspeed.feature: 0.1.4's rule with what landed and what was measured since (PF1-PF8) 2026-11-13 13:09:18 -08:00
shane cbd7649e02 Merge pull request #148 from shinyobjectz/win-nasm-pin
Release: Windows takes NASM 2.16.03, never Chocolatey's newest
2026-11-13 15:31:42 -05:00
shinyobjectz fc83cf7446 Release: Windows always takes NASM 2.16.03 from its own zip, never Chocolatey's newest
rc4 on Namespace's Windows image installed Chocolatey's NASM, and raea.exe failed to link: 135 of openh264's
SIMD routines (WelsSampleSad16x8_sse2 and the rest) unresolved, though openh264's C++ was built to call them.
GitHub's image, where rc3 linked, ships NASM 2.16. The step now always unpacks the 2.16.03 zip, puts it first
on PATH and fails if nasm -v names another version.
2026-11-13 12:24:03 -08:00
shane 2bbf0179fc Merge pull request #143 from shinyobjectz/render-quality-guide
Guides: which render quality to ask for (review versions take none)
2026-11-13 14:58:33 -05:00
shinyobjectz dcd1107a9f skills: pin raea-skills at 16ed215 (#59, render quality guidance) 2026-11-13 11:47:39 -08:00
shinyobjectz bf07a473ae Guides: a version made for notes takes no --quality flag, a film delivers at high, master is for delivered motion graphics and type 2026-11-13 11:46:08 -08:00
shinyobjectz f9b6f22ecf media: a quarter second of frames waits ahead; a video drawn small sends only the halving it is drawn from 2026-11-13 11:43:31 -08:00
shinyobjectz fcd6e12c03 media: the halvings' loop reads its last level without a closure (dupes) 2026-11-13 11:43:31 -08:00
shinyobjectz d7a755c08b Video plays smoothly at 4K and at 60 fps: frames decoded ahead and shown when due, a faster BGRA conversion, halvings from the decoder's thread, no relayout for a same-size frame 2026-11-13 11:43:31 -08:00
shinyobjectz b776edd026 RAEA_MODELS_TRACE=1: a wait for a scene's models says how many updates it ran and for which models 2026-11-13 11:42:00 -08:00
shinyobjectz 9a289e072c bundle: the copies' lookup is one closure, shorter notes (dupes, size) 2026-11-13 11:42:00 -08:00
shinyobjectz 4bc503d81d A render starts in a fraction of the time in a real project: the export cache and the bundler no longer read or stat every file under the edit's folder 2026-11-13 11:42:00 -08:00
shinyobjectz 4e252226a6 A deferred camera's MSAA is left off: msaa_for_3d turned it on again each frame, Bevy turned it off and warned, once a frame in every ray-traced render's log 2026-11-13 11:40:56 -08:00
shinyobjectz ca184a08c9 docs/lightspeed.feature: 0.1.4, the performance release (PF1-PF8): each area's measured baseline, what is fixed, what is open 2026-11-13 11:30:27 -08:00
shane cceec65c38 Merge pull request #146 from shinyobjectz/win-nasm
release.yml: nasm on Windows runners that lack it
2026-11-13 14:27:18 -05:00
shinyobjectz fac78b331b release.yml: the Windows job installs nasm when the image lacks it (Chocolatey, else NASM's zip). rav1d's build script runs nasm; GitHub's Windows image has it and Namespace's doesn't, so rc3's dry run on Namespace stopped there after 3 minutes. An inventory of Namespace's windows-2022 image found nasm the only missing tool the build uses 2026-11-13 11:19:32 -08:00
shane ae49b9f3c9 Merge pull request #142 from shinyobjectz/runner-cache-guard
release.yml: cache volume steps only on Namespace runners
2026-11-13 14:07:58 -05:00
shinyobjectz edf25e43c0 release.yml: the cache volume's steps follow the runner (a Namespace runner, nsc-*), not a repo variable: the Namespace plan has no Windows runners (not allowed to create windows/amd64 instances), so Windows builds on GitHub's runner with the R2 compile cache while the Mac and Linux keep their build folders on Namespace's volumes 2026-11-13 10:56:45 -08:00
shane 4a563b9cf6 Merge pull request #139 from shinyobjectz/cache-inline
release.yml: the cache script from the workflow's commit, and faster runners by repo variable
2026-11-13 13:55:50 -05:00
shane ea5e9015e7 Merge pull request #141 from shinyobjectz/play-tsconfig
raea play works in a folder with its own tsconfig.json
2026-11-13 13:55:45 -05:00
shane d8c392b69a Merge pull request #140 from shinyobjectz/yamnet-fetch
Fingerprint's YAMNet is fetched once on every machine (for 0.1.3)
2026-11-13 13:48:14 -05:00
shinyobjectz 035783ae0c raea play works in a folder with its own tsconfig.json: the work copy leaves it out (it shadowed the live runtime's paths; play, the stage and played stills threw __at is not a function) 2026-11-13 10:46:25 -08:00
shinyobjectz 08a3904127 release.yml: Namespace runners for the release build, by repo variable: RELEASE_*_RUNNER hold runs-on label lists (a machine and a cache volume), RELEASE_RUNNER_CACHE=1 keeps the build folder and cargo's downloads on the volume between runs (nscloud-cache-action, after the tag's checkout), so a candidate rebuilds what changed and links. The cleanup that deletes target/ is skipped there (a bind mount on Linux), and the Mac's Xcode pruning runs only on GitHub's runner. sccache on R2 stays for the workspace's own crates, which a fresh checkout's file times mark as changed 2026-11-13 10:43:48 -08:00
shinyobjectz cae6d2201c release.yml: the build jobs run on a faster runner when the repo names one (vars RELEASE_MAC_RUNNER, RELEASE_LINUX_RUNNER, RELEASE_WINDOWS_RUNNER; a third party's), else GitHub's own as before. GitHub's macOS runner is a 3-core M1 with 7 GB: a cold release build took 183 minutes there, Linux 105 and Windows 142 (0.1.2-rc5) 2026-11-13 10:37:07 -08:00
shinyobjectz b8d38aa2c0 Fingerprint's YAMNet is fetched once where perception's copy isn't (systems/columns models.rs), from the public repo's models-1 release (Google's model, Apache-2.0, as ONNX; perception's copy, sha256 8e4e21d5) and checked against that sha256, so every machine has the same encoders. Before, only machines with perception's copy had YAMNet: a fingerprint trained on one (Shane's) refused a fresh install's columns ('trained on other encoders'), so a fingerprint kept with a project didn't judge on a teammate's machine. A fingerprint trained without YAMNet takes it as an encoder added since. raea-sys-ml models.rs gains ensure_url, a file from a URL of its own 2026-11-13 10:29:16 -08:00
shinyobjectz d685762382 release.yml: the compile cache's script comes from the workflow's own commit (a sparse checkout into .workflow), not the tag's tree: a dispatched dry run that fills the cache builds an older tag (v0.1.3-rc3), whose tree has no tools/release/compile-cache.sh, so its Linux and Windows jobs stopped at 'Use the compile cache' with exit 127 2026-11-13 10:25:44 -08:00
shane c96de52402 Merge pull request #138 from shinyobjectz/release-cache
release.yml: a compile cache for release builds (sccache on R2)
2026-11-13 13:17:01 -05:00
shinyobjectz b4e6f54d55 release.yml: a compile cache for release builds, sccache on an R2 bucket (raea-build-cache), so a candidate after a small change compiles only what changed instead of three cold hours. GitHub's own cache can't carry it: a tag's run reads only its own tag's caches and the default branch's, so rc3's would never reach rc4, and the repo's 10 GB are CI's. tools/release/compile-cache.sh turns it on when the job has the bucket's key (secrets RELEASE_CACHE_ENDPOINT, RELEASE_CACHE_KEY_ID, RELEASE_CACHE_SECRET), each OS and architecture under its own prefix, C and C++ in build scripts through cc-rs and CMake's launchers; when the bucket can't be reached or written the build runs uncached, as before. Each cargo call's minutes are a notice on the run, and sccache's hits and misses are printed after the build. Linking (thin LTO) and build scripts' runs aren't cached 2026-11-13 10:07:28 -08:00
shane d145985058 Merge pull request #136 from shinyobjectz/feed-tasks-spec
docs/feed-tasks.feature: the feed-tasks spec (FT1-FT3)
2026-11-13 12:47:29 -05:00
shinyobjectz 03685d6139 docs/feed-tasks.feature: the feed-tasks lane's spec (FT1-FT3), for 0.1.3. FT1, the graph view never taking a press outside its own box in the window, is in rc3 (engine 37846080a) and raea-feed #11. FT2, the agents button as a checkbox that opens an editable to-do list built on the brief's tasks and sent edits, and FT3, a session started outside the app as a bubble in its project's feed while it is open, are raea-feed #12. Each rule's status says what was built, the decisions taken, what was checked and how, and what is left 2026-11-13 09:38:34 -08:00
shinyobjectz 620c796095 docs/scene-feed.feature SF8e: done. raea-feed #10 merged with raea-skills #58 (collaborate.md's row, reference/feed.md regenerated) and raea pins it (#133); the strict skills check passes against raea-feed main. The scene feed ships in 0.1.3 2026-11-13 12:14:09 -05:00
shinyobjectz 37846080a7 A box that clips its overflow takes no pointer for what it cuts away, in both of the window's hit tests. A card zoomed past the edge of a canvas (React Flow at scale 2) was drawn clipped but took the presses on the sidebar and the header around the canvas. blitz-dom's hit_inner tested children wherever they overflowed to: it now skips a clipping box's children when the point is outside its padding box, and a hoisted (z-index) child is under its stacking-context root's clip and the clips of the boxes between along its containing blocks, the ones blitz-paint's hoisted_clips draws it under; a box painted from above (#39) is under none. sdk/ui's hit dropped the inherited clip at a child with its own z-index and replaced it at a child that clips: both now cut the child's clip to the one it is under; a fixed box is exempt. Proved by the app's e2e/canvas-layer.spec.ts in a headless window (fails with either half alone) and a unit test in sdk/ui/test/dom.test.tsx that fails on the old hit 2026-11-13 09:03:49 -08:00
shinyobjectz e24034ee10 docs/manual/reference/sdk: raea.md and time.md regenerated for #126 (a Sequence's length in useVideoConfig); main's L1 failed on them for every lane 2026-11-13 09:03:44 -08:00
shinyobjectz 9f4990cd90 stage: the hold and wireframe are a crate of their own (raea-sys-hold); the stage's new calls share one send 2026-11-13 09:03:44 -08:00
shinyobjectz 7026280df3 docs/scene-feed.feature: the open items built and checked (SF2e the view's toolbar, SF3e wireframe, SF4c the part follows the drag, SF4d a part inside a group, the timeline's film); only the skills teaching is open 2026-11-13 09:03:44 -08:00
shinyobjectz df9d1d11d5 media: a playing video's frames leave its decoder when they fall due; RAEA_MEDIA_STATS says how play goes (measured: raea-feed d55df57) 2026-11-13 09:03:44 -08:00
shinyobjectz e60a8bc5fe stage: hold a part, say where it stands, wireframe (docs/scene-feed.feature SF4c, SF4d, SF3e) 2026-11-13 09:03:44 -08:00
shinyobjectz 1496780fa4 docs/scene-feed.feature: the scene feed item's spec (SF1-SF10), for 0.1.4: raea 3D looked at from inside in the feed, as one scene or a board of them; looking around with the watch view's timeline, comments pinned in the scene's space, parts moved, drawn and re-keyed in the scene's own code, a procedural part's props, quality that steps down under memory pressure, and what is open (SF8). Built on raea-feed branch scene (549b321); each rule's status says what was checked and how 2026-11-13 09:03:44 -08:00
shinyobjectz 2cb2136348 raea pins raea-skills main faa9938 (#58): feed_post's scene item (raea 3D looked at from inside in the feed) in collaborate.md and reference/feed.md, with the app at raea-feed 24b2eb5 (#10). SKILLS_STRICT=1 tools/skills.sh check passes against that app 2026-11-13 11:52:05 -05:00
shinyobjectz e368a5dbcb Inside a Sequence, useVideoConfig().durationInFrames is the Sequence's length (#126): a subtree's LocalTime carries its length, the composition's at the root, a Sequence's own cut where its parent's ends (unbounded, what's left of its parent's), a Loop's one pass, and a Freeze keeps its parent's; useVideoConfig reports it as it reports a Sequence's width and height, and a Sequence's time is still the same object frame to frame. Written from the spec line and its conformance test (#128): conformance 615 pass, the same five failing as on main 2026-11-13 11:33:49 -05:00
Ragulsundaram e3dfcb96d1 Spec: inside a Sequence, useVideoConfig().durationInFrames is the Sequence's length (its own, cut short where its parent's ends; a Loop's children get one pass), as Remotion's public docs for useVideoConfig say, and its conformance test (#126, from #128) 2026-11-13 11:33:49 -05:00
shinyobjectz f845ef0add raea pins raea-skills main d71042f (#57): the fingerprint page says what each axis reads (pictures, sound, motion, text, each on its own encoder) and that no shipped axis judges recorded against generated sound. SKILLS_STRICT=1 tools/skills.sh check passes 2026-11-13 10:56:43 -05:00
shinyobjectz cb01f542c0 Fingerprint gets its own section of the docs (docs/manual/fingerprint): what it is and the Fingerprint page, training one (renders, notes, marks, a box on the part of a sound you mean, the post-mortem), checking a cut (score, --was, scripts and stills, things, profiles), and projects and teams, with the judged-by chip's Keep with this project and Keep with the workspace (FP14e) written up for the first time. The guide it replaces (guides/fingerprint.md) is split into those pages; the manual's index lists them. raea pins raea-skills main f40ca31 (#56): the skill gains fingerprint.md, how an agent uses the person's fingerprint, routed from SKILL.md. SKILLS_STRICT=1 tools/skills.sh check passes 2026-11-13 10:56:43 -05:00
shinyobjectz 054738329d Skills for 0.1.3: raea pins raea-skills main e58e2a2 (#55, Solari's traced-sun limits as of raea 0.1.2; Solari is unchanged since 0.1.1), and sdk/guides/craft/bevy/solari.md, the source the skill's 3d/solari.md is copied from, says the same, so tools/skills.sh check's copy test passes. With the 0.1.3 app (raea-feed afb8074) as RAEA_APP, SKILLS_STRICT=1 tools/skills.sh check passes: the feed and files references need no change 2026-11-13 10:18:37 -05:00
shinyobjectz e85de83289 FP11c: a note's Reading, the readings' agreement and a label's span move to raea-sys-fingerprint-use (reading.rs), keeping raea-app-fingerprint under its 2,000 lines; sound_band finds its box without a copied closure 2026-11-13 06:13:08 -08:00
shinyobjectz 06090e06cd FP11c: done. A box drawn on the sound's spectrogram is a note's mark: learn-notes labels its span and keeps its pitch band in the evidence row
raea-feed #9 draws the spectrogram on the timeline and in Listen, and stores a box as a time pin over its span with a
mark on: "sound" ([time, mel] in 0-1). Here: grow::marked skips sound boxes (they are no place in the frame),
grow::sound_band reads the band, Reading and evidence::Row gain band, and learn-notes keeps a defect's band in its row,
widening a span shorter than half a second about its middle. The manual's fingerprint guide says how to draw one and
that the sound heads, per window, keep the band but don't learn from it yet.
2026-11-13 06:09:01 -08:00
shinyobjectz 7729997d96 FP14e: done. A project's judged-by is a menu that keeps one of the person's fingerprints with the project or its workspace (raea-feed #8: share, use and a commit of the folder) 2026-11-13 05:52:49 -08:00
shinyobjectz 8818eaa2ec Install guide: how the desktop app updates, checking by hand (Settings, General), and the Mac's Downloads pitfall: opened from Downloads, raea 0.1.1 and 0.1.2 run from a read-only copy and can't replace themselves, so install it into Applications once 2026-11-13 05:41:45 -08:00
shinyobjectz b715d70366 fingerprint.feature FP7a: archiving runs the postmortem in the 0.1.2 app (raea-feed #5 is merged) 2026-11-13 05:14:02 -08:00
shinyobjectz 2c6132a460 docs/manual/whats-new/0.1.2.md: raea 0.1.2's notes as the manual's What's new page (published 2026-11-13, promoted from v0.1.2-rc5 at 1be8199c8) 2026-11-13 02:26:31 -08:00
shinyobjectz 1be8199c85 FP1b, FP14d, FP10a: tagged done. FP14d's every clause is built (teach, approve, pair, read and learn-notes label the one that judges; move takes rows up). FP1b's scripts, briefs and pages are EmbeddingGemma 2 rows and its stills and sounds go through the encoders picture and sound axes already read, as its status says; FP10a's one stuck axis (glow) holds out 0.90 on another on-device encoder, so no adapter or trainer was needed 2026-11-12 23:11:04 -08:00
shinyobjectz 3599e18b6f FP13a: a render's camera path is its own and a thing's vector is its patch tokens. things.rs moved(): from the AOV pass's motion vectors (NAME.aov/motion), the median move of every pixel as the pan and the median move out from the middle after the pan as the zoom, eight times a second, with no model run; footage keeps raea-perceive flow. On the lurch red-team render it reads -0.063 then -0.190 frames a second (the scene trucks 0.02 then 0.06 a frame), where flow read -0.015 then -0.066, and 0 on the two renders whose camera holds still. pooled(): a thing's one vector is its frame's SigLIP 2 patch tokens averaged over the cells its mask covers half of or more, in place of the box pooled; fingerprint-things no longer needs image. Not yet: footage's camera path from Depth Anything 3 (the port gives depth only). 2026-11-12 23:11:04 -08:00
shinyobjectz 923163e7b9 FP5a: a reading keeps the layers under its pin. On a render with a layer pass, pinned() reads the layer-pass names under the pin's x,y at its moment (located.rs layers, now public) into the reading, and the reader's prompt says "pinned on NAME". On the things red-team render a pin on a block reads Box and one on the empty sky none (ignored test layers_under_a_pin). FP5a is tagged done with its status: read, readings, learn-notes 2026-11-12 22:34:25 -08:00
shinyobjectz 691673f616 FP11b: a mark on a defect note is followed through its whole shot. grow.rs through: the shot around the note from raea-perceive cuts (at most 8 s either side), EdgeTAM forward and back at 4 frames a second, and one region for each 2 s window where it kept the thing on half its frames or more, the box around it there; the note's own window always, at the mark. learn-notes makes one row a kept window (one row over the label's span without raea-perceive). cuts() moves from things.rs to grow.rs for both. On the things red-team renders a mark on a still block kept both windows at its layer-pass box (overlap 0.97) and one on a moving block followed it across the frame (0.41) 2026-11-12 22:29:45 -08:00
shinyobjectz edd00ee9ca CI installs cargo-shear 1.14.0 and cargo-dupes 0.2.1, the versions L0 runs, not whatever is newest: cargo-shear 1.14.1 (out 11-13) calls engine/cli's ignores for its feature-only dependencies on raea-runtime-bake and raea-runtime-sound redundant, which 1.14.0 needs, so main's gates went red from 43cfe8712 on 2026-11-12 22:25:18 -08:00
shinyobjectz 23f5a5ce53 Skills: raea-skills 7c835cc (release-012) for 0.1.2: fingerprint-where 9cad448 (score names where in the frame and the layers there; cli.md from raea's help after FP12a) merged with raea-skills main (#52, #53: the plugin's directory edition), the directory edition rebuilt from the skill, and reference/files.md from the app 0.1.2 ships (~/.raea/fingerprints, the storage files). skillcheck --strict and tools/skills.sh check with SKILLS_STRICT=1 pass 2026-11-12 22:19:06 -08:00
shinyobjectz a5a81f22b8 The manual's raea fingerprint page from raea's help after FP12a: bootstrap also trains patch heads that say where in the frame a picture defect is, and score's first moments say where and the layers there 2026-11-12 22:15:11 -08:00
shinyobjectz e05cee0c73 Windows app launch (#124): bytes become a string a 32 KB slice at a time, not String.fromCharCode(...bytes), which passed every byte as an argument and overflowed the stack on a blob of a few hundred KB (FileReader's readAsDataURL and readAsBinaryString, fetch's request body, a WebSocket's binary send, and the node shim's Buffer toString latin1); @raea/ui's platform has one latin1() for all of them, with a test of a 4 MB buffer. A frame's root-absolute script (/artifact.js) is found under the page's roots on Windows too: against a page at file:///C:/... it is C:\artifact.js, which only a leading / was taken for 2026-11-12 22:11:45 -08:00
shinyobjectz 50a695f0fb FP3b, FP5b, FP5c, FP12b, FP13b: decided for 0.1.2. FP3b closes on its first clause and its second moves to FP5c; FP5b's gate stays (no readings are checked yet, so notes train nothing); FP5c isn't measured on unchecked readings; FP12b and FP13b wait on Shane's own marks, so no grounder ships 2026-11-12 22:08:25 -08:00
shinyobjectz c65baf2c81 FP12a: patch heads say where in the frame a picture defect is. raea fingerprint bootstrap also puts FP0f's local defects in a random box of up to 6 frames a source (a blurred patch, a black hole, heavy grain, flat grey, a local glow; one that changes its box by under 6 levels is left out) and fits a logistic on SigLIP 2's 196 patch tokens per axis. Held out by source from 8 frames on 27 real renders: barren 0.92, glitch 0.90, blur 0.88 (0.79 before the visible rule), glow 0.49; an axis says where only at 0.85. score gives a flagged moment its place and the layers under it, by name (raea-sys-layers reads names); --json has at, the sheet boxes it in amber 2026-11-12 22:08:25 -08:00
shinyobjectz d679fa1cc4 LR10, LR11: done. LR0 lists the gap left after LR1-LR10 (23 of 33 pass; the 10 still off are LR10's list, each with its cause); #54 is closed with the harness's before and after and the cost per read, and #13 is answered with what now matches Chrome; the skills' motion router (raea-skills #50) merges into raea-skills main when 0.1.2 is published 2026-11-12 22:06:32 -08:00
shinyobjectz bf74492d50 docs/sdk-coverage.md retaken from main: 1557 of 1671 things reached (1548 before), the 3D camera's Hdr and feathers' theme components now typed in sdk/render, and seven more CSS longhands Blitz draws; the floor rises to 1557 2026-11-12 22:02:44 -08:00
shinyobjectz 43cfe87121 The SDK reference names the manual's examples where they use a component (hello, title, turntable), regenerated from main and these pages; the names check leaves a release's published notes as they were (docs/manual/whats-new: 0.1.0's canaries name the motion package by its name then) 2026-11-12 21:54:52 -08:00
shinyobjectz a2477cd71e Install page: raea skills install's hooks and Blender MCP server for every agent (and --no-hooks, --no-mcp), the Claude plugin from raea-skills with RAEA_NO_SKILLS=1 beside it, and the ALSA and fontconfig libraries Linux needs 2026-11-12 21:54:09 -08:00
shinyobjectz 33896c4518 The manual's install page says which GPUs raea draws on, and what runs without one (#110): a Windows PC with no DirectX 12 or Vulkan GPU (3rd-generation Intel graphics, for one) can't open the app's window or draw 3D; 2D video still renders on the CPU 2026-11-12 21:54:09 -08:00
shinyobjectz c7d7b59dfb The manual's install page for v0.1.1: pinning shows 0.1.1, and it says the desktop app comes from raea.io for the Mac, Windows and Linux and tells you when a new version is out 2026-11-12 21:54:09 -08:00
shinyobjectz 33380411d8 The manual's pages that raea.io/docs has served since 11-08 but no repository held until now (start/, concepts/, guides/3d|apps|words, examples/, whats-new/, index.md, and docs/manual.feature): written 11-08 by a session that has since ended and deployed from a working tree, they were parked on a branch so they couldn't be lost, and land for 0.1.2 so main's manual and the site are the same pages (16 links on main went to pages only the site had). It also holds the What's new pages for 0.1.0 and 0.1.1, made from their release notes by the release folder's whats-new.sh 2026-11-12 21:54:09 -08:00
shinyobjectz b537bcfffd The tour says how to consolidate the Inbox or a feed into a summary on its timeline, and that a working agent has a stop button beside it in the Agents list, the Feed's chat and the Inbox (raea-feed PR #1: c43ff66, 8fe9953) 2026-11-12 21:48:09 -08:00
shinyobjectz af293fcc35 Agents docs: each AI's own settings (agents.feature A7). Settings → Agents lists the AIs signed in on this Mac, each with what its ACP session reports it can be set to (thinking, mode, its own switches such as Claude's fast mode) plus environment and extra arguments; an agent on that AI shows the same settings, each defaulting to the AI's; they layer AI default, the Mac's defaults, the agent's, then the chat's model, and one that no longer applies becomes a notice 2026-11-12 21:48:09 -08:00
shinyobjectz e81d06dd8b Agents docs: no Director. The workspace has one primary, the harness at its root that takes whatever nothing else was picked for (a connected AI on a model, or one of the person's agents); New chat's menu picks a connected AI's model or an agent; an agent is a provider with more on top, kept in the workspace's folder (agents.feature A1c, A6) 2026-11-12 21:48:09 -08:00
shinyobjectz 96d2820589 A ShaderMaterial's shader is its colour pass's only: a prepass keeps Bevy's own fragment, which writes the normals and motion the prepass targets expect. Under Solari the camera has a normal and motion prepass, and the colour shader in it failed validation ("Error matching ShaderStages(FRAGMENT) ... prepass_pipeline") and Stay's fern dropped out. The three.js host draws <Instances> at each placement its data-at gives (sdk/render instances.tsx), as one InstancedMesh, instead of one mesh at the origin (sdk/r3f test/instances.test.tsx). docs/linux.feature is Shane's 11-11 plan for a faster Linux engine in the cloud: where a frame's time goes on Modal's GPUs, and the scenarios to test, validate and improve it (none started) 2026-11-12 21:46:51 -08:00
shinyobjectz 09eeb21fe9 LR10: getBoundingClientRect through a perspective is the box of the four corners as drawn, as Chrome's is. blitz-dom's transformed_bounds took each node's affine transform only, so a card turned under a perspective (its Projection) read at its flat size and place; one in a preserve-3d context maps from its context root's parent. A blitz-dom test holds Chrome's numbers for a 400x200 card under a 1000px perspective, rotateY(60deg), flat (379.05, 379.05, 206.19, 241.90) and in a world turned rotateX(10deg). transformed_rect maps any rect in a node's box, and a render manifest text's ink goes through it. snapcn 21 -> 23 of 33: card-rail 161.4 px off -> 0.6, announce-title 11504 -> 43.5, punch-lines and text-rewrite pass; P26 unchanged (185 of 215, every frame at the same SSIM) 2026-11-12 21:45:09 -08:00
shinyobjectz ea5fc2e5ef MX1, MX2: raea-sys-mlx, MLX on Apple silicon's GPU beside raea-sys-ml's ONNX Runtime (docs/mlx.feature)
On mlx-rs =0.34.0 (MIT OR Apache-2.0), which builds MLX v0.32.2 from source with cmake at build time. The dependency
is macOS-only, so the crate is empty on Linux and Windows. A model's MLX path is plain functions over its safetensors,
read by the checkpoint's own tensor names (weights.rs), with f32 tensors in and out (tensor.rs) and layers that do
PyTorch's maths (nn.rs): a Linear runs in its weight's dtype; LayerNorm, GELU and SiLU run in f32; attention is MLX's
fused kernel. Tests check each layer against the same maths in plain Rust on the CPU. f32 matmuls run in TF32 on the
GPU by default (within 3e-3; 1e-5 with MLX_ENABLE_TF32=0). use_metallib points MLX at a fetched metallib (MX4). No
model uses it yet: IDOL, which was to be first, is held.
2026-11-12 21:28:48 -08:00
shinyobjectz d415e0c59d Skills: raea-skills d5100dc (fingerprint-docs, on component-name 278f4ff): the skill teaches raea fingerprint things with raea check --things on a 3D shot (and its copy of the scenes guide), the post-mortem when a project is finished, and that a script scores on text axes only; cli.md gains check --things and fingerprint things (merged to raea-skills main when 0.1.3 is published) 2026-11-12 21:28:00 -08:00
shinyobjectz 7452b0d90c FP13: the scene guide's motion step runs raea fingerprint things and raea check --things on a moving shot (lands with raea-skills d5100dc, the guide's copy) 2026-11-12 21:25:42 -08:00
shinyobjectz d6d97c3b8d FP13, FP2f, FP1b: the manual and the scene guide teach fingerprint things with raea check --things, the post-mortem and scripts; docs/fingerprint.md says realness was measured and not shipped, and what FP1b's text column and FP13's things read 2026-11-12 21:24:34 -08:00
shinyobjectz 6c106fb8f4 FP1b: an axis judges only what a file has. A script scored with raea's own taxonomy came back blurry, glowing and frozen, because picture heads scored its empty picture columns; now each axis needs rows of its own modality, and a script's windows say nothing until an axis reads text (tested) 2026-11-12 21:22:19 -08:00
shinyobjectz 869318073a LR10: a family raea/text's loadFont asked for gets Google's faces in the page even where raea bundles faces of that name, as a linked stylesheet's @font-face shadows a local font in Chrome. Inter is bundled (static 400 and 700), so it was never a missing family and Google's never came: 300, 400 and 500 drew alike ("snapcn" at 100px 345.45 px; Chrome 340.39, 345.47, 350.45) and 600 as 700. Now 340.33, 345.45, 350.48, 355.38, 360.45. snapcn 18 -> 21 of 33 (wordmark-cut, text-select, hero-launch pass; punch-lines 18.1 -> 0.9, text-rewrite 7.4 -> 0.2); P26 unchanged (185 of 215, every frame at the same SSIM). LR10 records the read cost: the first read in a frame about 0.39 ms, each further one about 0.01 ms (300 frames, median of 6), and karaoke-captions' reads under the run's noise 2026-11-12 21:21:05 -08:00
shinyobjectz cd268ef764 FP7a: archiving a project runs the post-mortem in the background (raea-feed PR #5) 2026-11-12 21:11:27 -08:00
shinyobjectz b8d21bf712 FP2f: raea-sys-fingerprint-things holds things and geometry (the camera-speed, floating, passing-through and empty-frame reads), split from raea-sys-fingerprint-use to keep each crate under 2,000 lines 2026-11-12 21:09:35 -08:00
shinyobjectz e652168202 FP2f: realness measured, not shipped. A head on a sound's CLAP and YAMNet means, labels by construction: raea's SAO foley, TokenSynth notes and Fish narration against recorded foley, instrument notes and speech under CC0 and CC BY (Clotho, NSynth, LibriSpeech). Held out by generator it scores TokenSynth 0.90, Fish 0.80 and SAO 0.57, under the 0.85 it needs on all three, so it isn't an axis 2026-11-12 21:06:06 -08:00
shinyobjectz 6abeb6ed43 LR10: a Google family from raea/text's loadFont is fetched when loadFont is called, and a canvas's measureText and svg text have it. The page fetched it at the first layout that named it, after a component's first effect had measured (its canvas found the fallback), and a family the page fetched first was cached without ever reaching usvg's font database, so document.fonts.load found it already known and gave the canvas nothing. Figtree's "scene" at 600 64px measured 145.72 (the fallback) against Chrome's 171.25; now 171.26. blitz-dom leaves out an app-bundled svg face of a family the page already gave (Geist fetched at import came before the bundled Geist, and both stayed; tested). snapcn 17 -> 18 of 33: bloom-lockup passes (40.8 px off before), word-gather 25.5 -> 1.2; P26 unchanged (185 of 215, every frame at the same SSIM) 2026-11-12 21:04:41 -08:00
shinyobjectz 3dc3096963 Skills: raea-skills 278f4ff (component-name, on fingerprint-fix 6047418): the graphics router teaches raea component list, add and --shared, and the motion guides' copies say raea component add (merged to raea-skills main when 0.1.3 is published) 2026-11-12 21:00:01 -08:00
shinyobjectz 55d9eeaa50 raea component, raea part's new name in 0.1.3 (Layout LY1-LY4), in what teaches it: each ready component's header (examples/parts, the registry the CLI copies from), the edit template, the craft guides (motion.md, motion/parts.md, motion/footage.md) and the manual's raea part page, now the old name of raea component. The graphics router in raea-skills teaches component list, add and --shared (raea-skills component-name 278f4ff); the skills check's coverage no longer finds raea component untaught 2026-11-12 20:36:08 -08:00
shinyobjectz bf984d4656 Skills: raea-skills 6047418 (fingerprint-fix): SKILL.md tells an agent to check a fix with raea fingerprint score NEW --was OLD, and reference/cli.md is regenerated 2026-11-12 20:34:49 -08:00
shinyobjectz 0902d43201 FP10a: glow, stuck under the gate on its look columns (held out 0.79 on 580 labels in the 'me' fingerprint), holds out 0.90 on SigLIP 2's picture columns, an encoder already on the device, so raea's base taxonomy reads glow from pictures, as FP4b's bootstrap already measured it; no adapter was needed 2026-11-12 20:32:56 -08:00
shinyobjectz 5189132ef8 LR10: a canvas's system-ui and BlinkMacSystemFont are macOS's SF ("System Font", variable in weight and optical size), as Chrome's canvas takes them. fontdb knew neither name, so a font list headed by them (snapcn's '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif') was measured and drawn in Helvetica, about 10% wider at 72px, and 600 measured as 700. -apple-system alone stays as it is: Chrome's canvas finds no face for it either. text-build, which places its words from measureText, goes from 9 px off Chrome to 1.3; the rest is SF's trak table, which CoreText applies and usvg doesn't 2026-11-12 20:30:01 -08:00
shinyobjectz 0f9da00368 LR10: kerning across spans, hidden inline words, and a render manifest read as Chrome draws. blitz-dom gave every composition span a border edge (with border-style none a border's computed width is still medium, and inline_edges read the width alone), so each plain span got a spacer box at both ends and parley split the shaping there: a line set a letter a span lost its kerning (AVAWATAVAWAT 632 px, Chrome 578; snapcn's word-flip 5.6 px wide). sdk/ui/parity's p13-text/kerning-spans holds it. blitz-paint doesn't draw a visibility: hidden inline element's glyph runs, though they keep their place (#13: word-flip's strut drew as a fake word). A still drawn again after an all-black first draw replaces its manifest entry instead of adding one (every later frame was listed a place late), and check.sh finds frames by number. A manifest text's ink spans its glyph runs and inline-blocks, not the padding at a line's ends. snapcn 12 -> 17 of 33 (word-flip, text-reveal, text-swell, karaoke-captions, word-captions); P26 unchanged (185 of 215, the same frames at the same SSIM). The web-components guide lists innerHTML and outerHTML as missing 2026-11-12 20:30:01 -08:00
shinyobjectz 9632d542cd LR10: the 2D context's roundRect and arcTo geometry move to paths.ts beside the Path they draw on (context.ts was 517 lines with letterSpacing and wordSpacing, over the 500 limit); the motion guide's rule 2 (sdk/guides/craft/motion.md, which raea-skills copies) says what a composition's DOM answers 2026-11-12 20:30:01 -08:00
shinyobjectz d9a5296796 Skills: raea-skills 1a321b5 (on fingerprint-ref), the motion router's rule 2 names the web APIs a composition's DOM answers and the raea modules that install them (raea-skills #50, merged to raea-skills main when 0.1.3 is published) 2026-11-12 20:30:01 -08:00
shinyobjectz 53d5f94888 LR2: every host that runs a composition answers its layout reads. Live play (preview, raea play, the app's stage, an exported game) answers from its live page, synced mid-settle as a render's is. Live play's lite runtime set no refs (a ref was null, a canvas drawn through one drew nothing): its hosts now keep bevy-react's BevyElement, BevyCanvasElement and BevyTextNode linked as React's tree is and set and clear refs, and entry_lite installs canvas2d and the DOM reads. raea world answers from the page it lays its frames out with; a baked timeline (raea play --baked) refuses a read plainly instead of baking it as 0. #54's repro played live puts "here" at x 342 (x 0 before); every layout-reads probe played live is its render's frame (SSIM 1.000), and the games replay (pong, platformer, lite against React) stays 1.000. A read costs a live frame about 1.5 ms (step p50 0.4 -> 1.9 ms, one read a frame on a 40-line page) 2026-11-12 20:30:01 -08:00
shinyobjectz a504787ad3 LR11: where the docs stand (the manual's web-components guide, raea-skills #50 held until 0.1.3 is published) and what's open (#54, #13) 2026-11-12 20:30:01 -08:00
shinyobjectz 05fb89ab72 LR11: the manual's guide to web components that measure (docs/manual/guides/web-components.md): what a ref, document and window answer as Chrome does, the frame held until a measure lands, and what a composition's DOM lacks (MutationObserver and IntersectionObserver never call back, an img's onError never fires, one rect for a wrapped Range) 2026-11-12 20:30:01 -08:00
shinyobjectz 44ca3f16d6 LR10: a page's fonts as Chrome finds them, in svg and canvas text. An @font-face face is found by its own weight and style, not its file's (Google serves one variable Inter as every weight, whose file says 400, so 500 drew as 400 and 600 as raea's bundled 700); a face given twice (document.fonts.load and the page's @font-face) is added once; a page's faces of a family shadow the app's bundled ones, as @font-face shadows a local font (raea's static Inter 400 beside Google's 400 read to canvas text as a family split by unicode-range); and a character's advance is read at the weight asked for (a space's moves with a variable face). The canvas has letterSpacing and wordSpacing, shaped by the host. snapcn: title-sweep 3.7 -> 0.3, spec-sweep 4.4 -> 0.3, sky-lockup 15.7 -> 0.3; the corpus 12 of 33 (7 before LR10) 2026-11-12 20:30:01 -08:00
shinyobjectz 8a51aa0433 LR10: svg text spaces its last letter as Chrome does. usvg 0.48.1 left letter-spacing off a text chunk's last cluster, so an svg <text> with letter-spacing and a middle or end anchor was drawn half or a whole spacing off where Chrome draws it, and its box was a spacing short. vendor/usvg patches apply_letter_spacing (marked raea:), canvas.svgText's length drops the tracking it added to make up for it, and the layout-reads box reader skips an svg's <title> and <desc>, which are never drawn. snapcn: drop-line 1.3 -> 0.2 and hello-zoom pass; P26 unchanged (the six fixtures under the bar fail the same frames at the same SSIM on a binary without the patch) 2026-11-12 20:30:01 -08:00
shinyobjectz 677ca278ba FP13a, FP13c, FP10a: raea fingerprint things FILE finds a piece's shots, its things with their depth and the ground under them every half second and a SigLIP 2 vector each (a render's things from its layer pass, NAME.layers, and its depth from its AOV pass when beside it, with no model run; footage's from the marks on its notes, followed by EdgeTAM, on Depth Anything 3 Small), and the camera's path (Lucas-Kanade flow); geometry.rs measures floating, passing through, a camera that changes speed mid-move and an empty frame, each with red-team cases, and raea check --things reports them as findings, never heads. The layers file reader moves from runtime/world into raea-sys-layers so both read it, and raea-perceive depth-values takes many frames to one model load. report names the axes stuck under the gate with 300 labels or more, the only ones that may try another encoder or an adapter 2026-11-12 20:28:09 -08:00
shinyobjectz 9eb649bf98 FP1b: scripts, briefs and pages get EmbeddingGemma 2 rows, a passage a step on their timeline (raea-sys-columns gemma.rs on ort with the q8 export the app's library keeps in ~/.raea/models, the same vectors transformers.js gives), and an axis with modality "text" scores its words as EmbeddingGemma 2 queries against 24 ordinary passages; a still or storyboard frame is one frame through SigLIP 2. Evidence written before the text column reads as the same rows with no text, and a fingerprint pinned before EmbeddingGemma 2 was on the machine keeps working 2026-11-12 20:28:08 -08:00
shinyobjectz 1e8c404738 FP11b: grow.rs's union widens a box in a loop 2026-11-12 19:24:22 -08:00
shinyobjectz 535acb5a4f FP11b: a mark's region and a matte's box share one union (grow.rs), and raea-perceive is looked for beside raea, then on PATH, in a loop of its own 2026-11-12 19:23:25 -08:00
shinyobjectz 8579b43228 FP9a, FP7a: the CLI reference describes score --was and postmortem's --ask and --tally, regenerated from raea help 2026-11-12 19:22:18 -08:00
shinyobjectz e367fe8190 FP9a, FP7a: a fix checked against the flag it claims to fix, and a postmortem. raea fingerprint score NEW --was OLD says whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than its clean work), and exits 1 unless all are fixed (fixed.rs). raea fingerprint postmortem [PROJECT] [--ask N] [--tally] scores every version in the project's feed, asks at most ten yes/no questions in the app where a head goes against the person's labels or is least sure, each with its moment as a clip, and --tally makes the answers evidence and prints each head's held-out AUC before and after (postmortem.rs) 2026-11-12 19:20:35 -08:00
shinyobjectz c6acc16633 FP11a, FP11b: a note's marks teach. learn-notes makes a defect note's mark, box and lasso its row's region, grown and tracked over the label's span by EdgeTAM (raea-perceive track, from the note's frame forward and back; frames it loses dropped; grow.rs in raea-sys-fingerprint-use), and a span pin the row's time. The review player's marks and the agent's reading of arrows and strikes are in raea-feed 2026-11-12 19:20:35 -08:00
shinyobjectz 6c7889dbf7 Claude plugin: raea's marketplace installs raea-skills' plugin (its skills/ folder: the raea skill and its two hooks) instead of a second raea plugin of its own, whose manifest said 0.1.0 and carried no hooks. The README says how to install it 2026-11-12 19:03:08 -08:00
shinyobjectz 620ccb4093 Email plan (docs/email.feature): sign-in by emailed code, invites and review links by email, two-factor, notices, and raea news, the list people opt into and out of (EM10). Status 11-12: raea.io verified in Resend, DNS added, sign-in by email and the list live 2026-11-12 19:01:15 -08:00
shinyobjectz aca025d343 FP14d: the CLI reference describes move's flags (--to, --source, and --project's meaning with move), regenerated from raea help 2026-11-12 18:57:32 -08:00
shinyobjectz e4b607e7f8 FP14d: a note or mark teaches the fingerprint that judged the piece. teach, approve and pair already label the one which picks for the file; read, readings and learn-notes now keep a project's notes in the one that judges the project ([PROJECT] on readings and learn-notes), and learning again remakes only those notes' rows. raea fingerprint move [--fp CHILD] [--to PARENT] --axis/--source/--project takes a child's own matching rows up into a fingerprint it extends and retrains both; rows on an axis the parent lacks or the child overrides stay 2026-11-12 18:53:03 -08:00
shinyobjectz 0226baca9a FP14a: raea/brief's reference page lists the fingerprint types brief.ts exports (Fingerprint, Axis, Applies, Modality and fingerprint()) 2026-11-12 18:43:27 -08:00
shinyobjectz 760fcc9ec8 FP2c: raea-sys-fingerprint is a facility: raea-sys-fingerprint-use scores, compares and picks with its taxonomy, evidence and heads 2026-11-12 18:39:11 -08:00
shinyobjectz 4dcfa760b1 FP2c: Cargo.lock without half in raea-sys-fingerprint and serde_json in raea-sys-fingerprint-use, which neither uses now 2026-11-12 18:35:52 -08:00
shinyobjectz 85b877f06b skills pin: raea-skills fingerprint-ref (c5bfd05), on its main (cb8904f, #51), held off main until 0.1.3 ships: the skill scores a cut with the person's fingerprint before posting it and names raea/fingerprint, and reference/sdk.md lists raea/fingerprint 2026-11-12 18:34:47 -08:00
shinyobjectz 28fd448ea2 FP2c: fingerprint folded into what it copied, as L1's duplicate check asks. The ledger says its rows' labels, counts and projects once for training, inheritance, pairs and the bootstrap; one half-float codec serves the column cache and a fingerprint's words and evidence; a verb's files and a list's lines are read once; raea check's defects and its sound rules share their level in dB and their moments as issues; Encoders::pins is a map; the bootstrap names its own rows and each sense's defects once 2026-11-12 18:33:37 -08:00
shinyobjectz db58ead2c9 FP14a: room for fingerprint in L1's checks. raea/fingerprint gets its SDK reference page under Tools, every field of a fingerprint.ts described; the four crates have their layers; raea-sys-fingerprint-use drops serde_json, which it never used; and raea-cli's hook and check dispatch are one line each, as world, findings and notes are, keeping the crate at its 2000 lines with raea fingerprint in it 2026-11-12 18:21:27 -08:00
shinyobjectz 6f253b3fe5 FP5a, FP6b, FP6c, FP6e, FP8c, FP14c, FP14e: raea fingerprint pair WORSE BETTER records a pick or a hand edit as a pair, fit Bradley-Terry and held out by project, and an axis with pairs and no labels is ranked by them alone; versions makes weak pairs of noted moments the next version changed and nobody noted again; profile takes the ranges work you admire spans (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside, where and which way; read has a fresh session read a project's pinned notes into kinds and axes, readings puts them to you in the app and tallies your answers, and learn-notes trains on them only once you've agreed with 45 kinds and 40 axes in 50; reembed moves evidence to this machine's encoders where its media is found, each row keeping the pin it was embedded on; new --kinds --tags writes where a fingerprint applies; bootstrap leaves gaps and clipping out of windows too quiet for them to change. Scoring, the sheet, which, diff and profiles move to raea-sys-fingerprint-use, keeping raea-sys-fingerprint under its size. The guide (docs/manual/guides/fingerprint.md) and every new flag in the CLI reference 2026-11-12 18:14:51 -08:00
shinyobjectz 64dfd63cd7 FP2e, FP4b, FP6a, FP6d, FP8a, FP8b, FP14b, FP14c: a test that word heads score the spike's noise and clipping from words alone (0.987, 0.975); every mechanical axis carries a cheat (darkened half as much, a white flash, a gap a third as long, clipping a third as hard, beside the de-rez sharpened after, half glow, quiet noise and a zoomed freeze); raea fingerprint approve makes approved work clean on every axis away from its notes; another eye's readings teach a head but never count toward its gate; a project's or workspace's fingerprint keeps its evidence a folder a person and each machine trains its own heads (raea fingerprint share); raea fingerprint diff A B lists the axes two tastes rank the same evidence most differently on; a fingerprint that extends another inherits its axes and evidence, its own labels counted twice and measured against each alone, an override learning from its own only and the parent never from the child; raea fingerprint which PATH and use NAME --in project|workspace pick the one that judges a piece (the project's that applies to its kind, its default, the workspace's, then the person's) 2026-11-12 18:14:51 -08:00
shinyobjectz fb11b58f6f FP1-FP4, FP14a: raea fingerprint. raea-sys-columns turns a video into one-second windows read by encoders that run on this Mac (SigLIP 2 for pictures, CLAP for sound, YAMNet for sound events, on ort; SigLIP never on Core ML's GPU), cached by content hash. raea-sys-fingerprint holds the taxonomy (each axis with its words, a fingerprint saying what it's for and what it builds on), the evidence ledger, small heads trained held out by source, scoring and the contact sheet. apps/fingerprint is the verb: new, bootstrap (known defects put into windows of real work), teach, score (--json, --sheet, --timeline), report, and a service that keeps the encoders loaded. raea check finds clipping, dropouts and flash frames as its own findings. sdk/raea types a fingerprint. 2026-11-12 18:14:51 -08:00
shinyobjectz f89873c1df FP14a: raea fingerprint in the CLI reference: its page under Check, each flag described, and the pages after it renumbered 2026-11-12 18:14:51 -08:00
shinyobjectz 853b6ab3dc FP0: Fingerprint, the plan and its spec: a taxonomy of axes with small heads over frozen on-device encoders (SigLIP 2, CLAP, YAMNet on ort; SigLIP on MLX once MX5 lands), trained from notes, marks, approvals and reference profiles, shared as evidence. FP0a-g hold the 11-12 measurements; FP1-FP13 are the build, with earshot (MIT) as the reference design 2026-11-12 18:14:51 -08:00
shaneandshinyobjectz a983349265 Release: ship only raea-skills' skill folders into share/raea/skills (#123)
raea-skills' skills/ is becoming its Claude plugin too (skills/.claude-plugin/plugin.json, hooks/, README.md,
icon.png), and release.sh copied that folder whole, so the installer, which copies every entry of
share/raea/skills into ~/.claude/skills, would have put the plugin's README, icon and hooks folder there beside the
skill. Now only folders holding a SKILL.md are staged, and _-prefixed ones (raea-skills' _template) stay out as
before. Tested on a mock skills/ with the plugin's files: raea/ alone is staged.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-12 21:11:42 -05:00
Luke, I am your fatherandshinyobjectz ea741f6bef Page: give Blitz its viewport in device pixels (a Retina window's interface sits in a quarter of it) (#120)
* Page: Blitz's viewport is in device pixels, so a page at scale 2 fills its image (#119)

a78fb95 gives the app window's page the display's scale. With a scale other than 1, raea-sys-page still gave
Blitz a viewport whose window_size was the page's size in points. Blitz's window_size is in device pixels (it
divides by hidpi_scale for the CSS viewport), as the page's image and paint_scene already are, so on a Retina
display the interface was sharp but laid out in the top-left quarter of the window.

Page::px is the page's size in device pixels, used for the image, the paint and the viewport.

Nothing changes at scale 1.

* Page: the page's JS and its element list read the viewport in CSS px, and devicePixelRatio is the page's scale

With Blitz's viewport in device pixels, two readers of window_size in runtime/dom still took it for CSS px.
snapshot sent it as vw and vh with dpr 1, so at scale 2 innerWidth and matchMedia answered twice the width the
page is laid out at; elements tested boxes against a window twice the size, so elements up to a window's width
off screen were listed as visible. Both read the viewport's logical size now, and dpr is its scale.

tests/viewport.rs: a page at scale 2 lays a 100vw x 100vh element out at its size in CSS px; scale 1 is as it
was; a fractional scale rounds the image up.

Rebased onto main at 6da2995: main's LR1 (7fb2194) moved the layout snapshot into raea-sys-page (systems/page/src/snapshot.rs, snapshot_by, which a composition's page.layout answers too), so the vw, vh and dpr change is made there, and elements.rs re-exports it.

* Page tests: q and attr live in tests/common, which vars.rs and viewport.rs both use, not one copy each (dupes back to 293)

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-11-12 19:48:36 -05:00
shinyobjectz 5d181dae28 Skills: raea-skills 803dd07, files.md says the default workspace folder as raea picks it (~/Studio where workspaces already are, else ~/Documents/raea, or ~/raea when iCloud keeps Documents), as SKILL.md does (raea-skills #29) 2026-11-12 16:40:16 -08:00
shinyobjectz bb7e6716b4 raea's own commits name their author when git has no user.name: a Linux account with no full name (CI's runner, a container) failed every one with "empty ident name ... not allowed", so a new workspace was never made there (main's CI: workspace tests' a_new_workspace_and_project_have_the_layout on ubuntu-24.04). As git_cmd gives a fresh Mac an EMAIL, it names the author and committer for the account, only when no user.name is set 2026-11-12 16:35:10 -08:00
shinyobjectz 6cb250a531 Tutorials: Libraries and Share work for review name their tutorial in their front matter, as the other eight tutorials do, so raea.io's docs show each one's walkthrough player (its voiced script is already made) and step to it in the tutorials' order 2026-11-12 16:32:02 -08:00
shinyobjectz 99e3fe0751 Tutorials: Publish and the tour name YouTube, LinkedIn or Bluesky, the networks anyone can connect today
Shane, 11-11: "sync all publishing to the current status state". TikTok and Instagram wait on their app reviews
(raea-api's CONNECTIONS_LIVE), so the pages name live ones; the narration was re-voiced to match in the private repo,
and raea.io's v0.1.1 build lays these two pages over the release's docs until main carries them.
2026-11-12 16:32:02 -08:00
shinyobjectz ebff73dbc6 LR6, LR7: the canvas's text natives (measure, advances, svgText) are each a function of the fonts (raea_sys_canvas::TextNative), registered from one table and given the page's fonts by with_page_fonts, instead of three wrappers that did it alike; canvas.read's rectangle and svgText's tracking read without closures that copied raea-runtime-sound's (dupes back to 293/59)
Skills: SKILL.md's 7. Deliver (sources: runtime/export/src) checked, still true: the export's change only passes page.layout's request through.
2026-11-12 16:26:53 -08:00
shinyobjectz 734b172d34 LR8: done, 11-12: ResizeObserver from the page's layout, the silent observers, holds in passes that draw nothing, and the harness's Chrome that renders 2026-11-12 16:16:09 -08:00
shinyobjectz b30eb6aa88 LR7: done, 11-12: document, createElement, ranges, svg text measures and URL faces, as built and measured 2026-11-12 16:16:09 -08:00
shinyobjectz fb4572f284 LR6: done, 11-12: measureText and getImageData from the page's fonts and pixels, as built and measured 2026-11-12 16:16:09 -08:00
shinyobjectz eb8d3ad795 LR5: done, 11-12: el.style's writes and getComputedStyle's page values, as built 2026-11-12 16:16:09 -08:00
shinyobjectz 203c26621c LR10: the harness: the runs both sides make, and a Chrome that renders. An inline <svg>'s words are runs of their own, one per <text>, in the render manifest (from the svg's usvg tree, mapped onto the page) and in boxes.ts, where they had fallen into the nearest html box: drop-line's 'then ships the film t h e n t h e n'. Words hidden by visibility, a measuring copy, are skipped on Chrome's side as the manifest skips them. Chrome renders each frame in real time through Playwright (bench/layout-reads/chrome.ts, the same pinned Chrome for Testing): a headless --dump-dom under --virtual-time-budget runs no rendering step, so a component's requestAnimationFrame and ResizeObserver never ran on Chrome's side. probes/document.tsx (getComputedStyle, svg text, a Range, a node made and measured, word- and letter-spacing) and probes/observe.tsx (ResizeObserver) are new 2026-11-12 16:16:09 -08:00
shinyobjectz a5d89e95c1 LR7: a composition's document, with LR5's style and LR8's observers. LR5: el.style reads and writes the element's style (writes send an update op; React's next commit to the property wins), and getComputedStyle answers from the page's computed style: page.layout takes { styles: [ids] } and the snapshot carries s: {id: {property: value}} for them, as stylo serializes it (engine/page read.rs computed_style), kept until the next commit (page-layout.ts computedOf). LR7: document has body (the composition's surface, the element the page draws from), documentElement, getElementById, querySelector(All), createElement (appended into the composition it's laid out and measurable, removed it's gone; a canvas is an OffscreenCanvas), createTextNode and createRange: a Range over a text node is its characters laid out in the parent's computed font, placed where the parent's line starts. An svg <text> has getComputedTextLength, getNumberOfChars, getStartPositionOfChar, getEndPositionOfChar and getSubStringLength, laid out by usvg in the element's computed font (canvas.svgText: family, size, weight, letter- and word-spacing, font-variation-settings). document.fonts loads a family the composition asked for (fonts.load), and a FontFace given by URL is fetched through raea's cache into the faces an svg's and a canvas's text are set in (fonts.face). window is globalThis with innerWidth, innerHeight, devicePixelRatio and getComputedStyle. LR8: ResizeObserver calls back after a commit whose layout changed an observed element's size, and once on observe, with contentRect, borderBoxSize and contentBoxSize; while a delayRender hold is open it checks every 16 ms, as a browser renders while a page waits. MutationObserver and IntersectionObserver exist and never call back. A pass that draws no page (the sound pass, the 3D rows' pre-pass) answers reads with a 0 x 0 page, and its holds are released (page-layout.ts noPage): a hold waiting on a measure could never end there. probes/document.tsx and probes/observe.tsx match Chrome within 1 px 2026-11-12 16:16:09 -08:00
shinyobjectz 37fc50782d LR9: holds released as Chrome releases them. A composition holding its frame until an <img>'s onLoad is released: the load is told on the turn after the img is made or its src changes (sdk/raea dom-load.ts), through the host's events, as Chrome fires it once the picture is in (the page holds the frame for the picture itself). A hold released from requestAnimationFrame (two rAFs after a ref lands) is released: while a delayRender hold is open, rAF's callbacks run every 16 ms with the held frame's time (frame-globals.ts), as a browser keeps rendering while a page waits; <R3F>'s own hold doesn't pump. channel-thread, logo-collapse and pulsing-border, which LR9's real holds had stopped, pass again. settle.rs's held flag is set once per turn (no dead initial value) 2026-11-12 16:03:05 -08:00
shinyobjectz 34629d33b8 LR6: a composition's 2D context measures and reads back. measureText is the text shaped by usvg as the canvas draws it, in the page's fonts (canvas.measure: width, actualBoundingBox*, fontBoundingBox*, from the alignment point), and getImageData reads back what was drawn (canvas.read); raea-runtime-canvas serves both as natives, which @raea/ui's wire reaches through the composition's __ui_sync (sdk/raea canvas2d.ts). putImageData writes its pixels as they are (a put op). OffscreenCanvas is a canvas no page shows. raea's bundled faces (Inter and the rest) now reach usvg's font database too, so a canvas measures and draws them, not a fallback. probes/measure.tsx matches Chrome: width exact, ink and font box within 0.8 px, pixels read back equal 2026-11-12 16:02:32 -08:00
shinyobjectz 6da2995575 Layout L1: lint.rs's outside-import hint formats the shared path where it says it, so no closure copies direction/world.rs's (dupes back to 293/59) 2026-11-12 15:31:36 -08:00
shinyobjectz c7e857b243 Layout L1: the CLI crate back to 2000 lines (component and part's checks in one), workspace_of is shared_of (the loader only wanted shared/, and it duplicated godot_run's nearest_project), and the manual's raea component page (Projects group, --shared and --force described) 2026-11-12 15:19:50 -08:00
shinyobjectz 657664d7d9 Skills: raea-skills 8c6225c, the reference and SKILL.md for LY1-LY4 (project new's folders, @shared/); also brings in #46 (findings) and #47 (hold) already on raea-skills main 2026-11-12 15:13:33 -08:00
shinyobjectz cb87e0cd59 Layout LY1-LY4: a project's compositions/, components/, controllers/, assets/ and artifacts/, and the workspace's shared/ (docs/layout.feature)
Shane 11-12: reorganize the default project around compositions, components, controllers, assets and artifacts, with a workspace library any project can call on. It's named shared/ and @shared/ so it isn't confused with raea's media libraries.
- LY1: raea project new makes the five folders (each with a .gitkeep), out/, brief.ts, AGENTS.md and a tsconfig mapping @shared/* to the workspace's shared/. raea workspace init makes shared/ with the same five, and .gitattributes keeps assets/** and out/** in LFS.
- LY2: the engine's loader resolves @shared/<kind>/<name> by walking up to .raea/workspace, with a relative import's extensions and index files; outside a workspace it's refused with what to do. PJ8's lint takes @shared/ imports and names @shared/ as the fix for a climb into shared/.
- LY3: the scan reads compositions from compositions/ and components from components/ (and from shared/), lints a composition elsewhere as misplaced, says once that a project is in the old layout, and reads controllers as the project's over shared/controllers/ by id.
- LY4: raea component list/add [--shared] replaces raea part, which still answers this release.
2026-11-12 15:07:16 -08:00
shinyobjectz b3fe2699d0 LR9: "raea" exports delayRender(label?, { timeoutInMilliseconds }), continueRender(handle) and cancelRender(error) on the frame hold <R3F> already uses: the frame isn't marked done while a hold is open, and the last release draws it, so a composition that measures after a font, a fetch or a timer has that frame taken, not the one before. A hold not continued within its timeout (30 s) fails the render naming its label; cancelRender fails it at once, as a throw does. Settle lets a held frame wait up to HOLD_SECS (120 s) instead of failing it at its 20 s stall guard, so the hold's own named failure comes first. probes/hold.tsx sets its words after a timer under a hold and matches Chrome; a never-continued hold fails in 2.6 s naming it. The manual has its page (reference/sdk/hold.md) 2026-11-12 14:45:00 -08:00
shinyobjectz 8a2f9c78ab LR4: a composition's refs have the tree a web component walks and queries: children and childNodes, the first, last and sibling nodes, parentElement, tagName, nodeName and nodeType, id, className, classList, dataset, getAttribute, textContent, contains, matches, closest, querySelector and querySelectorAll, answered in JS from bevy-react's committed instances (sdk/raea's dom-tree, installed from the entry with dom-reads). Selectors cover tag, *, #id, .class, attributes, descendant and child, comma lists, :first-child, :last-child, :only-child, :nth-child and :not; anything else throws a SyntaxError, as Chrome's does. el.id is the id attribute as on the web: the bevy-react patch renames its reconciler id to nodeId, and canvas2d, dom-reads and useEntity read that. probes/tree.tsx prints every answer and matches Chrome's words 2026-11-12 14:26:20 -08:00
shinyobjectz 2d869d719b LR3: a composition's refs have the geometry a web component reads, from the page that draws the frame: getBoundingClientRect (a DOMRect, transforms included), getClientRects, offset* and offsetParent (untransformed, whole px, from the positioned ancestor's padding edge), client* and scroll*, each as Chrome answers it. bevy-react 0.8.1 gets a patch (sdk/react/js/patches, applied by bun install) that makes its instances a tree, BevyElement and BevyTextNode with their parent, children and committed props; sdk/raea's dom-reads puts the reads on BevyElement from the entry. #54's repro now puts "here" where Chrome does (x 342, was 0), and probes/geometry.tsx prints every read and matches Chrome's words. The bundle crate's stylesheet url() rewriter moves to raea-runtime-cssurls to leave it under 2000 lines 2026-11-12 14:18:19 -08:00
shinyobjectz 272b94e765 LR1: a pass with no page answers through layout::nothing_drawn() (one closure, not one per caller), and the two new crates have their layer (runtime) 2026-11-12 14:13:01 -08:00
shinyobjectz ee171c4f85 LR1: room for the layout reads in crates at their 2000-line limit. Matchmove (raea track, matchmove.solve) moves out of raea-runtime-react into raea-runtime-track, which react re-exports as scene::track; the frame pages' asset writer (store_page, store_clear, the writer pool) moves out of raea-runtime-export into raea-runtime-pagestore. page-layout installs itself on import, so the entry adds one line. A pass with no page answers NOTHING_DRAWN, and wait_flush takes the runtime's ask. page-layout and dom-reads are installed by the entry, so the manual's and the skill's references skip them as they skip canvas2d 2026-11-12 14:09:19 -08:00
shinyobjectz 7fb2194503 LR1: A composition reads its layout synchronously from the page that draws its frame (#54). Its JS asks page.layout and blocks; settle wakes on the ask as on a flush, applies the commits already sent, and the host lays its page out at the frame's time and answers every element's boxes at once, keyed by React id: raea-sys-page's snapshot (now runtime/dom's too), with offsets from blitz-dom's offset_rect and offsetParent. settle_with takes the host's answer; plain settle says the host lays no page out. Each runtime has its own ask (a render's 3D pre-pass and a bake's workers run beside it). The still, 3D and fed renders answer from their page; the sound pass and the 3D rows' pre-pass answer no boxes. sdk/raea's page-layout keeps the answer until the next commit or frame, so a composition that never reads makes no snapshot 2026-11-12 13:54:53 -08:00
shinyobjectz fc7bfa3a0c LR0: bench/layout-reads, compositions that measure their text and layout against headless Chrome: check.sh runs a corpus (modules exporting Comp, conf and props) at its first, middle and last frames in raea and in Chrome (React DOM in raea's Clock, mounted once its fonts are in), and compare.jq pairs their text runs by words (raea's manifest against boxes.ts, made the same way), box and ink within 1 px. probes/ is raea's own corpus, #54's repro first ("here" at x 0 where Chrome puts it at 342); snapcn's 33 run through the private tree's adapter. The baseline, recorded in docs/layout-reads.feature: 3 of snapcn's 33 pass (all hold-only); 13 of the 27 that measure throw and the rest drift up to 87 px 2026-11-12 13:42:42 -08:00
shinyobjectz 593ebb5226 LR0: Layout reads, the plan (docs/layout-reads.feature): compositions measure text and layout as Chrome does (#54), answered synchronously from the Blitz page that draws the frame; LR0 the snapcn harness against headless Chrome, LR1-LR2 the layout call and every host, LR3-LR8 the DOM on refs and document, LR9 delayRender, LR10-LR11 the bar, docs and the issues 2026-11-12 13:42:42 -08:00
shinyobjectz 97e03e7447 The black-frame warning reads only elements' boxes: asking a text node for its bounding rect panicked in blitz-dom (transform on a text node), so a render whose frame drew black twice crashed whenever near-black words came before anything with a colour of its own (snapcn's text-build and text-swell, 11-12). bench/black-frame gains RAEA_BLACK_FAULT=3 (every draw black, the canary healthy: the render warns, naming what the page shows) and a text-first case that panicked before this; regression from 559d8274e (#96), which isn't in 0.1.2's rc3 2026-11-12 13:21:04 -08:00
shinyobjectz 559d8274e0 A frame that comes out all black though its page shows something is a warning, said once over its run of frames (#96)
A frame black on two draws whose GPU passes its canary was kept as the scene's black with one stderr line, and every
later black frame was let through silently: #96's 4K handover lost frames 22-29 that way, the render reporting
success. Now, when such a frame's page shows something that isn't black, the render warns "black-frame" naming it
and where it's written ("frames 22-29: drew all black on two draws, though the page shows a rgb(34, 34, 34)
background (handover.tsx:31:3)"), in the run's findings: stderr, the manifest, the summary's count and raea check's.
A page that is black (a black background, nothing on it) says nothing, as before.

raea-page's visible_paint finds it: the first element shown on screen, not a video's holder, whose background or own
words' colour isn't black, with its source stamp; it shares the manifest's opacity and stamp walks, now functions of
their own. raea-core-facts' said_frame joins a frame's finding to the same one running on the frames just before it,
so a run prints one line and counts once. Both black checks of the page path call it (bevy_frame.rs's still and video
frames, render.rs's page over 3D). Left out, as on the issue: a fed MP4's frames, which never come back to the CPU.

RAEA_BLACK_FAULT=3 draws every frame black with the canary passing (a draw dropped whole, as #96's was), to test it.
Checked: a #222 page under that fault warns once over frames 0-5, the manifest holding one finding with frames [0, 6];
a black page under it says nothing. Test: said_frame merges a run and starts another after a gap (the two tests that
say and take findings hold one lock).

Skills (SK4): SKILL.md's "7. Deliver" names runtime/export/src and says nothing of black frames: checked, still true.
2026-11-12 12:49:42 -08:00
shinyobjectz 645b0853cc Compositions get the web's canvas 2D context, requestAnimationFrame and Image (#55, #56)
A <canvas> ref's getContext("2d") in a composition was bevy-react's recording context, whose API isn't the web's
(no fillRect, setTransform or createImageData) and whose draws nothing in raea reads: snapcn's dot-bloom and
orb-swarm threw, and a canvas drew nothing. sdk/raea's canvas2d.ts gives it @raea/ui's CanvasRenderingContext2D, the one
an app page has, whose display list goes to the element as its __canvas2d prop, which the page already draws into
the canvas's bitmap (systems/canvas). The context sends through the host's own _send when it has one (sdk/ui
paths.ts, context.ts). bevy-react's handle keeps no props, so a canvas's width and height (300 x 150 unset) are read
from the batches the bridge sends through the host's op_flush; set on the ref, they go to the element and clear the
bitmap, as in a browser. getImageData reads zeros in a composition (no host to read back from).

frame-globals.ts installs requestAnimationFrame, cancelAnimationFrame and Image where they're missing (#56). A callback
runs once, at the frame after it was asked for, given that frame's time (f * 1000 / fps), so a frame drawn again gets
the same calls: from the React entry's frame step and the live entry's draw. Image's load fires on the next microtask
once its src is set, so a preload resolves; it reports no pixel size.

The bundle pointed @raea/<package> imports only at packages listed whole; a module listed alone (@raea/ui/canvas, as
@raea/ui/plugin is) now resolves too (rewrite.rs point_sdks).

Checked: a composition drawing red, then lime under setTransform(1,0,0,1,50,50), draws both where Chrome would;
canvas.width reads its width prop (200), createImageData(2,2) is 2x2, rAF's time at frame 5 is 166.67 ms and an
Image's onload fires, across a 10-frame MP4. Tests: conformance/frame-globals.test.ts; point_sdks with @raea/ui/canvas.
2026-11-12 12:37:09 -08:00
shinyobjectz e165d0c4a8 Video with alpha (#113): a VP9 WebM's transparency and a ProRes 4444's are drawn, not refused or made opaque
A <Video> on the page was opened by the platform's decoder alone (Apple's on a Mac), which reads no WebM: a VP9 WebM
with alpha was refused, "no video track". The page now asks the backends in raea-io-media's order (RAEA_MEDIA's, the
platform's, the portable one, the ffmpeg CLI), as the other readers of video do, and says what each answered when
none opens it.

The ffmpeg CLI decoder read nothing under FFmpeg 8 and later, which took out -vsync: raea-io-ffmpeg's passthrough()
gives -fps_mode from 5.1 on (apps/check's flash test had that rule; it calls this one now). A VP8 or VP9 stream tagged
alpha_mode=1 is decoded with libvpx, named before the input (FFmpeg's own VP9 decoder drops the alpha WebM keeps beside
the picture), where this FFmpeg has it. ffmpeg's stderr is kept for a read that fails and out of the run's output.

Apple's decoder made every pixel's alpha 255. A track whose format description says it carries alpha (ProRes 4444 at
depth 32, HEVC with alpha) keeps VideoToolbox's: straight, as checked on a ramp from 0 to 255 over blue (63/192,
127/128, 190/65 at a quarter, half and three quarters).

Checked on the issue's files, a red circle on nothing over a blue page: WebM and ProRes give a blue corner and a red
centre (were refused and red); a 30-frame MP4 from the WebM holds that on every frame read; a plain H.264 is unchanged.
Test: raea-io-ffmpeg's vp9_webm_keeps_its_alpha (skips without ffmpeg and libvpx), now in CI's list.
2026-11-12 12:14:24 -08:00
shinyobjectz d1e61bee2b render --alpha: a frame with 3D is transparent where nothing is drawn, as a 2D page is (#114)
The 3D camera already cleared to #00000000 under --alpha (program.rs), but bevy_over_3d, which lays the page over the
3D for PNGs and transparent movies, set every pixel's alpha to 255 (the 3D taken as over black), so an <R3F> or a
native 3D scene came out opaque black around it and setClearColor(x, 0) had nothing to reach. Under --alpha the 3D's
own alpha is now laid under the page's by the same SrcOver as its colour and the premultiplied result made straight
(scene_straight); the page alone, a 3D slot and a camera in a page element keep their alpha too. program.rs's note
that frames with 3D come out opaque is gone. Checked on the binary at 320x320: the report's <R3F> box with
setClearColor('#000', 0), a native Camera3d box and a camera inside a positioned element all write alpha 0 in empty
corners and 255 on the box, a transparent .mov likewise, and a render without --alpha is unchanged (Bevy's 43, 44, 47
clear, opaque).

Skills (SK4): SKILL.md's "7. Deliver" names runtime/export/src; neither it nor the 3D pages say 3D is opaque under
--alpha: checked, still true.
2026-11-12 11:58:27 -08:00
Ragul Sundaram 875006089f r3f: three peer range >= 0.180.0 (HDRLoader first ships in 0.180) (#118)
src/three/scene.ts imports three/examples/jsm/loaders/HDRLoader.js, added in three 0.180; with three 0.170-0.179,
inside the old range, every <R3F> scene fails to bundle.
2026-11-12 14:45:59 -05:00
Ragul Sundaram 163f0b9e00 R3F: an opacity outside [0, 1] is clamped, as three draws it, instead of throwing (#117)
An easing that overshoots (bezier(0.34, 1.4, 0.64, 1)) gives a material opacity of 1.03; three clamps it when it
draws, but the bridge handed it straight to raea's MeshBasicMaterial, whose check threw RangeError. The bridge now
clamps opacity before converting.
2026-11-12 14:45:55 -05:00
shinyobjectz 76a4ef7885 A still no longer prints 54 CommandQueue warnings: the last frame's extract commands are applied before the engine goes (#89 item 7)
Bevy applies the extract schedule's commands in the next frame's render schedule. A still draws one frame and drops
the Engine, so each extract system went with its queue unapplied and bevy_ecs warned "CommandQueue has un-applied
commands being dropped" 54 times (lldb on the warning: the extract systems' FunctionSystemState, dropped with the
render sub-app's schedules from render_with). Engine's Drop now runs the extract schedule's apply_deferred on the
render world, as Bevy's apply_extract_commands does each frame. Checked on the binary: a still of the starter edit
prints no CommandQueue line, and a video renders with 0 findings. forward_render_diagnostics is written shorter to
keep raea-render within 2,000 lines.
2026-11-12 11:40:06 -08:00
shinyobjectz a185361869 A fresh raea init renders again: an <Audio> behind a condition isn't one the render must hear
The starter edit plays a sound-only cut with <Audio> (09ee78513, #89 item 2) on a branch that runs only when there is
one (`c.kind === "audio" ? <Audio /> : <Video />`). The render's silence check refused any edit whose bundle has an
<Audio> call and no sound, so `raea init` then `raea render edit.tsx` was refused before the edit had any cuts. The
check (raea_runtime_sound::always_plays_audio, its own file with a test) now counts only an <Audio> that always plays:
one behind `?` or `&&` is silent when its condition is false, as meant, while one in a wrapper's children
(`children: jsx(Audio, …)`, the <Mix> that dropped them on 10-18) is still refused. Checked on the binary: the starter
edit renders 90 frames with 0 findings, and an <Audio> inside a component that returns null is still refused.

Skills (SK4): SKILL.md's "7. Deliver" names runtime/export/src and says nothing of the silence check: checked, still true.
2026-11-12 11:32:27 -08:00
e90d70f0dc check: a card that shares one word with a line isn't held to it as a caption (#102, #89 item 3)
The cue rule anchored on any one word of weight within 2 s, so a card
sharing a single word with another line ("Wirestock x OpenAI Sora" against
"At Wirestock, I worked on...") was held to that word's time. A text now
counts as a caption only when at least half its words match the spoken run
in order, and a one-word card only within 0.75 s of its word. Words are
compared by the shared word_key, as the rest of the rule does. A caption is
still timed from its first word, so a card whose first word was said earlier
is still flagged, by design.

Part of #89

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: shinyobjectz <[email protected]>
2026-11-12 14:26:07 -05:00
shinyobjectz 6d8623ca9b Node's import.meta.url is written into each module, as import.meta.main is: macOS 15's JavaScriptCore left it undefined
createRequire(import.meta.url) then resolved packages from ".", so a tool requiring a package that way failed on
macOS 15 with "Cannot find package" (a newer JavaScriptCore gives the module's key, which is why it passed here).
raea-native's node test found it as soon as CI's unit tests ran it: the crates #90 added switch on raea-native's
modules feature, and before that the test compiled to nothing in CI. Each module's text now has import.meta.url as
its file's own file:// URL, the way node.rs already writes import.meta.main in.
2026-11-12 10:59:23 -08:00
shinyobjectz 2b8b43a420 raea check's flashing screen is a crate of its own, raea-app-check-flash, so the check has room for #89's fixes
apps/check was at its 2,000-line limit (tools/size.sh) with three of #89's items still to come. The screen itself
(Px, Swings, FlashScreen: WCAG 2.3.1's opposing swings in a frame's windows, from decoded RGB) is pure pixel maths
with nothing of the check's, so it moves to apps/check/flash with its six tests, unchanged; the FFmpeg side (the
decode, showinfo's exact times, the log's severities, the findings) stays in flash.rs. apps/check goes to 1,680
lines. CI's unit tests take the new crate too. And raea-render's log-filter comment is folded a line shorter: the
merge of #104 left the crate at 2,001.
2026-11-12 10:55:50 -08:00
Mattias HjemgaardandClaude Opus 5.5 ab0babcce7 log: the 3D camera is the shadow LOD origin, and bevy_time's warning is filtered (#104, #89 item 7)
* fix(log): a 3D camera that is the shadow LOD origin, and bevy_time's warning filtered

Every 3D run with a point or spot light warned that no entity has
ShadowLodOrigin (the scene camera draws into an image, so Bevy picked one
arbitrarily): the scene camera now carries the marker. bevy_time's "did not
receive the time from the render world" (raea drives Time by frame, with the
render world in step) is filtered out of stderr, in Bevy's log filter and in
raea_io_trace's logger; the event log keeps every record.

Measured on main 5b2c7731: a 3D still with a point light printed the
ShadowLodOrigin warning, now nothing; a 2D still printed bevy_time's line,
now not. The 54 dropped bevy_ecs CommandQueue lines on a 2D still are left as
they are: their source still needs finding.

Part of #89

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* check: keep raea-render under the size cap

The two new comments said in five lines what fits in three; raea-render
was 2 lines over tools/size.sh's 2,000-line crate limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-12 13:43:33 -05:00
shinyobjectz 09ee785138 raea cut takes a sound-only take (#89, item 2)
A take under media/ with sound alone (wav, mp3, m4a, aac, flac, aif, aiff, ogg, opus) was no take at all: `raea cut
take.wav --at 0-1` refused it, and a video's shot detection would have opened it as a picture. Such a take is listed
with the videos, cut on its words or spans as a video is, with no jump cuts to keep off and the edit's 30 fps grid; its
clips carry kind "audio" in cuts.ts (and no face is looked for in perception.json), and the project template plays
them as <Audio> under whatever the edit puts in their place. Found and shaped by SirSicard's report; items 3, 5, 6
and 7 stay open.
2026-11-12 10:32:22 -08:00
shinyobjectz 6f88437dc1 raea check: the safe-area rule tests a text's letters, not its box, and a missing taste file is a note (#89, items 1 and 4)
A centred line in a left: 0; right: 0 box was flagged in the left zone, since the rule tested the layout box, which
starts at x = 0. The render's manifest now records each text's ink (the lines' own extent, each laid by its alignment,
as a box beside the element's), and a run's per-frame boxes are its ink where that's recorded, its box on an older
manifest, so the clipped, safe-area and face rules measure the letters; the safe-area finding names the edge crossed
and prints what it measured. And --taste naming a file under the person's taste folder (RAEA_TASTE, else
~/.raea/taste) that isn't there yet prints a note and checks without it, as the skill's standing
`--taste ~/.raea/taste/taste.ts` does on a machine with no taste file; any other missing path still refuses.
findings_of and Probe::of are written shorter to keep the crate within 2,000 lines. Item 2 is the next commit; 3, 5
and 7 stay open (6 is in the docs already). Diagnosis and shape from SirSicard's report.
2026-11-12 10:32:22 -08:00
shinyobjectz 6e79971b12 CI runs the tests of the crates that need no GPU or media device, and two of their tests hold on any build (#90)
ci.yml's unit-test step tested three crates; the brief, K, bundle, check, workspace, tools and targets crates join it,
with debug info off for the test binaries (with it they filled 27 GB of a runner's disk). Two tests only passed by
accident of the build: the bundle test's fake SDK sat where the resolver no longer looks (it reads sdk/tsconfig.base
.json's paths since S1d), so it's laid out as the real one with that file; and the workspace's literal test depended
on serde_json's key order, which a crate built alongside (raea-cli) turns into insertion order through preserve_order,
so its lines are held as a set. Found and shaped by SirSicard's report.

Skills (SK4): SKILL.md's "2. The workspace and its projects" and "3. Read before you make" name apps/workspace/src,
where only its tests changed: checked, still true.
2026-11-12 10:32:04 -08:00
shinyobjectz 11dab02b51 Page: getBoundingClientRect stops at a freed containing-block link and answers a zero rect under display: none (#108)
A containing-block link is what the last construction and layout left, and freeing a node doesn't clear links to it:
after a display: none clip's anonymous blocks were freed, measuring one of its descendants panicked on the stale key
(invalid SlotMap key), which an HTML composition hit through its script's getBoundingClientRect. The two geometry
walks and inline_root_ancestor now stop at a missing node, as the paint tree's walk does, and an element in a display:
none subtree answers Chrome's zero rect rather than a rect measured up to the stale link. Cause read by Razepriv in
#108; the same family as #24.
2026-11-12 09:55:56 -08:00
shinyobjectz 6177e27d51 Encode: the RGB to NV12 step dithers through a 4x4 Bayer threshold, so dark gradients stop banding in 8-bit H.264 (#87)
nv12.k and nv12buf.k rounded half up into limited range (220 levels of 256), so a slow dark gradient merged into
bands and blotches that raea check flagged on every sampled frame of a 1080p60 fog shot. Each sample now rounds
through the Bayer threshold of its pixel (a chroma pair's, of its block's top-left), fixed by position, so play and
render agree and nv12_cpu (the CPU render) stays bit-equal: core/k/tests/nv12_dither.rs runs both kernels through the
interpreter against it, and holds a flat dark grey's mean. Samples are clamped to the nominal range (luma 16..235,
chroma 16..240), since 220/256 overshoots 219/255 and the dither would have put some white on 236. The report's
dark-gradient repro goes from a blotching error on 2 of 2 frames to clean, at 2.98 MB instead of 0.64 MB for its
4 s: the encoder keeps the gradient it used to flatten. Diagnosis and shape from SirSicard's report.
2026-11-12 09:55:54 -08:00
shinyobjectz a78fb95e75 raea's window: the page is painted at the display's scale, so a Retina window is sharp
v0.1.1 laid the window's page out at scale 1 and stretched its image over the window: on a Retina display every
glyph and hairline was drawn at half the pixels (a bug report of 11-12: "UI renders at 1x on Retina", the blur and
pixelation people noticed). page.rs size() now gives the page the window's scale factor along with its size in
points, read each frame so a window moved to another display follows; headless, the image target's scale stands.
RAEA_WINDOW_SCALE=2 opens the window at that scale on any display, to check it on a 1x Mac. tests/retina.rs covers
the scaled window and the headless case.
2026-11-12 09:47:09 -08:00
shinyobjectz be220a6064 Page paint: a filter of opacity() functions alone is drawn as the layer's alpha, not as an atlas image (#96)
Every filtered element is an image the size of its box in Vello's atlas (8192 px a side). Two overlapping scenes that
each stacked six full-frame <Freeze> layers under filter: opacity() (a motion blur) at 2160x3840 asked for twelve such
images, more than the atlas holds, so the frame was drawn without them: on 0.1.0 silently, on main as a refusal. An
opacity() filter scales the group's alpha exactly as the opacity property does, so it now folds into the layer's
alpha and needs no image. The report's composition draws its frame 26 at 4K; the filter-functions, opacity and
backdrop-filters parity cases match Chrome as before.
2026-11-12 09:07:31 -08:00
shinyobjectz 7fb6251bf9 Page layout: an inline box is laid out in full while its line is only measured, so a relayout keeps its baseline (#109)
Taffy's measure cache keeps a box's size without its baseline. On a fresh layout every inline-block missed the cache
and its baseline came along; once one span's transform changed, the title's other spans came back from the cache
baseline-less during the measure pass, sat on the line by their bottom margin edge, and the line measured taller by
the font's descent: a per-character spring title jumped 24 px and the block under it 25 px on the frames one span's
value left zero. Blitz already asked for a full layout of inline flex and grid boxes for the same reason; now every
inline box gets one. Checked with the report's composition: the accent line stays at the same row on every frame,
in either render order. The parity case p12-css/inline-block-transform-relayout toggles one span's transform and
holds the block under the title against Chrome.
2026-11-12 09:07:30 -08:00
shinyobjectz 5d320bc96e Live 3D: a mesh's emissive colour is sent the frame it changes, with its strength (#106)
A video draws its 3D live, and a mesh's row keyed only the emissive strength, and only where the first frame glowed:
a part dark on its first frame stayed black for the whole video, and a change of hue was ignored (stills were
right, since their first frame is the frame). The full path now sends the colour whenever it differs from what was
sent (none is black), with the strength (0 once black); the fast path hands such a frame to the full one, and its
strength rule reads the sent colour, not the first frame's. runtime/live/tests/live_emissive.rs steps a ball from
dark to blue to orange to dark, under RAEA_LIVE3D_CHECK.
2026-11-12 09:07:30 -08:00
shinyobjectz 3de2c63bab 3D: a Cone's picking bounds span its height, not twice it (#98)
boundsOf passed the cone's full height to box(), which takes half extents; the cone is drawn centred on its origin.
Found and diagnosed in #98. events3d.test.tsx checks a radius 0.5, height 2 cone's bounds.
2026-11-12 08:32:11 -08:00
shinyobjectz c89de2a778 canvas: arcTo draws the corner's short arc, as a browser does (#97)
Its ccw flag was inverted, so a right-angle corner drew three quarters of the circle through the far side. Found and
diagnosed in #97. sdk/ui/test/canvas-arcto.test.ts checks both turning directions and a four-corner rounded rectangle.
2026-11-12 08:32:06 -08:00
shinyobjectz d70c8e6604 Windows: every executable links with an 8 MB main-thread stack, not raea.exe alone (#112)
The desktop app's raea-page-host.exe kept Windows' 1 MB default and overflowed it inside a window callback
(0xc000041d) right after opening an MP4. .cargo/config.toml now passes /STACK:8388608 for both Windows MSVC targets,
so raea-page-host, raea-rune-host and raea-perceive match raea.exe.
2026-11-12 08:30:03 -08:00
shinyobjectz dfca0bcf12 Docs: raea's own servers index nothing for customers (docs/libraries.feature LB6b), so storage-and-search says indexing runs on your own computers again, and the API guide says a cloud upload is indexed by one of your linked computers 2026-11-11 19:46:40 -08:00
shinyobjectz 14870df064 Docs: sharing for review, libraries and the storage API. Two tutorials (share-for-review: a link anyone can watch and comment on, notes back to the agent, the next version on the same link, Review links, several files on one link, agents sharing; libraries: this Mac or the cloud, making one, search by what's in a shot, statuses, sharing from a cloud library, projects beside their code) and a guide to the API (who may call it: anyone on Pro or Team; agent keys and their scopes; libraries, search by meaning or by words, files, uploads, the trash, review links). storage-and-search says libraries stay on the Mac unless made in the cloud, and where indexing runs 2026-11-11 19:18:57 -08:00
shinyobjectz 6ba881cf0f R6e, R6f, R6g, R6h: the Library's review work is built. R6h: the projects saved to raea are listed under Projects in the Library's column, each its own cloud library over the project's folder (search, statuses, review links), with where its code stands above it (its GitHub repo and Pushed, or commits to push and to pull and changes in its folder) and one press to make the library; R6e to R6g take their @done tags 2026-11-11 19:01:47 -08:00
shinyobjectz de994972cd R6g: several files on one review link is built (a cloud library's picked tiles shared from a bar at the grid's foot; the set's page lists each item's own link; Review links lists the sets with Copy link and Stop sharing); R6h keeps what isn't: a library of a workspace's projects' cloud copies and synced code 2026-11-11 18:46:17 -08:00
shinyobjectz 13daeb9976 R6e, R6f: a file's own status and sharing a cloud library's file are built in the feed (statuses as reserved tags with the grid filtered by them; Share for review in a cloud library file's panel, Mac-only libraries never sharing); R6g keeps what isn't: links of several items and a library of projects' cloud copies and synced code 2026-11-11 18:33:34 -08:00
shinyobjectz b7b777fc8a README for v0.1.1: the first full release, the desktop app on the Mac, Windows and Linux from raea.io (it tells you when a new version is out; the Mac's updates itself), and a release badge in place of canary 2026-11-11 17:25:41 -08:00
shinyobjectz b903c74e5c skills pin: raea-skills ae8002c, SKILL.md teaches raea findings (what every render and check found, read back from the project's record; --open for what still stands, --despite for what the person accepts) 2026-11-11 17:24:38 -08:00
shinyobjectz ab904156c6 Release promote: a release may carry newer skills and docs than its candidate (Shane, 11-11: "promote skills to the latest possible"). No build of the shipped binaries reads skills/ (the raea-skills pin) or docs/: release.sh packs the skills the release's commit pins, and its skills-passed line and check-cli hold them to the candidate's binaries. So v0.1.1 can go from rc5's binaries with the skills that teach the feed's sharing tools 2026-11-11 17:11:34 -08:00
shinyobjectz 1ac6f0b88f R4d: a side-by-side compare of two versions on a review link's page is built 2026-11-11 16:49:51 -08:00
shinyobjectz 550b2b836d R6c: a file out for review says so in a library's tiles and search hits, and its panel opens the link in Review links; R6e keeps a status the person sets on any file as not built 2026-11-11 16:44:36 -08:00
shinyobjectz 27e54e954f R6: the Library in the review spec. Review links leave Settings for the Library's own board (R4a, R6c); guests' comments sync to the item as edits and the reviewer sees Done in vN (R4c); invites and shared projects live in the Library's Shared with you (R5b, R6d); Open in raea clones a shared project into the sidebar (R5d); R6 the Library: one column with Search by meaning across every library, Review links by state, Shared with you and the libraries, and what isn't built yet 2026-11-11 16:38:18 -08:00
shinyobjectz a3241af2b5 skills pin: raea-skills 68aca5a (PR 45), which teaches the feed's sharing tools and regenerates reference/feed.md 2026-11-11 16:04:01 -08:00
shinyobjectz c9e5a20c6b R4, R5: review links are Pro's and Team's and built (the Share button, Settings → Sharing, the agents' share tools behind Let agents share); R5 is collaborators on Team: invite by GitHub username or email, accept in your own raea, GitHub's invite too, remove; what isn't built yet is said in each scenario 2026-11-11 16:00:16 -08:00
shinyobjectz 8d111c6f5b Release promote: a release can go as soon as the Mac's candidate archive is out (Shane, 11-11: "once mac is ready we can go live too"). tools/release/promoted-bins.sh waits for a platform's candidate archive (and its .sha256) while the candidate's own release run is still building it, every two minutes, and fails at once when that run has ended without one; so v0.1.1's Windows job promotes rc5's zip as soon as rc5's windows-verify attaches it. Tested: rc5's Mac archive, still building, is waited for; rc4's Mac archive, built by the release-disk branch's dispatch, is refused by the attestation check (source ref refs/heads/release-disk, not the tag) 2026-11-11 15:10:21 -08:00
shinyobjectz f96fdda16a Release: promote a candidate instead of compiling again. A release whose code is an rc's (only the README, the workflows and the release tools may differ) is that rc's attested binaries packed again as the release: raea's version isn't compiled in (release.sh writes share/raea/VERSION; rc3's five binaries hold no "0.1.1-rc3"), so what ships is what the rc's checks ran, in minutes instead of a three-hour cold build. release.yml reads the tag's "promoted-from: <rc>" line (or the promote_from input; none builds from source) through tools/release/promoted-from.sh, which refuses, naming the files, when any code differs; each job then takes the rc's archive for its platform through tools/release/promoted-bins.sh (sha256, and gh attestation verify against release.yml and the rc's tag), its symbols from the rc's run, and packs, checks, attests and attaches as before. release.sh keeps a promoted Linux binary's carried symbols instead of stripping it twice. dry_run (by hand) packs and checks without attesting or attaching. Tested: rc5 against main passes the code check and rc4 is refused with its files; rc3's Mac archive downloads, verifies and unpacks 2026-11-11 14:55:54 -08:00
shinyobjectz 619816627e The manual's SDK reference from the SDK as this stack leaves it (bun tools/manual-ref/sdk.ts gen): an inline FramePass's uniforms are each frame's own (3d, post_process), a controller is a standing decision (brief), and Nudge places by scale, rotate and opacity too (raea) 2026-11-11 13:50:13 -08:00
shinyobjectz 0295020a39 skills pin: raea-skills d63c30a (PR 44), 3d/solari.md and 3d/water.md copied from the guides this stack adds 2026-11-11 13:34:02 -08:00
shinyobjectz 1e8b2e63dc CL10b: raea cloud on Cloudflare Containers (sdk/cloud/deploy/cloudflare): a Worker in front of one container that sleeps when idle and wakes on the next request, its home folder kept in R2 through RAEA_CLOUD_STATE 2026-11-11 13:34:02 -08:00
shinyobjectz 67d2b3e3ea sdk/plugins bevy.gen.tsx regenerated: raea-sys-shader's OwnMaterial and OwnArrayMaterial are in the registry (3D, 2D and the sprite extension), 389 components 2026-11-11 13:34:02 -08:00
shinyobjectz 1be0cc4a5b Craft guides bevy/solari (ray-traced light: what it lights and traces, glowing lamps, rooms that do not leak, cuts, metering) and bevy/water (seas, lakes and pools: waves, reflection, refraction, absorption, caustics, foam), routed from bevy.md, their sources cited in NOTICE 2026-11-11 13:34:02 -08:00
shinyobjectz b861af80be A controller's doc comment (sdk/raea brief.ts) says what one is: a standing decision ("every ad is 9:16"), not one piece of work; the raea app shows a new one in the project's feed, and an agent brings one to the person with controller_post 2026-11-11 13:34:02 -08:00
shinyobjectz 4855d4da0f Nudge places a part by scale, rotate and opacity too, not only x and y (sdk/video nudge.tsx), with docs/editing.feature: the editor as live changes to the composition's code (E1-E5, from Shane's 11-07 notes; E1c, the Properties panel's scale and opacity, were dropped on save before) 2026-11-11 13:34:02 -08:00
shinyobjectz eb56911dd6 R3F (sdk/r3f) draws more of raea as three.js does: a <ThreeShaderMaterial glsl> is three's own ShaderMaterial, its uniforms and samplers set each frame (three/shader.ts), and a <BufferMesh> carries its own attributes for it; <Look mode="paint"> and cartoon paint in the surfaces (three/paint.ts, colours written through the inverse of three's ACES) and the frame pass only draws the cells; Grass is clumps of tapered blades by the engine's detail steps, made once per field; an HDR or EXR panorama lights the scene only once it has loaded (one still loading compiled every lit material's shader wrong, so nothing drew) and wakes every page that asked for it; a light inside a moved Entity moves with it; a Grade's top-level value is each section's unless the section sets its own; emissive_nits sets emissiveIntensity; meshopt-compressed glTFs decode; the composition's size is in whole pixels. kinds.ts gets rows for Skybox and Lightmap (engine: their .ktx2 files are ones three's KTX2Loader does not read) 2026-11-11 13:34:02 -08:00
shinyobjectz ddf9a6adef Skin up close: the micro tile's grain shades the colour too, a crease or pore darker with green and blue more than red (the blood under them shows; a grey darkening read as dust), as a photo's colour is a blur that close. The tile keeps its size on the skin by the mask's scale channel (skin_mask.png green, 0 on older bodies is 1). The wrap per channel no longer widens with curvature (sdk/character skin.ts) 2026-11-11 13:34:02 -08:00
shinyobjectz 4fe5eb115b A material re-covering a glb takes real transmission, ior and thickness (systems/material surface.rs): a glass or frosted-veil <StandardMaterial> over a glTF part drew opaque, since over() copied every given field but those three. Test: transmission_ior_and_thickness_re_cover_a_glb_material 2026-11-11 13:34:02 -08:00
shinyobjectz d730ef1cdd raea render -o out/a.mp4 (and --audio out/a.wav) makes out/ first when it isn't there (a project made by hand has none): the render ran to the end and then failed writing with "No such file or directory". apps/sound out_folders, at the top of raea_app_sound::render, which every render passes through first (raea render, and raea export capcut's parts); it replaces the sound render's own folder making. Test: a_render_makes_the_folders_its_files_go_in 2026-11-11 13:34:02 -08:00
shinyobjectz 52b9bb7f65 docs/review.feature R4: review links, proposed and Team only (decided 11-11). The person or their agent shares an item as a raea.io link; anyone with it watches and comments on the picture without an account; comments come back to the item and its agent as R1 comments and R3 edits; new versions replace the cut on the same link; a link is the reviewer's only right. On Free and Pro, Share says links come with Team. Not built, not in v0.1.1, with two open questions 2026-11-11 13:24:34 -08:00
shinyobjectz 7116d23eeb Tutorial: storage and search says what Pro is now, one computer whose libraries are searched on raea.io too, with Team's teammates searching the same media 2026-11-11 13:24:34 -08:00
shinyobjectz c5269af648 A UiTexture's image is the texture of any material map, not only the base colour (systems/material maps.rs): as the emissive map a panel glows and shows under Solari, which draws no unlit surface; before, emissive_texture={targetImage(...)} was refused as a missing file. Test: a_screen_image_is_the_texture_of_any_map 2026-11-11 13:24:33 -08:00
shinyobjectz a81a8a1e1e Solari leaves additive and multiplying surfaces out of its traced scene (engine/render/raytrace solari.rs): traced, an Add sprite was an opaque card, and a wind's dust and air streaks cut a sunlit wall's light by a quarter. They still draw, forward. A mesh whose material isn't made yet is decided on a later frame. Test: an_additive_or_multiplying_surface_is_not_traced 2026-11-11 13:24:33 -08:00
shinyobjectz 5aa10b955c An inline FramePass's uniforms follow the frame (systems/framepass, runtime/scene3d shaded.rs, sdk/render framepass.tsx): the SDK sends them as a keyed prop, as a pass as written's are, and follow() puts each frame's values in the pass's slots. Before, an inline pass kept its first frame's uniforms for a whole render, so a camera or a time handed to a raymarch stood still. A uniform keeps its first frame's type; textures stay the first frame's (a texture array's layer picked by a uniform changes what's read). Test: an_inline_pass_follows_its_uniforms_frame_by_frame 2026-11-11 10:14:34 -08:00
shinyobjectz cd6bb40834 BL37, GD9, GD12: the manual's CLI reference from the help as landed (tools/manual-ref/cli.ts gen): scene export with its --at and -o described, godot run's --scene and --frames, and setup godot trying raea's own build first 2026-11-11 10:13:46 -08:00
shinyobjectz a331bffd13 BL29, GD8, GD9: Windows and Linux on raea's own v0.1.1-rc4 builds, and setup blender finishes on Windows with uv. Linux (debian:trixie-slim): Blender and GodotJS's Godot installed and both smokes passed. Windows 11 from the release zip in an empty home: Blender's smoke passed, GodotJS's Godot installed and its smoke passed, and raea's own Windows Godot (sha256 as pinned, 4.6.1.stable.raea) passed it too, its typings the same text as GodotJS's (4 of 18 files CRLF there, LF in raea's). With uv on PATH, setup blender exited 1 there: the MCP add-on's installer prints an arrow Python can't encode for the cp1252 console; it now runs with PYTHONIOENCODING=utf-8 and PYTHONUTF8=1 (apps/tools blender.rs), and so run on that machine it installed the add-on and exited 0 2026-11-11 10:09:23 -08:00
shinyobjectz 0eda5dc0f5 BL36, GD11: register_natives in 6 lines, not 11 (the calls crate's own registration in the one list), so raea-runtime-react is 2,000 lines, within the crate limit 2026-11-11 10:03:01 -08:00
shinyobjectz ad4fbf6b35 skills pin: raea-skills 9832e02 (#43), the lane's guides (3d/blender.md, 3d/godot.md, sources, blend-files, godot-projects) and reference/cli.md with its verbs 2026-11-11 09:58:28 -08:00
shinyobjectz 848ff9471d BL36, BL37, BL38, BL39, BL40, GD9, GD11, GD12, GD13, GD14: status 11-11 with the evidence. Each command passed on a test scene (a crate, a metal ball, a pole, a floor, a sun, a point light and a moving camera): scene export 6 parts on 30 frames; blender open built the .blend in 5 s; blender back said each change at its TSX line and wrote the new box as a model; godot export 3 tracks over 30 frames; godot back the same; the shots 30 frames in their Sequence, a second render 2 s from the store; take.py and the scene-glb guide script on real files (Godot's 3d/platformer: 2,923 meshes). GD9: the three editors report 4.6.1.stable.raea, the Mac's notarized and stapled, Mac and Linux pass the smoke and the typings check; the zips' sizes and sha256 are godot.rs's pins, uploaded with the release's files 2026-11-11 09:57:46 -08:00
shinyobjectz dfb13e6ec9 BL37, BL39, GD9, GD12: eleven new duplicate groups folded or written plainly (tools/dupes.sh: L1 counted 300 exact and 64 near against main's 294 and 59). Godot's pins are six consts, not two closures building them; a material's numbers read one table of defaults; scene export counts instances in the loop that lists what doesn't cross; a track no longer returns early when every channel holds still (each channel is skipped then anyway); an edit pushes itself onto the list; a shot's flags are a map and --transparent a field. Tests: apps/engines (15), apps/interchange (9) 2026-11-11 09:50:25 -08:00
shinyobjectz 9ab4e05f86 BL36, GD11: <BlenderShot> and <GodotShot>'s native calls move to a crate of their own, raea-runtime-shots (runtime/shots), which raea-runtime-react registers: in runtime/react they took that crate to 2,202 lines, over the 2,000 limit. No change in what they do; the size and length a shot is asked for are whole numbers of 1 or more and its fps a number over 0, each said by name when it isn't. Tests: a_shot_is_keyed_by_what_it_is_made_from and the command's 2026-11-11 09:50:19 -08:00
shinyobjectz d4e23b602a BL40, GD14: open .blend files and Godot projects come into raea by the guide, and the Blender and Godot guides teach the round trips and shots. bevy/blend-files: contents.py lists a .blend's meshes, collections, node groups and materials; take.py writes named objects and collections as one .glb with modifiers applied and a licence sidecar, now linking each taken object's parents into its scene (glTF's export walks down from the top objects, so a parented object came out as an empty 132-byte .glb). bevy/godot-projects: godot/scene-glb.ts writes a Godot scene's meshes, materials, skins and clips as one .glb, its cameras and lights left behind and the tracks that moved them dropped (glTF's export reported them as an error); type-checked as sdk/godot/test/guide-scene-glb.ts and run on Godot's 3d/platformer demo (2,923 meshes). bevy/sources: the open libraries and their licences, routed from bevy/assets. bevy/blender: raea blender open and back for the person's hands, and <BlenderShot>. bevy/godot: --scene and --frames, <GodotShot>, raea godot export and back. convert.py: a packed image isn't a missing texture 2026-11-11 09:35:28 -08:00
shinyobjectz b85ce4f97d BL36, BL37, BL38, BL39, GD11, GD12, GD13: Blender and Godot in a raea project: shots drawn by them, the scene sent to them and its changes read back. raea scene export EDIT.tsx -o DIR [--frame N | --at A-B] writes the composition's 3D as scene.json (each part's id, kind, name, TSX line from the bundle's source stamps, placement, material, primitive sizes; other meshes as .glb, models copied with their sidecars; lights, camera, ambient, background; what doesn't cross listed in left) (new crate apps/interchange). raea blender open builds it in Blender through raea/blender (sdk/blender scene.ts: Blender's own meshes, Principled BSDFs, lights and camera keyed on --at, raea_id on each object) and opens the .blend; raea blender back and raea godot back read the file back and say each move, colour, light, camera and deletion as an edit at its TSX line, and write objects made there as media/NAME.glb. raea godot export writes a Godot project that runs (native meshes, StandardMaterial3D, an AnimationPlayer for --at, still channels left out, nodes named for their parts); raea godot run takes --scene with no script (host/none.ts). <BlenderShot> and <GodotShot> (raea/blender/shot, raea/godot/shot) render their frames once per bundle, file, props, size, fps and length, sized from their Sequence's end, kept in the asset store (native calls blender.shot, godot.shot; raea blender shot, raea godot shot). register_natives() gathers every native call a composition's thread answers, so raea types lists them all. Tests: apps/interchange (9), apps/engines 2026-11-11 09:35:16 -08:00
shinyobjectz a4a213e05e GD9: raea's own Godot 4.6.1 + GodotJS editors, and raea setup godot downloads them first (apps/engines godot.rs, sdk/godot/build). Pins move to raea's v0.1.1 release (godot-4.6.1-raea-macos-arm64, -linux-x86_64, -windows-x86_64 .zip, each pinned by size and sha256); GodotJS's own pinned build is the fallback, so a release whose zips aren't up yet still installs, and setup says which build it installed and why not raea's. RAEA_GODOT_FROM=URL (file:// too) installs from elsewhere. windows.py cross-builds the Windows editor with MinGW-w64; macos.sh makes Godot.app from Godot's macos_tools.app; package.sh signs it with the Developer ID and Godot's editor entitlements, notarizes and staples it, and zips all three; verify.sh fails unless the smoke prints its PASS line. godot run's usage gains --scene and --frames. Tests: every_pin_has_a_full_digest, raeas_build_is_tried_first_and_godotjss_after, setup_says_whose_build_and_why_not_the_one_before 2026-11-11 09:34:49 -08:00
shinyobjectz fddaf29fb1 CC2a: raea export capcut finds a composition's footage where the render did: a staticFile path (/media/x) in the edit's media/, then the project's media/ and assets/ (raea-core-scene's media_path, the renderer's own lookup). It read /media/x as a file at the disk's root, so every project that names its footage with staticFile was refused (found making the release post's draft). The summary line says 1 clip and 1 sound, not 1 clips 2026-11-11 07:38:11 -08:00
shinyobjectz 91157b6610 CC4: the raea skill teaches handing a cut to an editor in layers: sdk/guides/craft/motion/delivery.md says when to raea export capcut (a CapCut draft, footage as clips of their own files, raea's drawing as transparent clips over them; Export to, then CapCut in the app), that graphics for someone else's edit go out as a transparent .mov with --alpha and nothing behind them, and the two mistakes (a background in a transparent movie or --alpha with an .mp4; exporting while CapCut is open). Its copy in raea-skills is PR 42; the pin moves with this 2026-11-11 07:27:30 -08:00
shinyobjectz e9174676c7 CC4: skills pin: raea-skills 8fa672e (PR #42), whose motion/delivery.md teaches handing a cut to CapCut in layers and transparent movies for graphics, and whose reference/cli.md has raea export and render --alpha-codec from main's help, so the release's strict skills gate passes on main 2026-11-11 07:27:19 -08:00
shinyobjectz 87ccba76c1 AP10: the app's icon counts what's waiting in the Inbox on Windows too: raea-page-window's dock.badge sets an overlay icon on the window's taskbar button (ITaskbarList3::SetOverlayIcon, win.rs), as the Dock's badge does on the Mac. badge.rs draws it, pure and tested everywhere: a red circle or pill with the count in a 3x5 pixel font at the small-icon size the taskbar asks for, 9+ above nine, cleared at nothing. win.rs type-checks for x86_64-pc-windows-msvc (windows 0.62, already in the lock); notify's nested if is collapsed for clippy 2026-11-11 07:20:52 -08:00
shinyobjectz 45aa5ca212 CC2d: raea export capcut keeps the copy of CapCut's project list in the person's own folder, ~/.raea/capcut/backups (%LOCALAPPDATA%\raea\capcut\backups on Windows, RAEA_CAPCUT_BACKUPS to choose), as docs/capcut.feature says. It went to raea's home, which from a checkout is the source tree, so an export run from one left the backup in the repository 2026-11-11 07:12:24 -08:00
shinyobjectz 7fd6282cb2 GD9: raea builds GodotJS's editors itself: sdk/godot/build holds the macOS (arm64, JavaScriptCore) and Linux (x86_64, QuickJS-ng, on Modal) builds from source, as GodotJS's CI builds its release (Godot 4.6.1-stable 14d1969, GodotJS a8e2567 at v1.1.0.beta1-4.6.1, AccessKit-c 0.18.0), and verify.sh, which runs raea's smoke script on a build and compares the typings it generates with those from GodotJS's own build
On 11-10 the Mac build took 370 s at -j6 (133,184,648 bytes, reporting 4.6.1.stable.raea.14d19694e): smoke PASS, and its 17 typing files are byte-identical to GodotJS's build's. The Linux build took 511 s on 16 cores (161,938,768 bytes); it ran before the BUILD_NAME=raea line, so it reports custom_build, and it hasn't run raea's smoke yet. `raea setup godot` keeps GodotJS's pinned builds for 0.1.1; the pins move to raea's own in 0.1.2, once the Windows editor is built too, the Mac one is signed and each passes the clean-machine smoke. Nothing is uploaded before then.
2026-11-11 06:48:22 -08:00
shinyobjectz 07cd85e663 CC1, CC2: raea render -o OUT.mov --alpha writes a transparent movie natively, and raea export capcut EDIT.tsx writes the composition as a CapCut draft ready in its timeline (docs/capcut.feature)
raea-io-alpha encodes --alpha PNG frames (straight alpha) as a QuickTime movie: ProRes 4444 or HEVC with alpha through AVAssetWriter on the Mac, and QuickTime Animation (32-bit ARGB run-length, FFmpeg's qtrle layout) or PNG frames on every platform. `--alpha-codec prores|hevc|rle|png` picks one; prores is the Mac's default, rle elsewhere. CC1a, on a 3 s 1080x1920 graphic: 12.3 MB, 0.34 MB, 0.84 MB and 7.4 MB; rle and png decode identical to the PNGs, prores and hevc alpha within 61 dB, and a frame that draws nothing decodes fully transparent in all four.

raea-io-capcut writes CapCut 8.5.0's draft as CapCut writes it (an empty project and one with a clip placed by hand give its skeleton and a video segment's companion materials): one material per segment, times on the frame grid, media copied into its assets/, version markers from the newest draft CapCut made, and the entry in root_meta_info.json (backed up first, refused while CapCut runs). raea-app-capcut renders the composition three times: as it is with --manifest (footage runs, sound clips); with its footage and the backgrounds holding it hidden (RAEA_HIDE_MEDIA=1, the overlay); and with only those backgrounds (RAEA_HIDE_MEDIA=under, kept unless black). Footage becomes clips of the original files at their trims and rates, placed by object-fit (cover, contain, a cover crop), keeping their own sound at the composition's gain; sounds become audio clips with gains and fades; the overlay becomes clips cut where it draws. The manifest gains each video's object-fit and each sound's rate and fades, and the export cache is skipped under RAEA_HIDE_*. Checked on two fixtures: the draft's layers composited in ffmpeg match raea's render (31-33 dB against its H.264). Not yet checked: the draft opened in CapCut itself (CC3a). The CLI reference gains export (in Make) and --alpha-codec.
2026-11-11 06:43:39 -08:00
shinyobjectz ce920a5530 release.yml: room for the macOS build. rc4's macOS job ran out of disk linking raea-page-host (ld: write() failed, errno=28): rc3's build had left 576 MB of macos-15's 320 GB free, and rc4's dSYMs (#88) took the rest. Before the build, the Mac job removes the image's Xcodes other than the selected one, and the Android and .NET SDKs, in parallel, printing the free space before and after 2026-11-11 07:04:04 -05:00
shinyobjectz 0ea4eabe4a BL29, GD8: Windows 11 runs raea/blender's smoke on Blender 5.2.4 and starts GodotJS's editor
- BL29: Blender 5.2.4's Windows zip (406 MB, sha256 as blender.org lists it, 901 MB installed) needs nothing more;
  sdk/blender/test/smoke.ts run under Bun 1.4.2 through raea/blender printed its PASS line (3 cubes, the last 4.000 m
  out, a bmesh volume of 1.000).
- GD8: GodotJS's QuickJS-ng Windows editor (83,915,786 bytes, raea's pinned sha256, 178 MB installed) reports
  4.6.1.stable and starts and quits headless with exit 0.
- Still to run on each: raea's own Windows and Linux builds (raea setup, then raea blender run / raea godot run), which
  come with v0.1.1's release builds.

Proven: a probe on a Windows 11 PC (x86_64) in a scratch folder, removed after.
2026-11-10 22:04:00 -08:00
shinyobjectz 0c72d3942a skills pin: raea-skills 26c0cfe (PR #41), whose reference/cli.md has the Blender and Godot verbs (setup godot, blender run, godot run/types/open), so the release's strict skills gate passes on main 2026-11-10 21:57:36 -08:00
shinyobjectz 65074df06e BL22: 155 any declarations down to 79: Python returns read from their own source, sequence items from Blender's C
- tools/returns.py reads what a function written in Python returns from its source, where its docstring has no
  :rtype: (or a Python property's getter, no :type:): the type every `return` gives when each shows one (a literal, a
  comparison, a builtin's result, a str method on a string, os.path's, a local only ever bound to such), "T | None"
  when a path falls off the end; anything else leaves it any. dump.py gives it as `ret`, gen uses it for functions and
  Python properties alike: CyclesPreferences.has_active_device() boolean, Mesh.edge_keys an array,
  BoneCollection.bones_recursive a set (33 members).
- pymod.ts types the items of sequences whose name doesn't give them, from the C (bmesh_py_types*.cc,
  idprop_py_api.cc): bm.select_history[i] a vertex, edge or face; a BMElemSeq's any element; a layer collection's
  BMLayerItems; a deform vertex's [group] a weight; an IDPropertyArray's numbers or booleans. BMVert/BMEdge/BMFace/
  BMLoop[layer] and an ID property group (keyed by name) no longer claim a number index.
- dump.py leaves out Python's own names a Blender module imports (anim_utils' Mapping, Sequence, Iterable, typing
  aliases, dataclass), and keeps a private class the module's functions name as their :rtype: (bpy.props'
  _PropertyDeferred, so FloatProperty() and the rest return it).
- cret.ts reads `(PyCFunction)(void *)(name)` entries (GPUShaderCreateInfo's depth_write, fragment_out,
  push_constant, uniform_buf: None) and a returned local by its every assignment (libraries.write None,
  bpy.utils.units.to_value float, bpy.app.help_text str): cret.json 284 method and 123 property names.
- Declarations typed any: bpy.types 51 -> 32 of 16 684; modules outside RNA 104 -> 47 of 1 440.

Proven: tools/gen.sh from Blender 5.2.1 (tools/cret.sh 5.2.1 first); sdk/blender's tsc and its 16 bun tests pass,
with test/returns.test.ts: the reader's 18 cases, and every member it types on live meshes, bone collections and
Cycles' preferences reads as that type in Blender.
2026-11-10 21:54:55 -08:00
shinyobjectz 3725537f35 sdk/cloud: renders on a GPU or a CPU from one image, render jobs, and a CPU box that hands its renders to a GPU worker (docs/cloud.feature CL13-CL15)
- The image is Node 24 on Debian trixie with glvnd and X11's libraries (libxext6 libx11-6 libgl1 libegl1), without
  which NVIDIA's Vulkan driver (mounted by the container runtime) doesn't load or gives no vkCreateInstance (driver
  610.57 on Modal's T4, A10G and A10). The entrypoint opens NVIDIA's driver when the host passed a GPU in, else Mesa's;
  WGPU_BACKEND=vulkan, and on the CPU EGL's vendors are hidden, since NVIDIA's EGL would hand wgpu an OpenGL adapter
  over llvmpipe. RAEA_CLOUD_DEVICE=gpu fails at start on no GPU; /v1/health says the device.
- /v1/jobs takes a project as a tar and gives back what the render made (CL14); deploy/modal/raea_cloud.py runs it on
  a Modal GPU list (L4, else A10G, else T4), one container that sleeps after five idle minutes.
- RAEA_CLOUD_GPU_URL on a CPU box sends raea render to the worker and lands its files back (CL15, image/raea.sh and
  server/offload.ts); deploy/k8s.gpu.yaml is such a worker.
- test/smoke.sh: worker and box, ten checks, all pass on 0.1.1-rc3. On Modal, test/gpu/edit.tsx (576 lit blocks,
  1080p, 90 frames): T4 156 s against llvmpipe on the same machine's 8 cores 203 s; a box on a Mac handed it to an A10
  (119 s) and the MP4 came back.
2026-11-10 21:52:21 -08:00
shinyobjectz 98e215b4c9 sdk/cloud: raea and an ACP agent on a developer's own server (docs/cloud.feature CL1-CL12). One image (image/Dockerfile): Node 24 on Debian trixie, raea's Linux release checked against its .sha256, any agent the ACP registry lists installed from its entry at build time (AGENTS=kimi-code claude-acp ...; npm at the registry's version, or a linux archive checked by sha256), and a server on :8080 behind one token: /v1/health, /v1/files (paths confined to the workspace, symlinks out refused), /v1/run (raea ARGS streamed as NDJSON), /v1/login (an agent's terminal sign-in found from its ACP authMethods, under script(1), handing back the device link and code) and /v1/acp (one agent process per WebSocket). The agent and raea never see the token. raea's skills are installed for each agent on every start; RAEA_CLOUD_STATE keeps the home folder in an S3-compatible object where the disk doesn't outlive the container. A TypeScript client (src/, fetch and WebSocket only), and deploy files for Compose (CPU, or an NVIDIA GPU with the graphics capability for Vulkan), Fly Machines and Kubernetes. test/smoke.sh on 0.1.1-rc3's Linux release with a stand-in agent: 8 of 8 (the token refused, four path escapes refused, a frame rendered through /v1/run in 19.5 s under amd64 emulation, an ACP turn with the permission answered); Kimi Code 2.5.3's device sign-in started through /v1/login. The Fly, Kubernetes and GPU files are written, not yet deployed 2026-11-10 21:52:21 -08:00
shinyobjectz beb69f40bc tools/release/rl3-mac.sh: the play step runs with RAEA_AUDIO_MUTE=1, so a clean-machine check makes no sound on the Mac's speakers while someone works at it 2026-11-10 21:51:20 -08:00
shinyobjectz fe44ef6e42 skills pin: raea-skills a5b8700 (PR #40, merged on #39 and #38): 3d/blender.md says a Blender step can be written in TypeScript (raea/blender, typed) and the new 3d/godot.md is raea guide bevy/godot's copy, routed from 3d.md, games.md and SKILL.md (BL35, GD10); with 3d/characters.md's game_engine joints (#38, 07166db, rc4-issues) and motion/match-cuts.md with craft/match-cuts (#39, d0e5e8d, match-cuts) beneath it in this stack 2026-11-10 21:43:27 -08:00
shinyobjectz 33d5548254 BL29, GD8, GD2: setup on a clean machine needs no uv, git or shasum; smoke scripts; a clean Linux's libraries recorded
- raea setup blender finishes on a machine without uv (the MCP add-on becomes a note) or git (raea.blender is
  remembered only where git is; find() takes raea's download anyway).
- Downloads are checked with coreutils' sha256sum where perl's shasum is missing (debian:trixie-slim has none), for
  Blender's setup and Godot's.
- A Linux Blender that can't load its libraries names the Debian packages it needs, found in debian:trixie-slim:
  libx11-6 libxi6 libxext6 libxfixes3 libxrender1 libxkbcommon0 libsm6 libice6 libgl1 libopengl0.
- sdk/blender/test/smoke.ts: raea blender run's smoke (cubes made, a bmesh volume, mathutils against Blender's, one
  PASS line).
- GD2: pin_for(os, arch), and a test that Linux and Windows on arm64 and other systems are told to build GodotJS and
  set raea.godot.
- docs: BL29 and GD8 record the clean Mac runs and the clean Linux probe; GD2 is done.

Proven: cargo test -p raea-app-tools -p raea-app-engines. macOS with an empty HOME and the system's PATH: raea setup
blender --download, then raea blender run smoke.ts, PASS (Blender 5.2.4 LTS); raea setup godot, then raea godot run
smoke.ts, PASS. debian:trixie-slim on Modal: Blender 5.2.4 runs with the packages above, smoke.ts under Bun through
raea/blender PASS, and GodotJS's Linux editor starts headless.
2026-11-10 21:42:49 -08:00
shinyobjectz 8a9236fffa BL28: raea setup blender installs raea's add-on, and a script drives the person's own Blender live
- raea setup blender copies sdk/blender/python/raea_blender into that Blender's add-ons folder (replacing an older
  copy) and enables it, beside the MCP add-on; --check says whether it is current and on. Started with its window,
  that Blender serves raea/blender on 127.0.0.1 behind a token (~/.raea/blender/live.json).
- The add-on serves only a Blender with a window: a background one (a command-line render, setup's own checks) would
  hide the person's open Blender behind its own live.json.
- Fixed: Blender 5.2 gives a timer the window but no area, so the bridge's ui_context left view3d operators with no 3D
  view; it now fills in the area whenever there is none.
- Fixed, headless too: a slot freed by garbage collection was freed at the head of the next batch, before the read an
  await had queued for it ("reference N was released or never set"). Frees now go last, and are sent again after a
  batch that fails before them. test/bridge.test.ts forces the race: it failed before the fix and passes after.
- test/live.ts, run by hand (it opens a window): setup in a scratch BLENDER_USER_RESOURCES, Blender started with its
  window, a cube made, moved and put in edit mode and view3d.snap_cursor_to_center run, on the main thread in the 3D
  view; once Blender quits, connect({ live: true }) refuses its live.json.
- The CLI reference (docs/manual/reference/cli: setup, blender, index) follows the help.

Proven: cargo test -p raea-app-tools; sdk/blender's tsc and its 14 bun tests against Blender 5.2.1; test/live.ts 5 of 5
runs; the race test 5 of 5; bun tools/manual-ref/cli.ts check.
2026-11-10 21:42:49 -08:00
shinyobjectz 95cccb4af5 BL22: C methods and properties typed from the bindings' own C source (tools/cret.sh)
- tools/cret.sh fetches Blender 5.2.1's Python bindings (a sparse clone of its tag) and tools/gen/cret.ts reads, for
  every method and getset entry, the one Python type all its C function's returns give: None, bool, int, float, str,
  or a tuple a Py_BuildValue format makes. An error's nullptr gives nothing back; any other return leaves it unknown.
  A name is typed for a family of bindings (bmesh, gpu, mathutils, generic, bpy, aud) only when every C function bound
  to it there agrees: tools/cret.json, 274 method and 122 property names.
- dump.py marks functions written in Python (`py`), which keep what their own source says. gen applies cret.json where
  a docstring has no :rtype: or :type:, and a C property's setter takes what its getter gives.
- Declarations typed any: bpy.types 68 -> 51 of 16 684; modules outside RNA 423 -> 104 of 1 461 (gpu.state,
  gpu.matrix, aud's properties, bmesh's and gpu.types' methods).
- test/cret.test.ts reads every property so typed on live bmesh, aud, imbuf and mathutils objects in Blender: each is
  that Python type.

Proven: tools/gen.sh twice gives identical src/gen; sdk/blender's tsc and its 13 bun tests against Blender 5.2.1 pass.
2026-11-10 21:42:49 -08:00
shinyobjectz 07b6e3c7ec BL34: the bevy/blender guide drops the fill_mode cast: an enum Blender works out at the time takes any string 2026-11-10 21:42:49 -08:00
shinyobjectz 87fa310c80 BL34: an enum Blender works out at the time takes its static items or any string; Python methods that return None are typed so (BL22)
- BL34: tools/itemf.sh reads Blender 5.2.1's own makesrna (a sparse clone of its tag) for RNA_def_property_enum_funcs
  calls with an item function, into tools/itemf.json (tools/gen/itemf.ts): 147 properties and RNA function parameters,
  a helper's placed on the struct its caller defines. gen types them `static items | (string & {})`: 222 declarations,
  Curve.fill_mode among them, so `fill_mode = "BOTH"` on a 2D curve type-checks without a cast. Python can't tell
  these enums apart (with no context Blender never calls an item function). 8 helpers whose struct is named at run
  time stay unresolved; their enums have one item or none, typed string already.
- BL22: dump.py marks a function written in Python whose source returns no value anywhere (returns_none, by its
  AST), and gen types it as returning nothing where its docstring has no :rtype: (register, draw, shade_smooth,
  keyframe helpers...). bpy.types declarations typed any: 127 -> 68 of 16 684; Python modules 470 -> 423 of 1 461.
- Two dumps of one Blender now write the same src/gen: a data member's repr sorts a set's items and drops memory
  addresses.
- The guide (bevy/blender), README and docs/blender.feature drop the BL34 cast.

Proven: sdk/blender's tsc and its 12 bun tests against Blender 5.2.1 (bridge, rna, mathutils); test/typing.ts sets a
2D curve's fill_mode to "BOTH" and still refuses rotation_mode "XYZW"; run by `raea blender run`, the same script
prints fill_mode BOTH; tools/gen.sh twice gives identical src/gen.
2026-11-10 21:42:49 -08:00
shinyobjectz 32fdfe0863 blender-godot: L1's repo-wide checks (licences, dupes, taxonomy, the CLI reference)
- Licences: Godot's setup unpacks its zip with the zip crate, which brings zeroize_derive into a plain raea build, so it
  leaves the plugin catalog's list (tools/licenses.sh: NOTICE's line and LICENSES/zeroize_derive-1.5.0).
- Dupes, back to 294 exact and 56 near: Blender and Godot share apps/tools' own_dir(name) (~/.raea/tools/NAME);
  godot_run's project_size reads `key=value` with split_once, and godot types counts its .d.ts files in a loop.
- Taxonomy: the backend-name scan leaves out sdk/blender/src/gen, Blender's own API as its RNA names it
  (bpy.ops.render.opengl), as it leaves out the generated .gen.tsx.
- The manual's CLI reference (tools/manual-ref/cli.ts gen): `godot` joins Generate and 3D tools with a page of its own
  (docs/manual/reference/cli/godot.md, with its prose: run, the window that --window and --movie open, types, open);
  blender.md says what a .ts script does; setup.md and the index follow the help.

Proven in an export of origin/main + this lane: tools/dupes.sh (294, 56), tools/taxonomy.sh, tools/licenses.sh --check,
and bun tools/manual-ref/cli.ts check (48 verbs, 214 flags, every flag described) pass; cargo test -p raea-app-engines
-p raea-app-tools passes.
2026-11-10 21:42:49 -08:00
shinyobjectz 4dc3083c6e apps/engines: Blender's TypeScript runner and Godot in a crate of their own, so apps/tools and engine/cli stay under the 2,000-line crate limit (tools/size.sh)
The lane's first commit put apps/tools at 2,192 lines and engine/cli at 2,041, and L1 refused it. raea-app-engines
(apps/engines, layer apps) now holds godot.rs, godot_run.rs and blender_bridge.rs unchanged, and `raea blender run
SCRIPT.ts` (blender_ts.rs, moved out of engine/cli's cli.rs). Its cli(args) answers `setup blender|godot`, `blender ...`
and `godot ...`, so cli.rs calls it once where it had five branches. Finding and setting up Blender stays in
apps/tools/src/blender.rs, whose run and sha256 are now pub for Godot's setup; zip and dunce moved with Godot.
Sizes now: apps/tools 1,496, apps/engines 777, engine/cli 1,996 (main has 1,999).

tools/layers.toml gives the crate its layer; tools/skills.sh's stale-help check also watches apps/engines/src, where
Godot's usage now lives; docs/godot.feature, sdk/godot/README.md, sdk/godot/tools/gen.sh and runtime/calls/src/blender.rs
name the new paths.

Proven: cargo test -p raea-app-engines -p raea-app-tools (10 and 12 pass, among them a new test that cli() takes only its
own verbs and leaves the rest to the CLI); raea built with it runs `raea godot`, `raea setup godot --check` and
`raea blender run` on a .ts script as before.
2026-11-10 21:42:49 -08:00
shinyobjectz b2631ff5b6 raea/blender and raea/godot: Blender's and Godot's whole APIs from TypeScript (docs/blender.feature BL22-BL35, docs/godot.feature GD1-GD10)
Shane, 11-10: "include natively a blender api package in raea/blender using samchon/blendia as good starting place and
get us to a solid scripting parity to the official blender python api. we will own this ourselves", and "make sure to
add GodotJS which should add a more complete integration and bindings for godot integration".

raea/blender (sdk/blender, started from samchon/blendia, MIT, and rewritten): bpy, bmesh, mathutils, bpy_extras and
gpu typed from Blender 5.2.1's own RNA and docstrings (tools/gen.sh: 1809 structs, 2498 operators, 41 modules outside
RNA; 102 of about 12 900 members any), run against a real Blender. Paths are lazy as Python's attribute access is
(writes and calls sent in order, reads awaited, py.pin for a stable handle), errors are Python's (BlenderError),
mathutils is computed in TypeScript with Blender's maths (1450 values within 1e-5 of Blender's), float arrays are
the value Blender gives (Vector, Matrix, Euler, Quaternion, Color), a call that makes a thing by its type returns
that class (tools/refine.py), node sockets are typed by name, and every argument can be given by keyword.
`raea blender run SCRIPT.ts [FILE.blend] [ARGS...]` runs a script on raea's engine against a headless Blender
(apps/tools blender_bridge.rs, runtime/calls blender.post); under Bun or Node it starts its own, or joins the person's
Blender through raea's add-on (python/raea_blender).

raea/godot (sdk/godot) on GodotJS (MIT): Godot 4.6.1's every class, singleton, enum and builtin typed from GodotJS's
codegen, JavaScriptCore on the Mac and QuickJS-ng on Windows and Linux (no V8). `raea setup godot` downloads GodotJS's
editor build pinned by size and sha256 (apps/tools godot.rs); `raea godot run SCRIPT.ts` bundles the script and runs
its default export (a function given the SceneTree and ARGS, or a SceneTree subclass as the main loop) headless or
with --window, --movie recording with Godot's Movie Maker (the window kept on top, the frame size from the project),
a callback that throws stopping the run, RAEA_CWD with cwd() and resolve() for paths; `raea godot types` and
`raea godot open` (godot_run.rs).

The guides: raea guide bevy/blender gains "A step in TypeScript" and bevy/godot is new, each example type-checked
with its SDK's tests (sdk/blender/test/guide.ts, sdk/godot/test/guide.ts) and run as shown; raea guide bevy routes to
bevy/godot. Their raea-skills copies are 7497067 (branch blender-godot-ts, not pushed). sdk/tsconfig.base.json maps
raea/blender and raea/godot; tools/release.sh ships @raea/blender's python/.

Proven: sdk/blender's tsc and bun tests against Blender 5.2.1; sdk/godot's tsc and its 7 bun tests against the
installed GodotJS; apps/tools godot_run's unit tests; post 07b's film (releases/0.1.1/src/engines), its left half
built and keyed by raea/blender and its right half recorded by raea/godot.
2026-11-10 21:42:49 -08:00
shinyobjectz 3763a778de skills pin: raea-skills d0e5e8d (PR #39, stacked on #38): motion/match-cuts.md and craft/match-cuts, the match-cut guide and its kit, copied from sdk/guides/craft (MC1-MC4), on top of 3d/characters.md's game_engine joints (07166db, PR #38) 2026-11-10 19:23:47 -08:00
shinyobjectz 20391a0649 MC5: the match-cut guide shown to change how a fresh agent plans. One-shot agent sessions planned the same 24-second loop (16:9, 30 fps, a 120 bpm grid) as a storyboard and its chain, four with the guide and two with raea's home on main's guides, which have none. All six chains pass all eleven plan checks, since each found plan.ts in its kit, so the change is in the craft: one hard cut on a downbeat in every guided plan and none in the controls, 7-9 thirds places used against 6-7, and storyboard cut fields that name where the eye lands 85-100% of the time against 46-67%. A fifth session built a 13-shot graybox of one guided chain from the guide's steps; the render check found nothing on it and failed all 22 hooks and both bridges when the hooks were moved. The render passed the cut check, and its floor was clean once three contacts were fixed. The sessions' findings went into the guide (MC1) and plan.ts (MC2) 2026-11-10 19:23:32 -08:00
shinyobjectz 76f383300c MC4: a chain's board for any project (sdk/guides/craft/match-cuts/board.tsx): Board({ chain, places, title, intro }) draws the eye's way through the whole piece with how often it rests at each place, the eleven plan checks' results, each shot's frame with its in hook, its out hook and the eye's way between them (its join, what it lands on, its bridge, montage, hooks in words, carry), and the library of places with their hooks, props and picks; the person's picks (added to and dropped from the chain) and notes come back with app.result. The frame takes the chain's aspect (16:9 when unset). A project's board.tsx is three lines (bench/direction/match-cuts/board.tsx, places.ts) and goes to the person with raea show board.tsx. match-cuts.sh now mounts it headless (raea app check --target web, @raea/app replaced by a stand-in with its two calls), and a board that throws fails it 2026-11-10 19:23:32 -08:00
shinyobjectz c49cc6b267 MC1: raea guide match-cuts, how a planner writes a piece's cuts as a chain of hooks on the thirds while it writes the storyboard (sdk/guides/craft/motion/match-cuts.md). It covers the kit a project copies (craft/match-cuts: chain.ts, plan.ts, thirds.ts, board.tsx) and NAME.chain.ts beside the storyboard; the frame's places; choosing hooks by shape, motion direction, colour, light or sound, and naming the part the render check measures; the action that carries the eye from each shot's in to its out, and where the eye travels over the whole piece; the six joins (graphic, motion, eye on a beat, a FULL wipe, a sound bridge, hard) in a table with what the plan checks and the render check hold for each; a montage's hand-off, J and L bridges and a loop; when a hard cut beats a match; what a chain does in story, pitch (the proof lands where the problem was) and explain (the cursor is the hook); seven planning steps with an example chain, its check file and its rule; what the render check can't see; and the common mistakes. The router's plan step, the story, pitch and explain modes and motion.md's index route to it. tools/skills.sh copies craft/match-cuts into the skill beside craft/checks 2026-11-10 19:23:32 -08:00
shinyobjectz b4aaa8204f MC3: the match cuts checked in the render: at each cut of a chain, the hooked part sits at its thirds place on the frame before the cut and on the frame after it (sdk/guides/craft/match-cuts/thirds.ts). landsOnThirds(chain) is a raea/check system on the chain's cut frames only, reading raea world's facts with no render: a part (named() as raea/check matches names) by its world box projected through the frame's camera, its corners clipped at the near plane; a text by its laid-out box, named by its words; where several share a name, the one nearest its place. A point holds within a tolerance of the frame (0.06 when the rule's values don't say), a line on its axis, FULL to a share of the frame (0.9). Each cut of the chain must be a cut of the composition, a Sequence starting on the chain's frame with the shot's name; a J bridge's sound is placed its seconds before the cut and playing on the frame before; an L bridge's still playing on the cut's frame and its last; the plan checks run once after the frames, so one rule holds both. A project makes it from its chain in a three-line file of its own and names that in a rule or an ask. bench/direction/match-cuts/graybox.tsx builds the chain as a project would (each shot a Sequence from sequences(), each hook placed with onFrame and carried over its shot), and match-cuts.sh checks it: nothing found on it, and each of nine cheats found: a hook off its place, one gone from its place by the cut, the part renamed, a cut ten frames late, a FULL covering half the frame, a part behind the camera, a hook naming no part, the J sound starting at the cut, the L sound stopping at it. The whole bench runs in 7 s. What it can't see: a part hidden behind another, a camera rolled about its view, the eye's way inside a shot, and a 2D graphic that isn't text 2026-11-10 19:23:32 -08:00
shinyobjectz 85c13e6daa MC2: a piece's cuts planned as a chain of hooks on the frame's thirds, and checked by name before anything renders (docs/match-cuts.feature). sdk/guides/craft/match-cuts/chain.ts holds the thirds (nine points, four lines, FULL), the glyphs and which read as the same thing, hooks (what the eye is on, where, and optionally the part that draws it, the way it moves, its colour and light), shots with the join they are cut into by (graphic, motion, eye, full, sound, hard) and chain(), which places each shot on the piece's frames; toFrame and onFrame put a point in the world on the frame and back (Y up, vertical field of view, as Bevy draws it: a ball placed by them lands within 0.0004 of the frame of where the render draws it). Its eleven plan checks: hooks, length (to a frame), lands (every match cut lands the eye where the last shot left it; a point on a thirds line lands on that line; FULL only on FULL), glyph (graphic cuts and montages), motion (the direction kept), carry (a shot that moves the eye says what moves it), hard (says what it lands on), beats (cut to music, every picture cut on a beat; an eye-trace cut always), bridge (J and L sounds that fit their shots), montage (three or more shots handing one hook on) and loop. It imports nothing, so bun and raea check's bundle both run it; plan.ts runs the checks on a NAME.chain.ts by name (--only lands,glyph). A chain is NAME.chain.ts, since cuts.ts is a project's footage edit. bench/direction/match-cuts: a twelve-second chain using every join passes all eleven, and each of fourteen cheats made from it by one change fails the check it names and no other. On the chain of the film this was taken from, lands, glyph and length pass as its own checks do, and beats finds its montage's cuts drifting 44-51 ms off the song's beats 2026-11-10 19:23:32 -08:00
shinyobjectz 19102fac4c skills pin: raea-skills 07166db (PR #38), 3d/characters.md names the game_engine joints (#68) 2026-11-10 17:40:01 -08:00
shinyobjectz 766eab881d sdk/raea/tools/anny/character.py writes a body on MakeHuman's game_engine rig, so it renders (#68). It still wrote Anny's cmu_mb rig, CMU's 31 joint names with 30 finger joints after them in skeleton.json and a skin of 68 of Anny's own bones in body.glb, which raea's character SDK stopped reading when it moved to game_engine (docs/skeleton.feature): the engine refused body.glb, its skeleton's joints (RightHandPinky3, ...) being no nodes there. Now it builds Anny on her game_engine rig (MPFB2's, shipped with her) in her own A-pose and writes what projects/psx/export.py writes for a psx person: the 52 joints in bones.ts's order with parents, heads and tails (a finger's thickness too), Root's weights on the pelvis, each vertex's four heaviest, body.glb's bones nodes of those names, landmarks (eyes from her default rig, which has eye bones) and the surface samples; no skin, bind or follow. The graph paper, the hull, joint.glb and the presets are as they were. The issue's steps on the adult preset: 1.626 m, 52 joints, 1,588 surface samples; the render of held(adult, { upperarm_r: [-0.45, 0.25, 0.9] }) at frame 30 draws the arm raised with the skin bending cleanly, and the rest pose stands in the A-pose. The characters guide's held example and its Why name the game_engine joints, and character.tsx's header the rig 2026-11-10 17:38:21 -08:00
shinyobjectzandSirSicard 6f7a3f4478 raea check --quick looks at a quarter in, the middle and the end of the composition's real length, and says which frames (#86). It read the length from the source's first durationInFrames={N} and took 90 for anything else, so a durationInFrames={DUR} of 300 frames was sampled at 22, 45 and 89, and text only in its second half went unseen (all 0 texts, exit 0) by the after-save hook too. Now render.json carries the composition's length (length, written by every render whatever frames it drew), the quick check renders frame 0 first to read it, then the three stills, and its report says ok looked at frames 75, 150 and 299 of 300. The reporter's one-text file with DUR: main, all 0 texts; now all 1 texts and its safe-area error, as with a literal 300. The extra render of frame 0 costs about half a second (the literal file 0.85 s to 1.40 s). frames_come_from_the_render replaces the source-reading test; the manual's check and render references say both
Co-authored-by: SirSicard <[email protected]>
2026-11-10 17:34:46 -08:00
shinyobjectzandSirSicard 7f438bf130 H.264 above 4096x2304 on the Mac finishes instead of hanging (#83). VideoToolbox gives such a session its software H.264 encoder (VTCompressionSessionCreate still succeeds), which emits nothing until it holds 13 frames; raea keeps 3 in flight and waited on the oldest with no timeout, so the render stopped at frame 0 and the watchdog blamed the GPU. Now a full queue with nothing out for 300 ms has its frames completed (what RAEA_VT_FLUSH does), unlocked since the output callback takes the lock, with one note on stderr naming the size and --10bit, and every full queue after that completes them at once; nothing out for 60 s fails the render with that reason, and finish() waits the same 60 s. A dropped VtEncoder invalidates its session, so a callback can't reach freed state after such an error. The reporter's 4608x2592 60 fps page: main stalls at frame 0 (killed after 20 s, no file); now 60 of 60 frames at 31.0 ms a frame. 640x360 2.2 ms a frame (main 2.4), 1080p 5.0 (5.1). The 60 s deadline itself isn't exercised here (no encoder stays quiet that long)
Co-authored-by: SirSicard <[email protected]>
2026-11-10 17:34:40 -08:00
shinyobjectzandSirSicard 2c2e3ad3b8 What ships is stripped, its symbols kept beside it (#88). Release builds were never stripped: .cargo/config.toml keeps rustc's strip off (it re-signs without the JIT entitlement) and tools/link-jit.sh signed without stripping, so 0.1.1-rc2's macOS raea was 707 MB and its Linux raea 2.67 GB, nearly all symbols and debug info. Now link-jit.sh runs dsymutil on a dist-profile executable (into target/dist/symbols), then strip -x, then signs it with the entitlement; RAEA_KEEP_SYMBOLS=1 keeps them. The release profile the agents build isn't stripped (dsymutil takes 5 minutes a link there, and a stripped binary's panics name no functions). On Linux, release.sh splits each binary's debug info into dist/NAME-symbols/FILE.debug (named by a gnu-debuglink) and strips the copy it packs; on the Mac it copies the dSYMs there and warns of an unstripped binary. release.yml keeps those as a 90-day workflow artifact, never published. Measured on rc2's binaries: macOS raea 707 to 394 MB, raea-page-host 370 to 217; Linux raea 2,665 to 491 MB, raea-page-host 1,541 to 259; the archives 318 to 264 MB (macOS) and 1,008 to 300 MB (Linux). The stripped, re-signed Mac raea keeps com.apple.security.cs.allow-jit (codesign -d --entitlements -) and renders; a test link of a dist executable gets a dSYM whose UUID matches it
Co-authored-by: SirSicard <[email protected]>
2026-11-10 17:27:29 -08:00
shinyobjectz 7099bb9226 skills pin: raea-skills 9c4e65c, 3d/meshes.md says an <Instances>' list that changes moves the copies and each distinct list is kept (#84, #85) 2026-11-10 16:46:23 -08:00
shinyobjectz 9a2187a6b9 raea render says NOT APPLIED for a --w, --h, --fps or --frames the composition's own size or length overrides (the #84 reporter's --frames 3 on a 1,350-frame composition rendered all 1,350, unsaid). They only size a file with no <Composition> or config, as the reference says; the entry now names each one it passes over and the value the composition holds instead. Checked: mem-static.tsx --frames 3 --fps 24 says both and renders its 120 frames at 30 fps 2026-11-10 16:46:23 -08:00
shinyobjectz d7f2aaf076 An <Instances> keeps one copy of its placements across a render's frames, not one a frame (#84). The SDK sent them inside data-props, so a set whose other props changed each frame (a spin) was parsed whole into each frame's props and every frame's scene was kept (the fed render's frames, the clipping check): 20,000 spheres turning cost 2.1 GB at 120 frames and the issue's 60,000 at 4K 7 GB at 60 and 14 GB at 240. Now the SDK sends them as data-at; raea-runtime-react keeps each part's text as one Arc<str> (AT3D) while it's the same, and Node3 and Item carry it as at; the look compares frames' texts before parsing one (instances_column), and the fast live path compares the Arc (panel_srcs, now shared text). <Entities>' expansion moves to raea-core-scene (entities_nodes) to keep raea-runtime-react under 2000 lines. Measured: the 20,000 spinning, 621 MB and 18.6 ms a frame at 120 frames (was 2,117 MB, 69.7 ms), 645 MB at 480; 60,000 at 4K60, 1.04 GB at 60 frames and 1.22 GB at 240. About 1 MB a frame still grows. A binary from before this, run on this SDK, draws an <Instances> as its one mesh 2026-11-10 16:46:23 -08:00
shinyobjectz 8796ceb67c <Instances> whose placements change over the shot move in a video, as they do in a still (#85). A render drew the first frame's list on every frame of a video or an --at list (the row's inst column held one list and said so only in a warning), while a still of a later frame showed it moved. Now the row keeps every distinct list it shows (inst_all, '|' between lists, each frame's list compared with the frame before's) and keys which one each frame shows (inst_k), as a panel's pictures are; a live frame sends its inst, and the fast live path drops to the full one when an Instances' list isn't the one it sent. raea-runtime-scene3d's sync_instances moves the copies (a mesh's, or each of a model's meshes at its place in the model) when the frame's list is another; a list with another count than the copies is the frame's error, and the rows hold the list before it with a warning. The SDK's at, the guide's meshes.md and the manual's rows say a list that changes moves the copies and costs a list a frame. The issue's 20 sliding spheres at 640x360: x-centroid 141.2 at frame 0 and 326.7 at frame 59 in the video (the fed live path, RAEA_LIVE3D_FAST=0 and RAEA_3D=program alike), 327.0 in a --frame 59 still; was 141.1 at 59. The same with a glTF (knot.glb): 142.9 and 326.8, still 327.1. raea-runtime-look tests: lists keyed frame by frame, still ones one column 2026-11-10 16:46:23 -08:00
shinyobjectz 9ebedb3f6f A render's timings (the JSON line on stderr after a video) print only with RAEA_RENDER_STATS=1. The fed, CPU, direct and engine paths each printed it after every render, so a person's terminal and the app's render log showed a line of numbers beside raea's own APPLIED line. The benches that read it ask for it: bench/rerender's bench.sh, bench.ps1 and the iOS app's entry, and bench/lightspeed/export.sh; nothing else read it (tools, apps, docs, tests). RAEA_TIMES' lines are unchanged. On bench/rerender/pages.tsx: without the variable stderr holds the APPLIED and summary lines only; with it, the fed path's line as before 2026-11-10 16:26:20 -08:00
shinyobjectz 75b1c69e71 A page's <video> and <audio> play at their element's volume in raea's window (Shane 11-10: 'a loudness lever not just on and off'). sdk/ui's element takes volume as a browser's does (0..1, RangeError outside it, volumechange) and tells the host __volume, again with each play; runtime/dom/media asks the decoder Cmd::Volume when it changes; raea-runtime-js keeps it per player and plays the sound at that gain while it isn't muted (an AtomicU32 beside muted, read in the audio callback), set again when a sound opens. Before this the window had only muted, so the app's volume slider changed nothing. sdk/ui test: the element's volume reaches the host as __volume, fires volumechange once and is told again with a play. The live composition stage has no volume call yet 2026-11-10 16:16:08 -08:00
shinyobjectz f822be2c05 The Linux release's README names ALSA and fontconfig: raea and raea-page-host link libasound.so.2 and libfontconfig.so.1, which a bare Ubuntu 24.04 lacks, so the first raea failed with a loader error (0.1.1-rc2's tarball in an ubuntu:24.04 container, 11-10). apt install libasound2t64 libfontconfig1 (libasound2 before 24.04); raea.io/install now says the same when ldd finds them missing 2026-11-10 16:15:04 -08:00
shinyobjectz d0d71e67d5 An <Audio> or <Video> fadeOut fades inside its clip, silent by its end, not after it (#89 bug 5). The fade began when the element left the timeline, so a clip played at full volume to its last frame and faded past the cut. A Sequence or Loop pass gives its end through MediaEndContext, the nearest of nested ends, and with endAt's: each frame's volume is turned down into it ((end - f) / (fadeOut * fps), the mixer ramping each frame's gain over the frame after it), and data-fade-out is 0 there, so the stop at the end is the mixer's 5 ms edge. Its last frame isn't 0: a silent sound isn't played, which dropped it a frame early and faded the frame before's gain over the whole fadeOut. Without an end, the fade after it's gone is as before. A 440 Hz tone in a 1 s Sequence, fadeOut 0.5 at 60 fps: -5.6 dB at 0.75 s, -12.9 dB at 0.9 s, silent from 1.01 s (was no fade in the clip and a tail to 1.6 s). sdk/raea conformance media.test.tsx: a Sequence's end, endAt's, a Loop pass's, nested ends, and none 2026-11-10 15:58:28 -08:00
shinyobjectz c4f9a84988 startFrom, endAt, trimBefore and trimAfter say they count the composition's frames, not the media's own (#89 bug 6): a 24 fps clip in a 60 fps film starts at its 4 s with startFrom={240}. The doc comments and the manual's SDK reference said the media's own frame 2026-11-10 15:58:28 -08:00
shinyobjectz 7d66dfc59c RR2: the camera changes per frame. <Camera3d is_active> (Bevy's Camera field) says which camera draws: each frame's first active camera in the tree is the piece's, the others are dropped from that frame with their depth of field and ambient, and the camera row's shot column steps where another camera takes over (raea-runtime-look active.rs). A frame where it steps is a cut (raea-sys-frame Shots), drawn as a shot rendered alone draws its first frame: motion blur's step before it draws the frame itself rather than the other camera's, with a plugin too, and Solari's and the path tracer's history reset. Play sends the shot on its live camera row (0 again when the first camera is back), and a live engine takes a changed shot as a cut (Moved). The step to f - 1 that motion blur needs never ran on any engine, because the Engine's reads count as a Bevy plugin; renders were right anyway (export draws f - 1 before f), and play blurred cuts from the other camera's frame. bench/rerender/rr2.sh on cams.tsx (cameras A, B, A with parts moving): without motion blur the piece equals its three shot compositions 120/120; with it the frames before the first cut and both cut frames are identical and the rest differ by the blur's grain alone (seeded by the frame number, SSIM >= 0.999439; one camera moved instead: 0.810 and 0.785 at the cuts); each shot of the piece rendered alone with --at is identical 120/120; play's 7 held seeks onto and across the cuts equal the render. The craft guide's rule 6 and limits.md say how to cut between cameras 2026-11-10 15:40:43 -08:00
shinyobjectz 5b2c7731e2 skills -> 551722c: 3d.md's rule 6 says how to cut between cameras (each shot its own <Camera3d>, switched with is_active; a cut is one render, its first frame drawn as a shot alone starts) and 3d/limits.md is regenerated from raea's guide (raea-skills #35, for RR2) 2026-11-10 15:40:28 -08:00
shinyobjectz d412678357 DR6: done. Each ask of a note is held by a check that must fail on the work as it stands before the work changes, or by a clip the person signs. An ask names its check (raea's by name or a .ts check by its path), its values, its composition (Ask.of; Rule.of runs a rule only there) and, where it can't be measured, proof { shot | frames, sign }. raea notes check runs the asks through raea check's run (apps/direction, lent by the CLI): a first run that passes is refused (exit 1), a failure is kept with its check and values in .raea/notes-checks.json, a check changed after it failed is to check again, and each finding's by is its ask, so two asks on one check are counted apart; raea check runs the notes' checks beside the rules. Each clip is cut with ffmpeg from the composition's newest render, never from one the composition changed after; the person's sign comes back from the app with the render's sha256 and is kept by raea notes take. An ask reads to check, failing, to sign, passing or signed (the agent's move until there is a clip of the work as it stands), the note its worst; raea notes ls says each and raea notes post sends the badge, each ask's state and each clip (raea show --status --states, --sign --clip --render). raea/check gains a per-rule memo, after, named, turned and inside; six worked checks ship in sdk/guides/craft/checks and in the skill as craft/checks (rides, flat-type, faces, stands-on, shot-length, no-part), with their pieces and cheats in bench/direction/asks (asks.sh: 35 cases as expected). A plain element that covers another is named by the component that drew it (runtime/world). Proved end to end in a copy of the raea app (1109.87): a note sent, taken, restated, failing, the work changed and passing, the clip signed in the page, --done refused, and the sign reopened by a changed composition. Tests: raea-core-facts 16, raea-app-notes 10, raea-app-direction 16, raea-runtime-world 15, engine/cli show.test.ts 5. The craft router says the order, and the manual's notes, show and raea/check pages say what's new. The worked checks' table moves "low poly" to DR14 and "the light at the cut" to DR19, each with why. 2026-11-10 15:34:46 -08:00
shinyobjectz 96191842c4 skills -> 9addeb6: craft/checks, the six worked checks a note's ask copies into its project (rides, flat-type, faces, stands-on, shot-length, no-part); craft/ROUTER.md's notes steps 5 and 6 (give each ask a check or a clip, raea notes check until each fails first and then passes); cli.md's raea notes check and raea show --status, --states, --sign, --clip, --render; sdk.md's raea/check named, turned and inside (raea-skills #36, for DR6) 2026-11-10 15:22:52 -08:00
shane 4eb42e3476 Merge public PR #81 from Ragulsundaram: HTML: frame 0 applies the GSAP timeline's time-0 sets (#79)
A paused timeline's playhead starts at 0, so seeking it to 0 changed nothing and frame 0 showed the page's raw CSS; at t=0 the seek forces the render. sdk/ui test html-frame-zero pins it.
2026-11-10 18:22:11 -05:00
shane db9973375f Merge public PR #94 from JimGHTB12: a page of many layers the size of the frame draws them all, and one of more than Vello's image atlas holds fails its render
vello_encoding lets go of what the resolve hasn't used (the longest unused first) and packs the atlas again with the resolve's own images once, before an image is left out; what is still left out is counted, raea-page refuses the frame naming it, and the fed render now reads refusals, so a video fails as a still does. bench/layer-atlas: 18 frame-sized layers drawn in all 48 frames (32 short on main).
2026-11-10 18:17:18 -05:00
shane d407fde7ee Merge public PR #93 from JimGHTB12: a filter takes in what its element draws outside its box, as Chrome filters it
blitz-paint sizes a filtered element's layer from the boxes it and its descendants draw (drawn_bounds: up to the clips in their way, a descendant's own filter reach included, and the out-of-flow boxes its stacking context paints past its clip), then grows it by the filter's reach as before. bench/filter-overflow checks twelve pixels against Chrome 157 and 120 clipped filtered boxes.
2026-11-10 18:17:07 -05:00
shane ff3515eda4 Merge public PR #92 from JimGHTB12: an inline SVG's CSS transform: a style of transforms alone turns its shape, and view-box origins are at user 0 0
blitz-dom's SVG serializer no longer writes a leading ; before the computed transform when the element's own declarations were transforms alone (simplecss dropped the whole style), and transform-box: view-box's reference box sits at user space's origin, as css-transforms-1 puts it. bench/svg-css-transform gains viewbox.tsx and probes measured against Chrome.
2026-11-10 18:16:00 -05:00
shane 38684c9246 Merge public PR #91 from JimGHTB12: stills of a 2D composition render into a folder that doesn't exist yet, as before DR2
write_manifest makes the manifest's folder before it writes: DR2 wrote it before the 2D stills path made the output folder, so --at into a new folder was refused (bench/at-0 and bench/svg-css-transform failed on main).
2026-11-10 18:15:38 -05:00
shinyobjectz 71750e0542 DR5: done. The craft guide's notes section says the order: raea notes take, restate each note as its asks (one per thing asked, the medium its words name, what it's about, what it doesn't ask for), raea notes ls until it owes nothing, then raea notes post, and a correction from the app is restated again; each ask is one move, so a note with three asks is three moves. The scenario's status says what was built, the end-to-end run in a copy of the raea app (a comment sent, taken, restated, posted, corrected in the page and restated again), the tests, and what wasn't seen. 2026-11-10 14:18:19 -08:00
shinyobjectz 0fbfcb1d48 skills -> df2d233: craft/ROUTER.md's notes section says the order of work: raea notes take, restate each note as its asks, raea notes ls until it owes nothing, raea notes post, a correction restated again (raea-skills #34, for DR5) 2026-11-10 14:18:10 -08:00
James DimachkieandClaude 4c773e5fcf A filter's layer stops at paint containment and at its own clip over the boxes its stacking context paints
Two more ways the layer grew over content nobody sees, both from the Codex review of the first commit:
- the stacking context's boxes were all added whole, where hoisted_content_bbox places them. Only the ones painted
  past the clip need that (the out-of-flow boxes from containing blocks above, #39's from_above, which the walk
  doesn't meet). The others are met by the walk, under the clips they are painted under, so a filtered
  `overflow: hidden` box with a frame-covering `z-index` child keeps a layer its own size;
- drawn_bounds stops at a `contain: paint` box as at an overflow clip (render_element's contain_paint).

bench/filter-overflow/clipped.tsx is now 120 boxes cut four ways, 30 each. The first commit drew 60 of its 120
tiles: each of the two new kinds made 30 layers the size of the frame, more than Vello's image atlas holds.

Co-Authored-By: Claude <[email protected]>
2026-11-10 14:13:17 -08:00
James DimachkieandClaude b6675ced26 The manifest's folder is made in a statement of its own
The first form chained the write after the folder with `.and_then(|()| std::fs::write(&path, m))`, which
tools/dupes.sh reads as a copy of apps/check's hook.rs:105 (57 near-duplicate groups against the 56 allowed).
The folder is now made first, in its own statement, and the write is as it was. The crate is still at its
2,000 lines: the manifest's JSON is written where it is built.

Co-Authored-By: Claude <[email protected]>
2026-11-10 14:06:22 -08:00
shinyobjectz a4fd51bebe DR5: a person's notes become files the work is held to, restated as asks before anything changes. raea notes take writes each note sent from the raea app (each edit comment, with its pin) or said in a session (--said) to notes/ROUND/nN.ts, the words verbatim and no asks; a note already taken isn't taken again. raea notes ls says where each stands (to restate, to check) and what its restatement still owes: a second reading where one ask came from several sentences, each medium its words name (2D, 3D, flat, extruded, real, modelled, voxel) that no ask asks for or turns down, and what a redesign keeps. raea notes post shows a restated note's asks on its comment in the app (raea show --on ITEM --working ID --ask TEXT...), once per restatement, and none that still owes something; the person's correction comes back with the next take as a new line of the note, kept, with its ask in corrected until restated. Note, Ask, Pin and Proof are world facts (core/facts note.rs) with their TS types, and sdk/raea/src/note.ts gives note({...}). The notes are a crate of their own (apps/notes), not apps/direction, which is near its size; the feature file says why. 2026-11-10 14:03:56 -08:00
shinyobjectz 105d285691 RR1: the guides and the SDK's doc comments say the effects are each frame's own. raea guide bevy's rule 6, bevy/limits.md, bevy/post.md and bevy/lights.md: the sky, Bloom, Fog, Grade, ToneMapping, Shadows and the rest, and each light's colour, shadows and shafts, take each frame's values, so shots with different looks are one composition and one render (a cut that brings or takes a mode warms up about 0.3 s); the Grade's worked example is bench/rerender/film.tsx and shots.tsx (content/rome isn't in a checkout), and post.md's mistake is now a render a shot joined with ffmpeg. AmbientOcclusion, AntiAliasing and Shadows' doc comments, and the manual's SDK pages from them (3d, pbr, post_process, light), say each frame's is its own. The skill's copies are raea-skills #32. 2026-11-10 14:03:56 -08:00
shinyobjectz 2e5f9d7755 RR1: every look changes per frame. Each frame's post-processing is its own (runtime/look post.rs), and a set that changes goes in a per-frame table (frame_sets) laid onto the camera's row frame by frame; the camera takes a group off and puts it on again when its columns change (raea-sys-post camera.rs, moved out of raea-runtime-scene3d; volumetric fog's group is raea-sys-fog-half's, which raea-runtime-scene3d hands to it, as a system can't use another sideways). Each light's colour, shadows and shafts change the same way. A draw across a cut (a sky, AO, anti-aliasing, a tonemapper, shadows or volumetric fog coming or going) warms up 8 updates as a load does, so the sky's light is there on a cut's first frame; a ramp is no cut. Play builds its rows the same way: a row with a table is never still (a play's first frame has its sky), depth of field comes and goes with the frames that have one, the page background is keyed, and a seek back that makes a new engine sets play's rows on it again. bench/rerender/rr1.sh: the film as one composition equals its six shot renders 900/900; a 60-frame grade, bloom and fog ramp equals 60 stills 60/60 at SSIM 1.000000; play draws the looks as the render does at 12 seeks and 2 seeks back (the HTML caption over the 3D still differs by up to 2 levels at its edges, as before RR1). The supersample downsample moves to raea-runtime-gpuframe, and light_sig and pass_column to raea-runtime-look, keeping raea-render and raea-runtime-scene under 2,000 lines. 2026-11-10 14:03:56 -08:00
shinyobjectz 45d41783a2 RR0: the iPhone bench stops at a locked phone: devicectl launches nothing on one, so every render after it failed the same way with no log. bench.sh exits 3 saying to unlock it, and clears a render's old logs before copying the new ones back (a stale log read as a fresh result). 2026-11-10 14:03:56 -08:00
shinyobjectz afa0f61ece skills -> dc4d05b: 3d.md, 3d/limits.md, 3d/post.md and 3d/lights.md say the effects and light colours are each frame's own (raea-skills #32, for RR1), and cli.md and sdk.md have raea notes, show's --ask with --working and raea/note (raea-skills #33, for DR5) 2026-11-10 14:03:41 -08:00
James DimachkieandClaude 43e8892ce2 A filter takes in what its element draws outside its box, as Chrome filters it
blitz-paint made a filtered element's layer from its border box grown by the filter's reach, and raea-sys-filters
sizes the layer's texture from that clip. So whatever the element's descendants drew outside its box was cut off
before the filter ran: a wrapper of no size with `filter: blur(4px)` around absolutely positioned children drew a few
px of blur and nothing else, and a 60 px box with `grayscale(1)` showed 60 px of a 200x100 child. The same wrappers
with `opacity` drew whole, since an opacity group already reaches over the element's overflow.

A filtered element's layer now reaches over the boxes it and its descendants draw (drawn_bounds), and the same of
each box its stacking context paints, then grows by the filter's reach as before. drawn_bounds is
scrollable_overflow's walk (blitz-dom's resolve_transforms: each child's box through its transform) with two
differences. It is cut, on each axis an element clips, to that element's box grown by its overflow-clip-margin
(the root element clips nothing, as in should_clip). The overflow itself reaches through every clip, and a texture
made from it is as large as content nobody sees: small filtered boxes, each around a clipping box with a child
covering the frame, became layers the size of the frame, more than Vello's image atlas holds, and tiles went
missing. And a descendant with a filter of its own counts with that filter's reach (its drop shadow).
raea-sys-filters still cuts a layer to the page grown by the reach.

bench/filter-overflow/check.sh: page.tsx draws the blurred wrapper, a grayscale box around a square with its own
drop shadow, and the grayscale box three ways (as it is, clipping its overflow, clipping x alone), probed at twelve
pixels for Chrome 157's values, read from a screenshot of the same markup; clipped.tsx is 60 small filtered boxes
around clipping boxes with frame-covering content, half of them painted by the stacking context, its tiles counted.
The raea before this fails five probes; with it all pass and all 60 tiles are drawn.

Not covered: a box-shadow or an outline of a descendant, and a descendant's url() filter, still end at the boxes'
bounds; a box the stacking context paints that a clip between the two cuts is counted whole (a larger layer, never
a smaller one); and a filtered element inside an element with a perspective transform is still cut to the page's
rectangle in that element's own space (raea-sys-filters' region).

Co-Authored-By: Claude <[email protected]>
2026-11-10 13:22:09 -08:00
James DimachkieandClaude c6f4c9132d An SVG element's transform under a viewBox that doesn't start at 0 0 lands where Chrome puts it
transform-box: view-box, an SVG element's default, takes the nearest viewport as its reference box, and
css-transforms-1 puts that box at the origin of the user space the viewBox sets up, with the viewBox's width and
height. blitz-dom's svg_view_box returned the viewBox's own rectangle, x and y included, and svg_css_transform moves
the origin by the box's corner. So under `viewBox="100 50 400 300"` a `transform-origin` of 0 0 became 100 50:
`<g transform="scale(2)">` drew its content 100 px left of and 50 px above where a browser draws it, and a rotation
turned about the wrong point. A viewBox starting at 0 0, a translate, and a fill-box or stroke-box origin weren't
affected.

svg_view_box now returns the viewBox's size at 0 0. A viewport without a viewBox was at 0 0 already.

bench/svg-css-transform/check.sh gains viewbox.tsx: a square scaled by 2, one turned 180deg about 50% 50%, and one
scaled inside a nested svg with a viewBox of its own, each probed where Chrome 157 draws it (their client rects read
from the same markup in Chrome). The raea before this fails all four probes; with it they pass, and the bench's two
earlier cases are unchanged.

Co-Authored-By: Claude <[email protected]>
2026-11-10 13:16:55 -08:00
James DimachkieandClaude eb3c8ea6bf An SVG shape whose style attribute holds transforms alone is turned by them
Since de1a6830 an SVG element's computed transform goes to usvg in its style attribute: the element's own
transform declarations are taken out and `;transform:matrix(...);transform-origin:0 0` is written after what is
left. When the style held nothing else, nothing was left, and the attribute began with `;`. usvg reads a style
attribute with simplecss, whose declaration parser stops at a `;` before the first declaration, so every
declaration in it was dropped: `<rect style={{ transform: "rotate(30deg)" }}>` drew unturned, and so did one with
only transform-box, transform-origin and transform. A style that also set a fill or a stroke was read.

The element's own declarations are now written from the first of them on (without the separators, spaces and
comments CSS allows before it, which stop simplecss the same way), and the separator only after them when there are
any.

bench/svg-css-transform/check.sh compared mixed.tsx's two squares with each other. Both are of this kind, both drew
unturned, and the comparison passed at 0 px. The check now also probes each square on its turned top edge and where
its unturned edge would be. The raea before this fails those four probes; with it they pass, and the two comparisons
read 75 and 0 px as before.

Co-Authored-By: Claude <[email protected]>
2026-11-10 13:16:55 -08:00
shinyobjectz 6668da3253 A sound render (raea render X.tsx -o OUT.wav) finds its staticFile assets in the edit's folder (from the orientation showcase's gaps): sound_only stepped React without setting the edit's folder (edit_dir, as every picture render does), so a <FramePass file={staticFile(...)}> loaded /media/shaders/... from the filesystem's root and the render was refused at frame 0. Live play's master bounce goes through it too. Checked: a Canvas3D with a file FramePass and an <Audio> renders to WAV (it was refused). The manual's --at example says what the files are named: in order, frame-00000.png the first frame asked for. 2026-11-10 13:09:41 -08:00
shinyobjectz 060380ead5 DR28: text-read, raea's reading check. A render now gives each text an Ocr (what Apple Vision reads in its box on that frame, and the share of its words), from frames decoded once in order (runtime/world pixels.rs), which also measure each text's contrast without an ffmpeg call a text a frame. OCR reads a box fast first, then the text's line across the frame and the box accurately where fast misses a word (a lone short word reads as well upside down), and a crop that holds still but for a video's coding noise isn't read again: the manual's title example checks in 2.5 s from no record. text-read gives each text on, visible (in the frame, at an opacity, size and contrast that read, covered by no layer past a share) and read; holds its reading time (0.3 s a word, at least a second, none for a caption said as it shows) to visible, saying which frames were lost and why; and calls text that can be read where OCR doesn't read it broken (an error past 3 frames; read on under half: a warn). raea check runs it on every composition's newest render as raea's own rule, where it holds the floor's reading rule; what it couldn't measure (OCR off the Mac, covers without --layers) is a note. A word is matched by one key everywhere (core/facts word_key: letters and digits, lower case), which the floor's caption-against-voice rule now shares. bench/direction/read: a caption and five cheats, all as expected. The scenario's plan now gives pixels.rs 240 lines and read.rs 270 (planned 170 and 230): the fast and accurate reads, the still-frame reuse and saying lost frames in groups took more than planned. 2026-11-10 13:08:52 -08:00
James DimachkieandClaude 0198736cd4 A page of many layers the size of the frame draws them all, and one of more than Vello's image atlas holds fails its render
An element with a perspective transform or a filter is drawn apart and placed in the page as an image the size of
its box (raea-sys-filters' placeholder), new in every frame, and Vello copies each into its image atlas. The atlas
stops at 8192 px a side, room for 28 images the size of a 1080p frame, and lets go only of what the last two
resolves didn't use, in one sweep a resolve. So a page of ten such layers or more filled it with the last frames'
images, the frame's last layers (the nearest ones) found no room, and Vello drew them at no size without an error.
A film staged on about twenty frame-sized planes lost a cursor or a mark from single frames, different ones on each
run, with "0 errors, 0 warns".

vendor/vello_encoding, when an image finds no room at the atlas's largest size:
- what the resolve hasn't used is let go, the longest unused first (ImageCache::evict_unused), so last frame's
  placeholders go before a picture this frame's layers drew;
- if an image is still left out, the atlas is packed again with the resolve's images alone, the tallest first
  (repack_with, once a resolve). Images met in paint order cut a guillotine atlas up: 18 a few px apart in size
  didn't all find a place in room for 28;
- the images left out after that are counted (take_images_left_out).
An empty image is no longer looked for a place (the allocator has none for it, and the atlas grew to its largest
looking), and isn't one left out.

raea-sys-page reads the count after each Vello draw (skipped.rs) and refuses the frame, and the fed render now reads
refusals (raea_gpu_device::check::fed_checked): it had no one to read them, so a refused page went into a video as
it came. A still's render read them already.

Tests: vello_encoding's resolver places all 18 frame-sized images of each of 40 frames (unpatched: 10 of 18 from
the second frame) and counts the ones left out of a frame of 40; the cache's two new steps; fed_checked fails a
refused frame by its number.

bench/layer-atlas/check.sh, 18 layers the size of the frame, each with one white tile, on Windows 11 with an RTX 4070
Laptop (Vulkan). Before: 32 of the video's 48 frames short of 18 tiles, stills 1, 3 and 5 of six drew 10, and 40
layers rendered with every frame short. After: 18 tiles in every frame of the video and in each still, and the
40-layer render fails with "frame 0: a page (1920x1080) was drawn without N of its images".

Not changed: the atlas's size. A page still can't draw more images in one frame than 8192 px a side holds (28 the
size of a 1080p frame at best, 6 at 4K); it now fails instead of drawing without them. An image wider or taller
than 8192 px, which Vello also left out silently, fails its render too.

Co-Authored-By: Claude <[email protected]>
2026-11-10 13:06:42 -08:00
shinyobjectz 0b96b5ebd8 skills -> 468ee89: craft/floor.md's reading time is counted while the text can be read, and raea check says which frames were lost (raea-skills #31; for DR28's text-read) 2026-11-10 13:00:51 -08:00
James DimachkieandClaude 22cac9cf13 Stills of a 2D composition render into a folder that doesn't exist yet, as before DR2
Since bb0a1768 every render writes its manifest beside its output, DIR/NAME.render.json for a folder of frames. A 2D
composition's stills write the manifest before raea-render makes the folder and its frames, so with a DIR that
didn't exist the render stopped before drawing anything:

    raea render edit.tsx --at 0 -o new-folder
    REFUSED  new-folder/edit.render.json: The system cannot find the path specified. (os error 3)

It worked into a folder that was already there, and for a composition with 3D, whose path makes the folder first.
write_manifest now makes the manifest's folder before it writes.

bench/at-0/check.sh and bench/svg-css-transform/check.sh render stills into a fresh temporary folder: both fail on
main with the message above, and both pass with this (Windows 11).

Co-Authored-By: Claude <[email protected]>
2026-11-10 12:37:09 -08:00
shinyobjectz 089ff35577 DR4: raea/check in the manual and the skill's router: doc comments on every export (and on raea/ecs World's members it re-exports), the module in the SDK reference's Tools group with its page written by hand above the generated block, and craft/ROUTER.md's evidence step says when a line the work keeps every round is a rule: a controller field naming one of raea's checks or a .ts check written with raea/check, run by raea check PROJECT 2026-11-10 12:14:15 -08:00
shinyobjectz 973ee00acc DR4: a check is a system, and raea's own are written the same way. raea check PROJECT|EDIT.tsx runs every rule that applies to each composition: raea's floor on its newest render, the person's taste, and the workspace's and the project's controller rule fields. It reads the frames each check ranges over (all, cuts, lines, once or a list) into worlds once, runs raea's named checks in Rust (apps/direction systems.rs) and a project's .ts checks in the JS host (raea/check: check({ id, text, needs, level, frames }, (world, frame, values) => ...) and found(...), with the components' types generated from core/facts), and keeps the findings in the project's record. A check that needs a render and has none waits, and says what for; a check that throws, or a rule file raea can't read, is a finding. raea check VIDEO.mp4 is the floor as before.
Proved by bench/direction/proof/proof.sh: five checks that import nothing of Bevy's (a lyric layer over footage, a footage cut, a cue in a mix, a caption in a vertical ad, a rider on a 3D seat), each passing its piece and failing its cheat, and a taste line failing the ad's cheat as the named check of its form.

Fixed on the way: a text's box grows over words drawn past it (the caption cheat passed); a word a cut passes through is in each clip's words (the cut cheat passed); a Part carries its own box before its transform, so a turned part is tested as turned; the help reads `[A|B]` as one argument. Copies folded rather than added: a command's words (apps/check, now also raea workspace's), the printed report and exit code, the person's taste folder, a controller read from JSON (core/brief, now also apps/workspace's), and a path made plain (runtime/bundle's). The spec's lines that the code showed wrong are fixed beside them: --stage moves to DR10, a note's checks to DR6, and the rule field from DR8 to DR4.
2026-11-10 12:14:15 -08:00
shinyobjectz 5ba4688c74 DR4: a rule is a line and the check that holds it (core/facts rule.rs): one of raea's checks by name with its values, or a project's .ts check by its path; taste's six forms are six named checks with the same names and values; a controller gains the field type rule ({ label, check, values?, level? }), each a rule; brief.gen.ts regenerated 2026-11-10 12:14:15 -08:00
shinyobjectz 9444f13df3 skills -> 3f29ca6: cli.md has raea check PROJECT|EDIT.tsx and raea world's --render and --no-render, sdk.md raea/check, files.md the controller field type rule, SKILL.md a rule field and the default raea.root (raea-skills #30; DR4 lands next) 2026-11-10 12:12:07 -08:00
shinyobjectz bb0a1768c5 DR2: every render writes its manifest beside its output (OUT.render.json, or DIR/NAME.render.json); raea world joins the composition's newest render (from the project's record, or --render OUT): each text's Contrast against its pixels, the frame's and each shot's Picture (light and movement), the render's Mix, each cue's Onset in it, and Covers from a render with --layers, measured on the output when asked (raea-sys-measure, which raea check's contrast and loudness now call) and kept in the manifest; a frame or world with no render says what Waits for one 2026-11-10 10:39:13 -08:00
shinyobjectz 43429e6f2a raea render's --layers stamps the source itself (a real-case run of DR2 found it): a layer is a stamped thing, and RAEA_SOURCE_STAMPS was off unless set, so a render with --layers (or RAEA_LAYERS=1) wrote a layers file with no layers outside bench/layers, which sets it. It now sets RAEA_SOURCE_STAMPS=1 before bundling unless the environment says otherwise (RAEA_SOURCE_STAMPS=0 keeps stamps off), as raea world and the stage do. Checked: the conformance composition rendered with --layers and RAEA_SOURCE_STAMPS unset records its layers (19 keys). 2026-11-10 10:26:46 -08:00
shinyobjectz b5de0cbee4 A GPU that stops drawing fails the render (from RR0's A15 bench): the fed and live-3D paths (runtime/export bevy_frame.rs) only said the frame's error and went on, so with Bevy's StopRendering every later frame had no 3D and the render wrote the page alone and exited 0 (bench/rerender shot 1 on an A15: Bevy's atmosphere LUT, Rgba32Float behind a filtering sampler, without FLOAT32_FILTERABLE). raea_sys_frame::gpu::said takes a drawn frame's error: said as before (a model that didn't load: the render goes on), or, once the GPU has stopped, the render's error (exit 1; the frames before it are kept, as for any failed render). runtime/export depends on raea-sys-frame for it. 2026-11-10 10:26:46 -08:00
shinyobjectz 1f4a825714 RT3: a scene with <Grass> under <SolariLighting> renders instead of panicking on frame 0. Solari's mesh copy read each mesh with Bevy's plain accessors, which panic on a mesh whose data went to the GPU alone (RenderAssetUsages::RENDER_WORLD, as raea-sys-grass makes its blades), so all six of RR0's shots refused under Solari; it now reads with the try_ accessors and leaves such a mesh untraced (still drawn, lit by Solari). Tested: a mesh whose GPU data was taken is left untraced; a readable one is copied, its u16 indices widened. Measured on RR0's grass-free shots on the M5 Pro at 1080p: Solari 31.7-64.1 ms a frame against raster's 7.0-32.2 ms 2026-11-10 10:23:38 -08:00
shinyobjectz a3477d0721 RR0: done: today's numbers on the Mac, the Windows PC and an iPhone. Mac: six chunks joined with ffmpeg -c copy 16.3 s quiet (25-27 s loaded), one render 31-38 s, the six start-ups 10.5-16 s; Windows: chunked 71.0 s, 47.3 s of it raea media concat's re-encoding join, React 12 ms a frame on QuickJS (10x the Mac's); the note by hand 3.6 s on the Mac and 64.7 s on Windows, against 29-43 s and 38 s for the whole film again. bench.ps1 runs bench.sh and change.sh on Windows' own PowerShell; the film's shots move to shots.tsx. bench/rerender/ios renders the shots on an iPhone 13 Pro Max (A15: shots 3-5 at 61-265 ms a frame; the atmosphere's Rgba32Float LUTs can't be filtered there, and shot 2 is killed at its first 3D frame); raea-io-os builds for iOS, where its system calls answer as headless (rfd, arboard and opener have no iOS backend) 2026-11-10 10:04:01 -08:00
shinyobjectz 8e15cfccd3 RR0: bench/rerender: a six-shot film made from code (film.tsx), its baseline bench (bench.sh: six chunk renders joined as agents join them, and the film as one render, with each render's start-up and per-frame split) and the one-note case (change.sh) 2026-11-10 09:56:13 -08:00
shinyobjectz fc274e2870 DR3: under the size and copy limits: gen check's fitted-fix wording moves to raea-core-meshcheck (said_fix, tested there), Finding::read replaces four copies of reading a kept finding, the export cache prune is one pass over the folder, and the closures cargo-dupes matched by shape are written another way 2026-11-10 09:54:02 -08:00
shinyobjectz f4c41e9996 skills -> 49d440e: cli.md has raea findings and render's --despite, 3d/rooms.md the room checks' finding shape (raea-skills #28; also a workspace's default folder, landed on main) 2026-11-10 09:20:20 -08:00
shinyobjectz bf7fed1817 DR3: done. raea findings in raea's help and the manual (its page, the reference regenerated); the room checks' guide says their finding shape; the status written in docs/direction.feature 2026-11-10 09:18:27 -08:00
shinyobjectz eab9198a1e DR3: nothing reads as fixed by hiding it: a clip no frame shows is said as a note, a renamed part is renamed, a video from the export cache says what it found, a run is set against the one before of its kind; renders inside another (a review's tiles, a quick check's stills) keep no entry; a review's cameras face where they're put 2026-11-10 09:18:26 -08:00
shinyobjectz c98501a88f DR3: the record and raea findings find the project from a bare file name; a clip's span counts its last frame; gen check says a fitted copy's fix as what to run; raea next's page says what it reads from the record 2026-11-10 08:56:09 -08:00
shinyobjectz aebbdb2d4a DR3: the project's record keeps what each render and check found; raea findings reads it, raea next steps by it
A render, or raea check, of a file in a raea project keeps its findings in .raea/record/, one file apiece named by
when (UTC) and what, with the project's commit ("+" when the file has changes not committed), what --despite let
through, and at most 500 entries. raea findings [PROJECT | EDIT.tsx] [--about NAME] [--check ID] [--open] [--since
RENDER] [--json] compares each thing's latest entry with the one before (or RENDER): what was fixed, what is new and
what is carried, and since which render; a finding is the same across renders by its check and what it is about, not
its frames. raea next reads the record, not out/ and a check.json's time: a render's errors are the next step, then
its video's check and what that found. A render's manifest has all its findings (the exposure's too). The record lives
in core/facts beside Finding, since the render, raea check and raea next all use it (the scenario says why); the
registry's up() moved with it. raea findings is dispatched; its help line follows the lane changing help.
2026-11-10 08:56:09 -08:00
shinyobjectz 8a67680058 DR3: a render's exposure warnings and raea scene light's cuts are Findings
A render's measured exposure (clipping to white, crushing to black, stops off mid grey) is said as its Findings, so
it counts with the clipping check's on the last line. raea scene light says a cut that jumps in exposure or drifts in
white balance as a warn about the shots either side, with the stops or mired it turns on, and counts its findings
last; --json has them. The conversions live in raea-sys-light-meter, beside what they read, and scene light's text is
its report(), which leaves raea-runtime-export 7 lines smaller.
2026-11-10 08:56:09 -08:00
shinyobjectz 44b446302d DR3: raea judge writes what it saw as Findings
The defects present on its sheets become Findings in judge.json (findings, count) and in its text, counted last: a
blocking defect an error, a detail a warn, each a level lower from a judge that only advises (clef before
calibration). A judge sees pictures, not parts, so a finding names its sheet in its words and is about no entity. The
rubric's raw answers stay in defects.
2026-11-10 08:56:09 -08:00
shinyobjectz a0b770709f DR3: raea gen check, raea solid info and raea project scan write Findings
gen check's and solid info's {check, level, says} become Findings about the model, or the part (else the solid's file),
worst first, their count last; their JSON has findings and count in place of found, errors and warnings. A fix's
command, which was in its words, is its fix. project scan's lint is Findings about each file keyed file:line, a note
for what only the render knows, a fix raea doctor --fix applies starting by saying so; its JSON has findings in place
of lint. A file whose registerRoot makes its compositions through a helper is no orphan: the scan says it can't list
them (computed-root, a note).
2026-11-10 08:56:09 -08:00
shinyobjectz 3a705253de RR0: the re-render overhaul planned as docs/rerender.feature (RR0-RR15), with its research: why agents stitch clips with ffmpeg (docs/rerender.md) and the GPU layer on Mac, Windows and Linux (docs/gpu.md) 2026-11-10 08:54:56 -08:00
shinyobjectz 1c49f37e06 Merge branch 'raea-root' 2026-11-10 08:54:56 -08:00
shinyobjectz 4ca98b13a3 Workspaces go in ~/Documents/raea when no raea.root is set
~/Studio didn't say whose folder it was. With no raea.root, default_root: ~/Studio where workspaces are already (the root before 11-10), else ~/Documents/raea, or ~/raea when iCloud keeps the Documents folder (a workspace's git history and footage don't belong in a synced folder). The feed's host says the same (raea-feed host/workspace.ts defaultRoot). raea's usage and the manual's CLI pages name the new default; the skill's files.md follows in raea-skills.
2026-11-10 08:54:10 -08:00
shinyobjectz e98085bb45 render's --quality says what it does on Windows and Linux: OpenH264's bitrate scaled, and no change once a frame fits at its finest quantiser (#82)
The reporter saw --kbps and --quality write byte-identical files. On an RTX 4070 with rc2 the default, --kbps 20000
and --quality master did too (blocks.tsx, 1.0 Mbit/s), while --kbps 1000 gave 0.79: OpenH264's rate control never
goes below QP 12 (encoder_ext.cpp clips iMinQp to GOM_MIN_QP_MODE), so a frame that fits there has nothing left to buy.
2026-11-10 08:28:08 -08:00
shinyobjectz 9b9dd9e780 K's min, max and clamp take their bounds plus a zero the GPU compiler can't prove (#82)
On a Snapdragon X's Adreno X1-85 (Vulkan), a byte from clamp, min or max that was then shifted and or'd into a word
came out with 0xff in its top two bytes: the compiler fused the three into a pack it gets wrong. nv12buf.k packs four
luma bytes that way, so half the luma words of a bright frame were wrong and video striped. The bounds now add kz,
i32(shape.n >> 31u), which is zero but read from the shape uniform, so the compiler can't fuse them. The reporter
found the trigger and this fix on the device (128,319 of 262,144 words wrong before, 0 after); the test runs their
kernels, clamp and min/max each packed with or and shl, against the interpreter on random pixels. 05c978867's
unsigned shl stays (an i32 shift into the sign bit is still left to the compiler) but wasn't the cause.
2026-11-10 08:28:08 -08:00
shinyobjectz ebce4f28ab DR3: the older commands' JSON reads as a Finding (Finding::of_value), and scene lint's findings are read through it
{check, level, says} with what it is about (part, into, on, file) is what scene lint, gen check and solid info write;
of_value reads it as a Finding, a pass ("ok") as none, an object fix as its command. The plan's finding.rs is 240
lines for it.
2026-11-10 08:25:40 -08:00
shinyobjectz 2c111623c7 DR3: raea check's report turns an issue's second into its frame without a closure of its own (tools/dupes.sh) 2026-11-10 08:25:40 -08:00
shinyobjectz 0a895f8752 DR3: the render reference says a render's findings, its count last, exit 1 on an error, and --despite 2026-11-10 08:25:40 -08:00
shinyobjectz 9f3ffa7b1c DR3: raea render's usage names --despite CHECK WHY 2026-11-10 08:25:40 -08:00
shinyobjectz 574a4d228f DR3: raea/room's checkLayout and checkDecor return raea's one Finding
Each is { check, level, about, says, measure, by }: the check by an id a command line can name (work-aisle, walkway,
facing, behind-seat, work-triangle, decor-floats, decor-opening, decor-unit, decor-height, decor-centre, decor-width),
error, warn or note, the things it is about by name, and the distance it turns on with its limit. A clearance that is
met is a note (it was "ok"), so its margin still shows; "warning" is now "warn" and "rule" is "check".
2026-11-10 08:25:40 -08:00
shinyobjectz 898a0068df DR3: raea render counts its findings last and exits 1 on an error not let through
A render's findings (the clipping check's, as it says them) are kept for the end: the last line it prints is their
count, and an error not let through makes it exit 1 once its output is written. RAEA_DESPITE="CHECK: why" (a check's
name, or all) lets a check's errors through and writes the reason into the manifest, for a harness that renders many
pieces and compares pixels: P26's compare and recapture set it; a raea before this ignores it. The --despite CHECK WHY
flag is read the same way; its line in render's usage follows once the lane changing that line lands. raea check
--quick judges its stills' render by the manifest it wrote, not its exit, and reads their findings.
2026-11-10 08:17:29 -08:00
shinyobjectz 05abcdfc82 DR3: one Finding; the clipping check, raea scene lint and raea check write it
core/facts gains Finding { check, level, about, frames, says, measure, fix, by }, its one-line text, ranked (worst
first) and count, with its TypeScript declaration; raea check's P0 and P1 are errors, P2 a warn, P3 a note, and lint's
"warning" a warn. systems/contact's found.rs makes the lint's faults and the clipping check's overlaps Findings about
the parts by name, with the number each turns on and its fix. A render's manifest carries "findings" (it carried
"clipping", which nothing read) and says each on stderr; raea scene lint prints them worst first, notes included,
with the count last. raea check -o writes {file, fps, findings, passed} and prints the count last; --quick takes in
what its stills' render found and says a render that fails as an error. raea next reads the errors from findings.
The plan's apps/direction issue.rs is six lines in apps/check's report (the scenario says why).
2026-11-10 08:17:29 -08:00
shinyobjectz b8e55e9d5f skills -> 9e0adfd: cli.md names raea render -o OUT.wav and --audio OUT.wav (raea-skills #27; also raea world, landed on main) 2026-11-10 08:01:17 -08:00
shinyobjectz 1b55218328 raea render -o OUT.wav renders the sound alone, and --audio OUT.wav writes a video's sound beside it from the same pass
Shane 11-10: "we should add an audio-only render and also be able to render video and audio at the same time".

apps/sound (raea-app-sound, new): `raea render EDIT.tsx -o OUT.wav` bundles the composition as a render does (its --composition and flags), steps React through every frame for its sounds with no frame drawn (raea_runtime_export::sound_only, which live play already mixes from), masters it by its <Mix> as the video's sound is mastered, writes a 48 kHz WAV and prints its length, loudness and true peak. `--audio OUT.wav` on a video render sets RAEA_AUDIO_BOUNCE, which every render path already writes from its own bounce (export sound.rs and fed.rs, encode sound.rs), so the WAV is the very sound the video carries before AAC, with nothing rendered twice. engine/cli: the render line names OUT.wav and --audio, and run() hands a render to apps/sound first (one line; raea-cli is at its size limit). runtime/export, at its 2,000-line limit, is unchanged. docs/manual/reference/cli/render.md regenerated, with --audio described.

Checked: the Orientation film's sound alone, 125.8 s in 22.3 s, -14.0 LUFS, true peak -1.7 dBTP; a 2 s test with -o t.mp4 --audio t.wav wrote both, the WAV 2.000 s and the MP4's audio track 1.961 s (AAC).
2026-11-10 08:01:17 -08:00
shinyobjectz 0207451f1b DR28: Shane's note of 11-10 as a scenario: text on screen timed by when it can be read, and visible text OCR doesn't read is an error
His words verbatim, restated as five asks with what they don't ask. Each Text gets on, visible and read times; reading
is measured against visible; visible-but-unread is an error, a run read on under half its visible frames a warn; a
named check on every render, with its cheats. DR26 builds it straight after DR4.
2026-11-10 07:47:50 -08:00
shinyobjectz fcdcd8dbaa DR1: done. Status written; a word set one letter a span reads as its letters
The render's page manifest joined every text node of a run with a space, so a word revealed letter by letter
(content/rome's <Letters>) read "4 9 B C" for 49 BC; a run of single letters now reads as they're set, spaces
included (raea-page run_text, 1 test). A part's kind comes from its shape, never from what its author named or
propped it (the cheat test). raea world's reference page (docs/manual/reference/cli/world.md), the Check group's
order shifted by one. tools/layers.toml places raea-core-facts, raea-runtime-world and raea-app-direction.
raea-runtime-react back to 2,000 lines (scene/holders.rs, behaviour unchanged).
2026-11-10 07:47:50 -08:00
shinyobjectz ca54307223 DR1: raea world reads a frame into one world of facts
runtime/world (raea-runtime-world) steps a composition's React to the asked frames, as raea scene lint steps it,
and reads each into raea-core-facts entities: the 3D layer with its Camera (velocity from the next frame) and
Parts measured from their triangles, Text3D as Text and Part; the page laid out by the render's own Blitz page with
nothing painted (BevyPage::lay_out), so text has its box, size, font and line count; Sequences as Shots (from and
to; Sequence now stamps data-raea-end), footage as Clips with SHA-256 and their take's words, sounds as Cues, the
project transcript's lines and <Speech> lines; each entity's Source from the code stamps. <style>/<script> text is
not read as words.

apps/direction: raea world EDIT.tsx [--frame N | --at A-B|A,B] [--find JSON] [--no-layout] [--json]; --find spans
media (with, without, where Comp.field).

Folds: raea_runtime_react::scene::surface, raea_runtime_bake::runs, raea_core_facts::Word/transcript_words (raea
check's). Stamps name Audio. The time a layout-only page update gets is sent as a drawn update sends it.
2026-11-10 07:47:50 -08:00
shinyobjectz e0067e2f00 DR1: a composition's stepped frames are readable outside raea-runtime-export (scene_frames and a Frame's scene are public; no lines added, the crate is at its limit), and raea scene lint steps the frame it reads and its neighbour, not the whole composition 2026-11-10 07:47:50 -08:00
shinyobjectz 7222289a05 DR1: core/facts, the world's components. A frame of a composition as one world of entities with components by name, in raea/ecs's form (an id, a parent, components), as data Rust reads and a TypeScript world is built from: Source, Layer (its medium: 2d-type, 2d-graphic, 3d, footage, page), Text (words, box, extruded), Part, Camera, Shot, Clip, Cue, Line, and relations by name. Their TypeScript declarations come from the types. 2 tests. 2026-11-10 07:47:50 -08:00
shinyobjectz b46b6468f4 skills -> 1c68723: raea show posts quietly and asks everything as one item with previews (raea-skills #25: SKILL.md §6, cli.md raea show --open, the repeatable --question and --preview; #26: files.md names engine/cli/src/app.ts as app-host.json's reader) 2026-11-10 07:21:15 -08:00
shinyobjectz b30ef6adca raea show posts quietly, and asks everything in one item with previews
Shane 11-10: "any time you make an update to the feed it takes me out of the thing im currently doing", and the questions should be "a single thing that allows me to actually preview things while answering questions and all in one feed item rather than a bunch of them".

show.ts: --question repeats, each starting a question whose --choice's follow; --preview FILE after a --choice is that choice's (a still, a video, a sound, a NAME.script.ts or a .md), after the --question the question's own. Several questions, or any preview, go to the app's host as one item (questions); one question without previews is sent as before. The CLI opens the item's raea:// link (which brings the window up) only with --open or when it just started the app; otherwise the page finds the post (raea-feed f03b4e7, /host/shown) and says so in a notice. An app from before that route never finds an unsent item, so there the link is opened as before.

app.ts: the app-host verbs (show, harness, task, library) and their host lookup move out of native.ts, which was over the 500-line limit (514; now 407). cli.rs: the help line says so. docs/manual/reference/cli/show.md: regenerated, with --open and --preview described and the prose saying posts are quiet.

Checked: the parser on seven argument lists (old one-question stills, three questions with previews and --open, a --preview before any question, two previews on one choice, a stray file beside questions: refused with why); tsc --strict on native.ts, app.ts and show.ts; tools/manual-ref/cli.ts check clean for show.
2026-11-10 07:17:47 -08:00
shinyobjectz 086115c907 DR0: docs/direction.feature, the plan for direction that holds. One world of facts, findings and rules in raea/ecs's form, so a person's notes become checks and a project is built in an order that can't skip modelling, blocking or review. 28 scenarios (DR0 to DR27) with what raea already has and the gap in each, read against the code. DR0's decisions are decided. bench/direction/proto/world.ts proves the form on raea/ecs as it is, under plain bun: a 2D lyric, a 3D rider and seat, a footage cut and a cue in one world, four checks as systems, a three-ask note, six cases and two cheats as expected. 2026-11-10 06:25:45 -08:00
shinyobjectz 20a696e793 A click in a scene reaches the object under an overlay that covers the frame, and a part with no key is followed. A film lays a sheen or a grade over its whole picture as a page element; the pick answers the page's element when it is in front, so with one on top no click reached a 3D part. An element covering seven tenths of the frame or more now gives way to a part under the point and is answered as what is over it. locate boxes a part around its vertices as drawn (a skinned part by its pose, as a pick's own box already was) and finds a part with no LayerKey by its entity (entity:BITS, which a pick now names as entity_key), so the box of a loaded model's own mesh follows it. 2026-11-10 06:08:57 -08:00
shinyobjectz f25c925eec A script's solid is its expression until something needs the solid. /3d's manifold held a built Manifold for every solid a script made, so a set made of cuts was cut twice on every open: once here as the script ran, and again by the renderer, which builds its meshes from the expressions (and now keeps them on disk). A boolean, a move, a rotate and a scale now only write the expression; a query, a mesh, an export or an operation on the solid itself builds it then, from the expression (raea-core-shape's solid_or_empty, so a boolean that left nothing can still be asked whether it is empty). A launch-film set played offscreen at frame 0: 4.6 s to 3.6 s, another 4.4 s to 3.2 s, each frame the same bytes as before; examples/headless/solids-and-worlds.ts passes its 12 checks. 2026-11-10 05:46:47 -08:00
shinyobjectz 07e47b4ee1 What is drawn is measured as it is posed. The scene's bounds (what a free camera frames) were each mesh's own box placed by its own node, which says nothing of a skinned mesh: a rigged model under a scaled armature measured a fraction of what was drawn, and a camera framing it stood inside it. view::bounds now takes the vertices the frame draws (layer.rs drawn, the ones a pick's ray is cast against), so a skinned mesh is measured where its joints put it. Seen in raea.app 0.1.0-dev.1109.42 on a launch-film cat: the whole model in frame, its parts pointable. 2026-11-10 05:20:10 -08:00
shinyobjectz 05c9788672 A video's bright parts come out whole on GPUs whose compilers treat a signed shift into the sign bit as undefined. nv12.k packs four luma bytes (and two chroma pairs) into a word with shl, the top byte by 24, and the WGSL shifted i32: a byte of 128 or more overflows into the sign bit, which WGSL defines but a driver's compiler (a Windows on ARM GPU's, #82) didn't, so every 4 pixels of a bright region came out as two right and two at 255, white stripes over the whole video (the reporter's luma plane: 29,489 of 29,495 words whose second byte is 128+ have both top bytes 255; none below). K's shl now shifts as u32 and bitcasts back, the same bits as the interpreter's wrapping_shl, so nv12.k, nv12buf.k and p010buf.k (whose 22-bit shift overflows the same way) are unchanged. 1 test: the WGSL shifts unsigned, and on the GPU all 256 bytes pack as the interpreter packs them. 2026-11-10 05:14:25 -08:00
shinyobjectz bec8cddcf0 kept.rs names raea's caches folder without the closure another file already has 2026-11-10 04:30:04 -08:00
shinyobjectz ee62b13253 A solid's mesh is kept on disk between runs. An expression's mesh is the same every time a build makes it, and the boolean cuts of a furnished set were a quarter of the seconds its scene took to open, on every open. raea-core-shape's cached() now reads the mesh it made before from raea's caches folder (shapes/, named by the expression and by the running build, written beside and moved into place) and makes it only when it isn't there; RAEA_SHAPE_CACHE=0 turns that off and =DIR moves it. A launch-film set played offscreen at frame 0: 12.2 s with it off, 4.6 s kept, the frame the same bytes. 1 test (a kept mesh reads back bit for bit; one cut short isn't read). 2026-11-10 04:29:00 -08:00
shinyobjectz 281da9cc10 An ImagePlane plays its sprite sheet and swaps its picture in an mp4 render: a video's 3D is drawn live, frame by frame, and a live frame sent a panel only its placement, visibility and screen values, so the cell frame showed, the src it showed and its sheet's grid stayed at frame 0's for the whole film (a folder of PNGs, made from a program, played them). A live frame now sends a panel's sheet_frame, sheet_cols, sheet_rows and src when they change (live.rs's columns, and the fast path, which leaves a panel whose src changed to the full path: it holds the raw src against the one it last made a row from, so an unchanged one costs nothing); the engine swaps a live panel's picture when its row's src names another (scene3d::Pictures' live, found as spawn finds it). A program keys a part's grid as it keys its cell (it was the first frame's), so a src that changes to a sheet of another grid shows that sheet's cells; a card whose height follows its picture takes the new picture's shape. Found making 0.1.1's app showreel, which worked around it by rendering frames. 2 tests: raea-runtime-look's sheet keys, and raea-runtime-live's live_sheet (raea-runtime-scene is at its 2,000-line limit), where RAEA_LIVE3D_CHECK holds the fast path against the full one; a 30-frame repro reads the right cell and grid at frame 20 in the mp4, the program render and the PNGs. 2026-11-10 03:42:36 -08:00
shinyobjectz 0614e4b950 A 3D part asked for again by id answers its own box on the frame. The game inspector re-reads the picked element on every frame (stage.inspect), and for a 3D part that answered the holder element's box, which has none of its own: the outline a click drew on a mesh was gone a frame later, so a 3D object looked unselectable while page elements kept their outline. Live::element now places the part by its key (raea-sys-frame locate) and says it is a part. Seen in raea.app 0.1.0-dev.1109.33: three meshes in a paused game keep their outline as frames step. 2026-11-10 02:16:19 -08:00
shinyobjectz a956d8f8ee The dot-named edit joins the bundle key's file list in place, and its test is in raea-runtime-bake: raea-runtime-bundle is at its 2,000-line limit 2026-11-10 00:24:48 -08:00
shinyobjectz b6aa8b1d1e A preview wrapper rewritten gets its own bundle: a dot-named edit is part of its bundle cache key. The cache names a bundle by every source file under the edit's folder, but its walk passes dot files over, and the app's preview wrappers (.raea-view-NAME.tsx) are dot files rewritten at one path. A wrapper naming a model's new light level was given the bundle that named the old one, so the stage asked for a copy the store had dropped (the 3D didn't open) or drew the model as it was before an edit. Keys of other edits are unchanged. 1 test; docs/preview.feature PV3b has the packaged low-disk run. 2026-11-09 23:57:40 -08:00
shinyobjectz 85f20faaf0 Shadow maps fit a GPU with little memory of its own (#66): on Vulkan raea reads the largest heap the GPU calls its own (device-local) and, when a scene's <Shadows> gives no size, makes the sun's and spots' maps 2048 a side under 2 GB and 1024 under 1 GB instead of 4096, saying so once. An AMD APU's own memory on Vulkan is the carve-out its firmware leaves it (often 512 MB), and wgpu's allocator never puts a GPU-only texture anywhere else, so a sun's four 4096 cascades, 268 MB of depth, are the likeliest cause of #66's OutOfMemory on a Ryzen 7 4700U (not reproduced: there's no such machine here). On an RTX 4070 the blocks example's first frame holds 571 MB of GPU memory with 4096 maps, 370 MB with 2048 and 319 MB with 1024 (Vulkan, wgpu's allocated total, a build of this change with the heap size forced). The heap read gave 12012 MB on the 4070 and 32606 MB on lavapipe, which keep 4096; DX12 and Metal draw in the system's shared memory and keep 4096 too. A <Shadows mapSize> still wins. 2026-11-09 23:56:39 -08:00
shinyobjectz f04b3ae1b4 PV3b: docs/preview.feature has the proxy store's rules as the packaged app showed them 2026-11-09 23:33:51 -08:00
shinyobjectz fa78ed3bc4 raea play no longer hangs at start-up on Windows: pipelines compile on the render thread as each frame queues them, as Bevy always compiles them on macOS. On Bevy's task pool (its asynchronous compilation, Windows and Linux only) the first frame's wait_pipelines waited on pipelines the pool left unstarted with its threads idle. With the v0.1.0 zip on an RTX 4070, 17 of 32 opens stalled 2.8-42.6 s and some never finished; on lavapipe at 4 cores, as the release run checks it, kept-unmount hung past 200 s, the stall that timed out v0.1.0's Windows live-play check and kept Windows out of the release. Compiled on the render thread, the same binary opened 32 of 32 in 0.49-0.70 s on the 4070 and passed 26 of 26 plays on lavapipe, and a build with this change passes all 13 live-play cases on both. RAEA_BEVY_ASYNC_PIPELINES=1 brings the task pool back. Why the pool leaves its tasks queued isn't known yet. 2026-11-09 23:22:38 -08:00
shinyobjectz dad6913856 PV4d: docs/preview.feature says what the packaged app showed and what it fixed 2026-11-09 22:36:37 -08:00
shinyobjectz aa0a416b73 A GPU error is the render's error (#66): raea's engine answers Bevy's render errors itself (gpu_error), putting the first one, with what the GPU said, where a frame's other errors go, so raea render refuses with it. Bevy's own handler asks the app to quit, which an engine that steps its app never reads: the frame came back half drawn and was saved with APPLIED and exit 0 (on DX12 the blocks example drew its floor and one box; on an AMD iGPU's Vulkan, OutOfMemory left the background only). Drawing stops as before; it's said once, since Bevy asks again every update and a live game prints each one. A unit test gives it an FXC error twice 2026-11-09 21:34:45 -08:00
shinyobjectz 85adac1697 Ink outlines compile under FXC, DX12's shader compiler on Windows (#66): the wide line's 16 directions at three radii are one loop of 48, since FXC can't unroll two nested loops with a return inside them (X3511, 172 iterations) and every 3D scene builds this pipeline, so on DX12 its error stopped every 3D render (the blocks example drew its floor and one box). Checked with naga 30's HLSL as wgpu gives FXC (shader model 5.1, loops bounded) and Windows Kits 10.0.22621's fxc on cuda-box: the old shader fails as the issue says, the new one compiles; the filter passes, froxel min/max, traced AO and shadow-only compile too 2026-11-09 21:26:25 -08:00
shinyobjectz 4c990e1b75 PV4d: a 3D part asked by id answers its own props; docs/preview.feature's scenarios are done
stage.inspect {id} on a part's element answered the holder's raw props (data-3d, data-props as a string), so the
feed's game inspector lost a picked part's props on its next refresh; it answers the part's kind and its own props
now, as the pick does. The feature file: what was built after the first landing (the card that changes code, every
kind of file, a level of detail by size on screen, notes to agents), and each scenario's @done.
2026-11-09 21:24:03 -08:00
shinyobjectz 794769e15b raea show --on against a raea app from before it says so (quit and reopen to update), not the old host's bare "not found"; the host's own refusals still pass through 2026-11-09 21:07:12 -08:00
shinyobjectz e1b7a97ebd Video playback without the hitch every 300 frames: the Mac decoder's reader is recycled at a keyframe play has reached (a cursor stepped back to it, nothing decoded), so it no longer decodes a GOP first; frame 299 went from 46 ms (1080p60) and 163 ms (4K30, 250-frame GOPs) to about 20 ms at the next keyframe, open-GOP HEVC too, every frame's time checked (io/apple/tests/play_timing.rs). The page's video picture shares the frame's pixels instead of copying them again (Shane 11-09: playback starts to get weird) 2026-11-09 21:05:42 -08:00
shinyobjectz 29c7d81369 skills -> 5f0118a: cli.md has raea play --pick/--view and raea media lod (raea-skills #24) 2026-11-09 21:04:01 -08:00
shinyobjectz f0e01210c2 PV3c: raea's help names media lod; two copied closures folded (L1 dupes) 2026-11-09 21:03:59 -08:00
shinyobjectz 551b2102bb PV1: the pick and the layer pass walk the drawn meshes through one function; the licence catalog follows meshopt
systems/frame layer.rs drawn(): every shown triangle-list mesh with its posed vertices and corners, which the layer
pass rasters and a pick's ray is cast against (pick.rs had the walk copied). A render's layers are byte-identical
before and after (shapes.tsx frame 10), and the live pick answers the same part. meshopt and float-cmp are in the
plain build now (raea media lod), so tools/licenses.sh takes them out of the catalog-only list in LICENSES/ and
NOTICE.
2026-11-09 21:03:59 -08:00
shinyobjectz 1bed45b774 PV3c: raea media lod, a model at a lower level of detail; the feature file says what is built
raea media lod MODEL.glb [--level N] [--texture PX] -o OUT.glb halves every mesh's triangles a level (meshoptimizer
on the mesh's own vertices: skins, morph targets, UVs and materials untouched, only the index lists replaced), makes
embedded pictures at most PX on their longer side, and drops what nothing uses. Checked: a skinned body, 27,420
triangles to 6,854 at level 2, rendered and looked at. 2 tests. Cargo.lock has raea-runtime-live's raea-sys-frame
edge too (the first PV1 commit left it out). docs/preview.feature: each rule's status and what isn't built.
2026-11-09 21:03:59 -08:00
shinyobjectz e58ed228a4 PV4d: stage.locate says where parts and world points are on the stage now
A selection's box and a note's pin follow what they are on as the camera turns, a prop moves or the frame plays
(systems/frame pick.rs locate: a part's meshes' bounds and each point through the frame's camera). The stage's host
calls move to calls.rs (lib.rs was past 500 lines); the bundle's raea-props lines are two shorter (its crate was at
2002).
2026-11-09 21:03:59 -08:00
shinyobjectz 7198060ab9 PV1: raea play --seek takes --pick X,Y and --view YAW,PITCH,DISTANCE (its help line and manual page) 2026-11-09 21:03:59 -08:00
shinyobjectz afb3eb6dc6 PV1: the live stage picks 3D parts, a free camera, and props set as it plays
stage.pick answers what is under a point of the stage, the page and its 3D as one picture: a 3D part (its layer key,
name, JSX props, box, the point hit and its distance; the nearest mesh along the pointer's ray, skinned meshes as
posed: systems/frame pick.rs) or the page's element, with the part behind it. stage.view draws the 3D from an orbit
until it is given back (systems/frame view.rs, FreeView). stage.props sets a composition's props over its defaults
as it plays (the entry's raea-props). What the stage opens is stamped, so every pick has its place in the code.
stage.seek (written 11-07 for the editor's Live, never committed) lands with it. raea media still takes --width.
Proof: raea play shapes.tsx --offscreen --seek 10 --pick 640,330 answers shape-2 at shapes.tsx:28:11#2 with its
props; --view 1.2,0.9,9 draws it from above. docs/preview.feature is the plan.
2026-11-09 21:03:59 -08:00
Ragul Sundaram b529c4ea00 HTML: frame 0 applies the GSAP timeline's time-0 sets (#79)
A paused timeline's playhead starts at 0, so seeking it to 0 was a no-op and
frame 0 showed the page's raw CSS. At t=0 the seek now forces the render.
2026-11-10 10:31:30 +05:30
shinyobjectz 2293efc121 skills -> 1ccc69b: edit comments are tasks, marked working and done (raea-skills #23: SKILL.md §6, feed.md comment_task and feed_post answers, cli.md raea show --on/--working/--done/--note/--sub) 2026-11-09 20:08:55 -08:00
shinyobjectz cf28bf1ca0 A shell verb's refusal exits 1: js::run_node takes the script's process.exitCode at its end, as Node does (engine/cli's native.ts sets it, so raea show, init, cut, frame, part, brand and library refusals exited 0) 2026-11-09 20:06:50 -08:00
shinyobjectz a7e5b6c1d1 raea show --on ITEM --working ID / --done ID [--note LINE] [--sub NAME]: an outside session marks the person's edit comments as tasks in the raea app (POST /host/task); FILE --replaces ITEM --done ID settles them with that version; docs/review.feature R3; the show page's flags (Shane 11-09) 2026-11-09 20:03:00 -08:00
shinyobjectz eff11d8778 raea hook: the open's arguments read in one loop, the program's name and the patch's headers matched without copying other code's closures (dupes) 2026-11-09 19:41:12 -08:00
shinyobjectz dfa94a073e skills -> 306d618: raea's hook stops a Preview open once for raea show, for any harness (raea-skills #22; cli.md lists raea hook [claude|codex|gemini|kimi], so every lane's L1 skills check needs it with this lane's raea) 2026-11-09 19:35:05 -08:00
shinyobjectz 94a1cc59f7 The manual's hook, skills, skill and index pages for raea hook on every agent (tools/manual-ref/cli.ts gen in an export of origin/main + this lane) 2026-11-09 19:35:04 -08:00
shinyobjectz e9e0fba83e raea hook for every agent: media opened in Preview goes to raea show (a second try goes through), and every harness gets the hooks (Shane 11-09)
Shane 11-09, on a hook that steers an agent's open of a still to raea show: "yes lets do that or at least make it double
confirm then push and confirm. again also make sure all hooks and usages are acp agnostic not just claude".

apps/check/src/hook.rs: raea hook [claude|codex|gemini|kimi] reads any of the four harnesses' hook input (the harness
named, or told apart: Gemini's BeforeTool/AfterTool, Kimi's client_type). Before a shell command (Bash, shell,
shell_command, exec_command, run_shell_command; not Codex's apply_patch), a still, video or sound opened with open,
open -a Preview, xdg-open or qlmanage -p while the raea app is installed is stopped once: exit 2 with the reason on
stderr, which every harness hands its agent, naming the raea show command for those files. The same command in the
same session within ten minutes goes through (~/.raea/hooks/again), so an agent that means it says so twice. open -a
raea, open -R, links and PDFs are never stopped. After a save (file_path, path, or the files an apply_patch adds or
updates), the quick check on a composition, its findings in the shape each harness reads (Kimi's plain stdout,
Gemini's AfterTool context, Claude Code's and Codex's PostToolUse context). quick.rs loses its Claude-only hook.

apps/tools/src/agent_hooks.rs: raea skills install --agent A adds both hooks to that harness's own config:
~/.claude/settings.json, Codex's hooks.json (trusted in its /hooks), ~/.gemini/settings.json (milliseconds, named),
Kimi Code's config.toml [[hooks]] (only the four keys it allows). An event with a raea hook entry is left alone.
agent_mcp.rs loses claude_hook. engine/cli/src/skill.rs: hooks for every agent; a skill folder that's a link (a
raea-skills checkout) is left as it is instead of replaced by a stamped copy.

engine/cli/src/show.ts, native.ts: raea show names its poster from the harness that started it, found up its parent
processes (HARNESSES: Claude Code, Codex, Gemini, Kimi, OpenCode, Goose, Cursor, Amp, Qwen Code, Crush, Aider) when
its shell carries no mark, with an inbox per harness process.

docs/agents.feature A5d, A5e; the manual's hook and skills pages.
2026-11-09 19:33:35 -08:00
shinyobjectz 36c3fe1dd7 skills -> 96e0764: files.md lists ~/.raea/app-host.json and raea show's inbox (raea-skills #21) 2026-11-09 19:13:23 -08:00
shinyobjectz 5512224403 raea show in the manual: docs/manual/reference/cli/show.md
What raea show does for an agent outside the app, the inbox its answers come to, examples, and every flag described
(generated by tools/manual-ref/cli.ts from raea help --json in an export of origin/main + this lane); index.md lists it
under Agents and setup, and skill, skills and setup move down one in order.
2026-11-09 19:13:18 -08:00
shinyobjectz 397d502f67 raea show: in the manual's CLI groups, and raea-cli back to its 2,000 lines
tools/manual-ref/cli.ts: show is in Agents and setup (what an agent reads and shows the person). engine/cli: the show
comments fold into library's, so the crate is 2,000 lines again (rask's crate limit).
2026-11-09 19:11:35 -08:00
shinyobjectz 28b1acb6d2 skills -> 128698f: agents show work in the raea app with raea show, never in Preview (raea-skills #20; the reference's cli.md lists raea show, so every lane's L1 skills check needs it with this lane's raea) 2026-11-09 19:05:38 -08:00
shinyobjectz cbc763ef8d raea show usage: each flag names one value, so the skills reference counts them right
engine/cli/src/cli.rs: the help line reads --ask LINE and --question Q --choice A --choice B [STILL...] instead of
quoted phrases and a parenthesised choice, which tools/skills.sh read as extra values.
2026-11-09 19:05:25 -08:00
shinyobjectz 890e51afc5 raea show: what a session shows the person goes to the raea app as an item they can use, not Preview (Shane 11-09)
Shane 11-09: "my agent working raea keeps making sheets in preview and not in raea how do we make it so when using
raea and raea app is installed new edits new sheets or examples or questions are pulled up in the raea app and not
preview. we should see them as interactive too. the whole point of raea is interactive artifacts and things and
recording them after making an answer."

engine/cli/src/show.ts (a SHELL verb): raea show FILE... [--title --ask --project --replaces --as --role --inbox] and
raea show --question Q (--choice A ... | STILL...). native.ts finds the running app (RAEA_FEED_HOST, else the address
the installed app leaves in ~/.raea/app-host.json, raea-feed host-file.ts), starts it when it's installed and not
running, POSTs /host/show (raea-feed host/show.ts makes the item: stills a look, several a storyboard, a video a
watch, a sound a listen, a script or .md a read, a .tsx an artifact or the project's composition in its editor, a
question an ask), then opens raea://item/<project>/<id> so the window comes up on it. It prints the session's inbox
file, where what the person sends comes back (docs/agents.feature A3b). Without the app, the files open in the Mac's
viewer and it says nothing was posted. raea library finds the app the same way now. The poster's name and inbox come
from the harness (CLAUDE_CODE_SESSION_ID, ...) unless given.

docs/agents.feature: the file (rules A1 to A4 from 11-09) with A5, raea show.
2026-11-09 19:00:23 -08:00
shinyobjectz c6bb61b248 skills -> a5eb821: a plan is shown as previz, a storyboard of stills or its NAME.script.ts (as a screenplay and an A/V table), and a whiteboard maps (raea-skills #18, #19: feed.md's feed_post read and look files from raea-feed 4f526df; every lane's L1 skills check needs it) 2026-11-09 18:12:00 -08:00
shinyobjectz bb1d2bd0d5 Paste into a page's text fields: raea's pages get Blitz's shell provider with the clipboard (Shane 11-09: "make sure i can paste text into any text field")
Blitz's default shell has no clipboard, so Cmd+V in any field of raea.app inserted nothing (and Cmd+C, Cmd+X copied
nothing). systems/page gets PageShell, the shell provider a page's document is made with (config_in, beside PageNet and
the others); raea-page-host inserts one (src/shell.rs) on raea-io-os's clipboard, which is the system's in the window and
the process's own headless, as navigator.clipboard's is. io/os exports clipboard_text and set_clipboard_text for it.
Test: shell.rs pastes into a focused field through Blitz's event driver (with Blitz's default shell the same paste
inserts nothing), then Cmd+A, Cmd+C copies the field's text back.
2026-11-09 16:51:03 -08:00
shinyobjectz 148379c6e4 skills -> 43b2de1: ~/.raea/sessions and ~/.raea/inbox in the raea skill's files reference, and app-prefs.json's writer is host/app-prefs.ts (raea-skills #17; every lane's L1 skills check needs it) 2026-11-09 16:41:48 -08:00
shinyobjectz 3eccbe39e5 raea gen: a TypeScript flow anywhere imports raea/gen (Shane 11-09: the launch film's Source page flagged four flows importing ~/raea/sdk/gen by its absolute path)
Since the public-first split (11-06) the public sdk/tsconfig.base.json leaves raea/gen out (sdk/gen is the private side's), and `raea gen` gave bun only that file, so a flow outside raea's tree couldn't import raea/gen, the name docs/gen.feature GN12 says flows use. Agents wrote the absolute path instead, which the app's lint rightly flags as an import from outside the project.

raea-io-gen-core tsflow.rs (moved out of raea-io-gen cli.rs read_flow, and re-exported there; in gen-core so raea-io-gen stays under its 2000 lines): bun gets the runner's own override, the SDK's tsconfig with the SDK's folder as baseUrl and raea/gen and @raea/gen mapped when sdk/gen is there. A public install without sdk/gen gets the public names only. Tests: the override (with and without sdk/gen, a file that isn't JSON) and a flow in a folder outside the SDK importing raea/gen through bun (skipped without bun). The launch film's four flows now import raea/gen and quote with raea gen plan.
2026-11-09 16:39:45 -08:00
shinyobjectz b85409d738 Layer pass conformance (docs/review.feature R2e): a flat <Screen> and a skinned character (RobotExpressive, CC0, walking) in bench/layers/conformance.tsx, each one layer. A Screen carries its source stamp (engine/bundle stamp.rs PART_NAMES), and an ImagePlane or Screen panel gets its LayerKey and RAEA_HIDE_LAYERS visibility like a mesh (runtime/scene lib.rs bevy_parts; models.rs panels_rows sends its components). A fifth mutant, bind (a skinned mesh drawn in its bind pose, systems/frame layer.rs posed), fails at IoU 0.80, so the oracle checks the pose. All 18 layers IoU >= 0.962; all five mutants fail. 2026-11-09 13:27:32 -08:00
shinyobjectz bf49796080 skills -> 42d53be: ~/.raea/app-prefs.json in the raea skill's files reference (raea-skills #16: the desktop app's Selectable layers setting, RAEA_APP_PREFS; every lane's L1 skills check needs it) 2026-11-09 13:26:31 -08:00
shinyobjectz 70946b84bf Layer pass before landing (L1): LICENSES/ and NOTICE as tools/licenses.sh writes them (vello_cpu, vello_common, glifo and fearless_simd are in the plain build now, through raea-sys-layers, so not the catalog's alone), and page_css joins its parts in one expression (raea-runtime-bundle back under 2000 lines) 2026-11-09 13:09:03 -08:00
shinyobjectz ed0ebd2c01 Layer pass before landing (L1): RAEA_HIDE_LAYERS's page CSS (hidden_css, layer_selector) moved from raea-runtime-bundle, which was over its 2000 lines, to raea-sys-layers (hide.rs); the render manifest's videos and text moved to engine/page motion/manifest.rs (motion.rs was over 500); raea-sys-layers in tools/layers.toml (systems, a facility raea-sys-frame builds on). Copies folded: a part's key from its props is raea_sys_layers::key_from_props (runtime/scene bevy_parts), an env switch set to 1 is raea_io_home::env_on (fresh.rs stamps, apps/game probing), and the ID scene draws a box shadow as its element's layer out to 1.5 deviations past its box (hiding an element hides its shadow) instead of skipping it. 2026-11-09 13:06:19 -08:00
shinyobjectz ea3d7f85ec raea render --layers in the manual's CLI reference (docs/manual/reference/cli/render.md): what NAME.layers holds and where it goes 2026-11-09 12:53:54 -08:00
shinyobjectz d1edca2817 Layer pass: a <Video> is a layer (docs/review.feature R2e; parked with the source stamps): Video and Audio pass their source stamps on to the element they draw (sdk/video media.tsx useMediaAttrs), and the page bridge keeps a video's KEPT data-raea props (runtime/page elements.rs dropped every data- prop of a video, its player's and the stamps alike). bench/layers: a 4 s test-pattern clip in the conformance composition, IoU 1.000 at all three moments; all 16 layers pass and the four mutants still fail. 2026-11-09 12:53:33 -08:00
shinyobjectz e029385319 Layer pass, the 3D's half (docs/review.feature R2b, R2e; work in progress, parked with the source stamps): each Engine::draw records its frame's meshes with --layers (systems/frame layer.rs record: every shown Mesh3d from the lowest-order active Camera3d drawn on the CPU straight at mask size, nearest first, as the layer of the nearest part up with a LayerKey; skinned meshes posed by their joints; no morph targets), and the file's mask is the page's where it painted and the 3D's elsewhere (raster.rs, Recorder::frame_3d). Names: a use's outermost element is named after its component (Badge), an unnamed part after its tag (Mesh3d), else aria-label, class, tag. RAEA_LAYERS=1 turns it on too, until --layers is in the help with its manual entry. bench/layers: a third mesh in front of the moving cube, written before it; mutants.sh breaks the pass four ways (keys swapped, the 3D 2 px right, the farthest triangle winning, the page under the 3D): each fails compare.sh while the pass passes all 15 layers at IoU >= 0.969. 2026-11-09 12:48:31 -08:00
shinyobjectz 7a3e87dddb Layer pass, the page's half (docs/review.feature R2b, R2c, R2e; work in progress, parked with the source stamps): raea render --layers writes NAME.layers v1 (systems/layers, raea-sys-layers: gzip of RAEALAYR, the header's table of layers, each frame's quarter-size mask as runs) and render.json's "layers" names it. The page is painted a second time once the frame's update has laid it out: blitz-paint now names the node each paint call draws for (painting()), and an ID scene on vello_cpu draws that node's layer index as a flat colour with antialiasing off (edges counted above 12/255 coverage, glyphs emboldened as the page draws them). bench/layers/compare.sh scores each layer's mask (its own pixels plus those of the layers inside it) against oracle.sh's: all 12 page layers pass at IoU >= 0.977 at frames 10, 45 and 80. The 2 mesh layers come with the 3D half. key_of moved to raea-sys-layers (systems/frame re-exports it). 2026-11-09 12:45:05 -08:00
shinyobjectz c03edea294 Layer pass oracle (docs/review.feature R2e, work in progress, parked with the source stamps): bench/layers/conformance.tsx (two 3D meshes, a component used twice, a page element, text, an image, a rotated element and a .map() list, overlapping) and oracle.sh (each layer hidden in turn at three moments, the pixels that change as quarter-size masks, sampled as NAME.layers' are); all 14 layers' hides change their pixels. Stamps: raea's page parts (Img, Video, AbsoluteFill) stamped as 3D parts are; the work folder's motion/prelude read as raea; data-raea-idx kept through the page bridge. 2026-11-09 12:45:05 -08:00
shinyobjectz 09a935abd0 Layer keys (docs/review.feature R2a, work in progress, parked with the source stamps): a .map()'s key in the stamps (data-raea-idx, and loc#key in a use chain); raea's 3D parts (Mesh3d, Model, Entity…) stamped and given a LayerKey component (raea_sys_frame::layer) from it in runtime/scene; the work folder's SDK imports (../motion/x) read as raea's, not the edit's own; only components that read their children's types keep them unwrapped; RAEA_HIDE_LAYERS hides a layer by key (page CSS from its stamps, a 3D part's Visibility) for the layer pass's oracle. Not for landing before the layer pass. 2026-11-09 12:45:05 -08:00
shinyobjectz e1914cabca Source stamps (work in progress, parked): engine/bundle's stamp.rs and its lib.rs and test hunks, parked by the orchestrator so #51's fix can land in the same crate; not for landing until its owner finishes it 2026-11-09 12:45:05 -08:00
shinyobjectz 0adc2ed8f2 Source stamps (work in progress, parked): the render manifest carries each element's nearest source stamp (engine/page motion.rs) 2026-11-09 12:45:05 -08:00
shinyobjectz 4ca212f207 Source stamps (work in progress, parked): fresh::stamps() reads RAEA_SOURCE_STAMPS, and the bundle cache keys on it; not for landing until its owner finishes it with engine/bundle's stamp.rs 2026-11-09 12:45:05 -08:00
shinyobjectz ace0f1423f docs/review.feature: R2 status (the player reads NAME.layers v1 and picks by shape; the engine's page half passes the oracle at IoU >= 0.977; the 3D half and --layers come with stamps-wip) 2026-11-09 12:44:24 -08:00
shinyobjectz 3240414eff docs/review.feature: reviewing a video in raea's player, comments on the picture (R1) and every layer selectable the same way for 3D, React and the page (R2), from Shane's ask of 11-09 2026-11-09 12:44:24 -08:00
shinyobjectz 311b7988ee The Rune host answers the synchronous net.storage.get, through raea-io-net-calls as its async net.* calls are (L1 targets suite: rune-motion and rune-signin on native listed it as unanswered once storage.ts read kept values synchronously)
Without BEVY_TSX_STORAGE the answer is an error, which storage.ts takes as nothing kept. The counter test asserts the call is answered, not refused.
2026-11-09 12:42:59 -08:00
shinyobjectz ebd147a076 The desktop app keeps its localStorage across launches, and a page reads it before its code runs (Shane, 11-09: the open workspace and Getting started's Hide were lost on every quit).
raea.app never set BEVY_TSX_STORAGE, so raea-io-net-calls refused net.storage.* and storage stayed in the window's memory (the launcher half is in raea-platform). With it set, a page still read its settings before the kept values came back, as net.storage.get was only asynchronous, and an app saving its settings on load (apps/app settings/store.tsx) would write its defaults over them. net.storage.get is now a synchronous host call too (raea_io_net_calls::storage_get, registered by raea-runtime-js net.rs install), and sdk/ui's storage.ts fills localStorage from it at load, falling back to the asynchronous answer on a host without it. Test: raea-runtime-js net::tests::kept_storage_answers_synchronously.
2026-11-09 12:42:59 -08:00
shinyobjectz d3e2922058 Page media in its own crate, raea-runtime-dom-media (runtime/dom/media), so raea-runtime-dom stays under the crate limit (L1 size: 2049 lines); its copies folded
The video and audio elements' sync moves out of raea-runtime-dom as it was, and raea-runtime-dom re-exports it as media. raea-sys-image and vello were only media's and go with it. Stream's four one-line senders are now one ask(Cmd), with Cmd public (L1 dupes: seek and muted were one shape). A seek that has landed is Media::landed, which is checked from two places. Tests: raea-runtime-js, raea-runtime-dom and the new crate pass; raea-cli checks.
2026-11-09 12:39:13 -08:00
shinyobjectz ada5e5b5a3 Page media: React's muted reaches the host's player, so an unmuted video plays its sound
The app's watch player stayed silent when unmuted (Shane, 11-09): React DOM's muted is a property, but the page runtime took it as a prop on the wire, which runtime/dom's media.rs never reads (it reads __muted), so play()'s muted start held. sdk/ui dom/host.ts applyProps now sends a media element's muted through its setter on change, and at creation sets __muted in _extra, which hostElement sends with the create. Test: dom.test.tsx React muted case (52 pass).
2026-11-09 12:31:56 -08:00
shinyobjectz f8844bb385 Page media plays: video and audio elements' play(), pause() and load() drive the host's player, on the sound's clock
The desktop app's watch player threw on play() (the page runtime's <video> had none: the host played nothing), and
going back from an item crashed the app (its preload cleanup called load()). Now raea-runtime-js media_play.rs plays a
source on its decoder's thread: frames asked for at the clock's time (a slow decode skips frames, never lags), the
clock the sound's, out of the default device through cpal (media_sound.rs; muted plays silence on it), so picture and
sound can't drift; the wall's with no device or RAEA_AUDIO_MUTE=1. runtime/dom media.rs passes __play, __muted and
__load and tells playing, time (each frame), timeupdate (4 a second) and ended. sdk/ui dom/media.ts: play() (a
Promise), pause(), load(), paused, ended, loop, autoplay, canPlayType, preload, readyState per source, a new src
pausing as a browser's does; dom/host.ts gives React's onPlay, onPause, onPlaying, onTimeUpdate, onEnded, onCanPlay,
onVolumeChange and onEmptied their events. Tests: media_play::tests (wall clock: order, end on time, exact seek,
loop, pause), sdk/ui dom.test.tsx's media case (51 pass).
2026-11-09 12:31:56 -08:00
shinyobjectz 804f57664f raea-app-registry in the apps layer (tools/layers.toml); the dupes ratchet down to 294 exact, from folding the registry's line counting into its caller 2026-11-09 12:30:45 -08:00
shinyobjectz 151de4ba63 Project registry in its own crate, raea-app-registry (apps/workspace/registry), so raea-app-workspace stays under the crate limit (L1 size: 2060 lines)
The registry depends on nothing of the workspace crate. It now owns up() and slug(), which the workspace crate re-exports, and takes the controller ids named by the project's overrides as an argument. raea-app-workspace's registry module wraps scan() with them, read from .raea/project. raea context takes both the workspace's sections (controllers, project files) from one call, raea_app_workspace::context(), which keeps raea-cli at 1997 lines. Folded the copies L1 counted: Registry::warnings() and composition_files() replace the filters and sort in doctor and next, resolve() builds its candidates in a loop, and a line number is counted from the newlines before it (stamp.rs had the same line_starts). New test: an override naming a missing controller is linted once. raea-app-registry has 6 tests and raea-app-workspace 6.
2026-11-09 12:28:18 -08:00
shinyobjectz 0f6c275bdb Project registry lint: a path outside the project is written from ~ (~/.cache/raea-mocap/...), as a person reads it 2026-11-09 12:14:40 -08:00
shinyobjectz 9aaf3f21e6 Project registry (docs/projects.feature PJ8): one static reading of a project's compositions, components and controllers, and lint for what isn't connected
apps/workspace src/registry: each .tsx and .ts is parsed with oxc (the version engine/bundle uses), without running it. A composition is each <Composition> that a registerRoot registers, with its id, component, size, fps and length read from the source. A prop written as a top-level constant, or simple arithmetic on constants (const FPS = 30; 15 * FPS; edit.w; Math.round), is read as its value; anything else is kept as the expression. A .tsx whose default export no other file imports is registered under its file's name, sized from its newest render manifest. A component is a .tsx that a composition imports, directly or through another file. A controller is a module whose default export is controller({...}) from raea/brief.

Lint (each finding has a file:line and its fix): not-a-project, broken, orphan, unresolved, outside, duplicate-id, computed (info), unregistered (info; fixable when a manifest gives the size), controller-home (fixable: moved to controllers/<id>.ts), controller-duplicate, override-missing.

CLI: raea project scan [DIR] [--json]. raea doctor lists the warnings, and --fix registers a default export and moves a stray controller, committing only the files it touched. raea next reads compositions from the scan (no more grepping for registerRoot) and puts unconnected files first. raea context gains a PROJECT FILES section. Tests: 11 pass.
2026-11-09 12:03:32 -08:00
shinyobjectz 4b8157f98c A still of a 3D composition no plugin carries state for draws only its own frame, not every frame before it (#77). Every engine installs the plugin clock (some plugin is always registered), so catch_up rendered each frame before a still in full: render graph, shadow views and submit, about 90 ms a frame in a film, and --at 2448 took 226 s. The engine now steps through those frames only when the rows hold something a plugin carries from frame to frame (raea_runtime_plugins::steps): a component or resource of a type from outside Bevy's own scene and render crates and raea's (a rigid body, a particle effect, Bevy's animation, time or states; a short type name, which could be anyone's), a driven mesh, or a row kind not known to be frame-pure. Keyed component rows land on their frame however it is reached. The film's --at 2448: 226 s -> 20 s, pixel-identical; a physics still at frame 100 (avian) still steps all 100 frames. bench/at-cost checks that a frame-pure still steps none. 2026-11-09 11:18:41 -08:00
shinyobjectz d4a00c6044 Stills late in a long 3D composition no longer cost memory and time with the frame index (closes #77). A still at --at F stepped React only near F, but held every frame before it as copies; each changing column was keyed on every one of those frames, and the timeline evaluated and kept every frame (a film's --at 2448: 234 s and 7.1 GB, against 9 s and 3.1 GB at --at 30). The timeline (core/program) now evaluates only the frames where some key's value can change from the frame before, and a frame no key changes shares the frame before's columns. A column keyed one value a frame keeps only the keys where its value differs from a neighbour's (raea_runtime_look::linear_keys, also used by the scene's per-frame colours), which is exact under linear interpolation. 200 turning cubes at --at 2448: peak 829 MB -> 504 MB (1.32x the --at 30 peak, was 2.14x), engine open 700 ms -> 280 ms, and the frame is pixel-exact. bench/at-cost checks the ratio and the pixels. 2026-11-09 10:23:46 -08:00
shinyobjectzandJameschuthink 97d93d244f Direct render: the 2D image rows' Blitz page (a Bevy App) is made on its first draw, not with the view, so a render that never draws an image row makes none (closes #70)
rows2d::Rows keeps an Option<Page> built by page() on first use with the same arguments; draw returns R<bool>
since building can fail there now, and the engine's overlay (runtime/gpuframe overlay.rs) logs and skips that frame's
rows on an error, as it already does for rgba(). texture() is None before the first draw.

Checked on an M-series Mac, release build, RAEA_EXPORT_CACHE=0, a 30-frame 800x1000 TSX with a moving text box
(and the same with an <Img> on frames 10-19; a TSX page arrives on the GPU, so neither draws an image row): one
warm-up, then 5 runs each, two rounds in swapped order. Median 0.395 s -> 0.312 s (about 83 ms a render). Frames
identical by framemd5 on both, the <Img> red on exactly frames 10-19 in both builds.

Co-authored-by: Jameschuthink <[email protected]>
2026-11-09 08:46:40 -08:00
shinyobjectzandJameschuthink b800a1c5e1 raea-perceive: portable OCR fetches ocrs's .onnx models (the .rten copies answer 403), and the tool's vision-portable feature turns on its own ocr-portable and face-portable, so a vision-portable build has read-lines and the face commands (closes #69)
Checked on this Mac with an empty model cache: cargo build --release -p raea-perceive --features vision-portable,
then read-lines --backend ocrs and see-layout --backend portable on a HELLO WORLD picture both read the line (rc 0),
and the cache holds the two .onnx files.

Co-authored-by: Jameschuthink <[email protected]>
2026-11-09 08:46:17 -08:00
shinyobjectz 85f4f08e14 docs/manual/tutorials: Build and install plugins (install from npm, Git or a folder, read and approve, use in the feed, build one with reload on save, share it); narration to come 2026-11-09 08:45:34 -08:00
shinyobjectz d854f1a7af docs/manual/tutorials: Work as a team leaves out rendering across teammates' computers until that is built and tested 2026-11-09 08:25:31 -08:00
shinyobjectz 19acea76e4 docs/manual/tutorials: ten narrated tutorials, from getting started to storage and search
The scripts the docs' tutorial player narrates (Fish, through raea-api's speech) over the app's own screens on a made-up
workspace, Sunmelt: get started, connect your agent, a tour, review and notes, inspect, controllers, publish, extend
with the SDK, teams, and how storage (Git with LFS pointers, media by hash) and search (vectors in turbopuffer) work.
Each page carries its full narration as text; its front matter names the tutorial the page plays.
2026-11-09 08:25:31 -08:00
shinyobjectz ca69ed1094 docs/manual/guides: Build and share plugins (the manifest, where contributions show, @raea/app and its permissions, the sandbox and network, building with a folder install and hot reload, components for compositions, sharing on npm or Git, what isn't built) 2026-11-09 08:24:34 -08:00
shinyobjectz 41d22acc0c skills -> 0ae1e8e: plugins in the raea skill's references (raea-skills #15: feed_post's plugin type, ~/.raea/plugins) 2026-11-09 08:23:48 -08:00
shinyobjectz 8b94190778 Plugins a person installs: compositions import them after the project's own packages (engine/bundle edit.rs: RAEA_PLUGINS, else ~/.raea/plugins), and docs/ecosystem.feature records phase 2's start (the manifest, per-person installs, approval, permissions, a network allowlist; tools, panels and item types) and the two answered questions 2026-11-09 08:21:24 -08:00
shinyobjectz 4c9ddb3d42 skills -> 22dd7fc: artifacts in the raea skill (raea-skills #14: SKILL.md §5, feed.md's artifact type) 2026-11-09 07:49:03 -08:00
shinyobjectz 494711189a docs/ecosystem.feature: phase 1 narrowed to artifacts as agents' own code, and done (raea-feed cc4fe7d, 9f0ef35; raea-platform 90a6a03; raea-skills #14) 2026-11-09 07:47:40 -08:00
shinyobjectz b4b2f7f03c docs/ecosystem.feature: a plan for raea's plugin ecosystem, the engine and the app (Shane 11-09)
What exists, the two answers it rests on (the engine's extension surface is the SDK with native Bevy plugins under it;
the app is the side that needs a runtime: a loader, a sandbox, a bridge and hot reload, whose dev reload already
exists in blitz/dev.mjs), one package format for both, the engine's three tiers by how they load, the app's extension
host and its contribution points, sharing through npm with an index in raea-api, the phases, and four open questions.
2026-11-09 07:09:21 -08:00
1289 changed files with 335964 additions and 4358 deletions

No files matched your search

+9
View File
@@ -3,6 +3,15 @@
[target.aarch64-apple-darwin]
linker = "tools/link-jit.sh"
# every Windows executable's main thread gets 8 MB of stack, as on macOS and Linux (Windows' default is 1 MB). The
# desktop app's raea-page-host overflowed 1 MB inside a window callback (#112); engine/cli/build.rs did this for raea
# alone. A DLL's link ignores /STACK.
[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "link-arg=/STACK:8388608"]
[target.aarch64-pc-windows-msvc]
rustflags = ["-C", "link-arg=/STACK:8388608"]
# no strip after linking: rustc's strip pass re-signs the binary and drops the entitlement (release has no debug info
# of its own; std's stays)
[profile.release]
+6 -3
View File
@@ -1,11 +1,14 @@
{
"name": "raea",
"owner": { "name": "Shane Murphy", "url": "https://raea.io" },
"owner": { "name": "raea", "url": "https://raea.io" },
"metadata": {
"description": "raea's plugin for Claude, from the skills/ folder of shinyobjectz/raea-skills: the raea skill and its hooks."
},
"plugins": [
{
"name": "raea",
"source": "./",
"description": "Make video, motion graphics, games and 3D with raea, the Render Anything Engine."
"source": { "source": "git-subdir", "url": "https://github.com/shinyobjectz/raea-skills.git", "path": "skills" },
"description": "Make video, motion graphics, games and 3D scenes with raea, the Render Anything Engine: the raea skill, and hooks that run raea's quick check on a composition after it's saved and show media in the raea app instead of the Mac's viewer."
}
]
}
-11
View File
@@ -1,11 +0,0 @@
{
"name": "raea",
"version": "0.1.0",
"description": "Make video, motion graphics, games and 3D with raea, the Render Anything Engine: write raea compositions, render them on the GPU, check the frames.",
"author": { "name": "Shane Murphy", "url": "https://raea.io" },
"homepage": "https://raea.io",
"repository": "https://github.com/shinyobjectz/raea",
"license": "FSL-1.1-ALv2",
"skills": ["./skills/skills/raea"],
"keywords": ["video", "motion-graphics", "game-development", "rendering", "bevy", "react", "agent-skills"]
}
+7 -2
View File
@@ -61,7 +61,9 @@ jobs:
run: |
rustup show active-toolchain
sudo apt-get update && sudo apt-get install -y ripgrep
cargo install --locked cargo-shear cargo-dupes
# the versions L0 runs on the Mac, so a new release can't change the verdict (cargo-shear 1.14.1 calls
# engine/cli's feature-only ignores redundant, which 1.14.0 needs; both ran red on main 11-13)
cargo install --locked [email protected] [email protected]
- name: layers
run: bash tools/layers.sh
- name: names
@@ -113,4 +115,7 @@ jobs:
- name: cargo check
run: cargo check --locked -p raea-cli --tests
- name: unit tests (the crates with no GPU or media device)
run: cargo test --locked -p raea-io-media -p raea-core-fonts -p raea-native
# debug info off: with it the test binaries of the app crates filled 27 GB of a runner's disk (#90)
env:
CARGO_PROFILE_TEST_DEBUG: "0"
run: cargo test --locked -p raea-io-media -p raea-core-fonts -p raea-native -p raea-core-brief -p raea-core-k -p raea-bundle -p raea-app-check -p raea-app-check-flash -p raea-io-ffmpeg -p raea-app-workspace -p raea-app-tools -p raea-app-targets
+173 -10
View File
@@ -8,6 +8,11 @@
# git tag -a v0.1.0 -m "raea 0.1.0" -m "skills-passed: <full sha>"
# A tag with a suffix (v0.1.0-rc1, v0.1.0-canary.3) is made a pre-release; a plain version (v0.1.0) is a full release,
# GitHub's latest. The release's notes are set by hand.
# A release whose code is a candidate's is promoted, not compiled again (tools/release/promoted-from.sh: the tag's
# "promoted-from: v0.1.0-rc5" line, which tools/agents/release-go.sh writes): each job takes the candidate's attested
# binaries for its platform (tools/release/promoted-bins.sh) and packs, checks, attests and attaches them as the
# release, in minutes instead of the three hours a cold build takes. Run by hand, dry_run packs and checks without
# attesting or attaching (the archives are the run's artifacts), for trying a promote before the real one.
name: release
on:
@@ -23,6 +28,14 @@ on:
description: the full SHA where tools/skills.sh check passed with the feed app (else the tag's skills-passed line)
default: ""
type: string
promote_from:
description: a candidate tag (v0.1.0-rc5) whose binaries this release is, else the tag's promoted-from line; none builds from source
default: ""
type: string
dry_run:
description: pack and check only; nothing attested or attached (the archives are this run's artifacts)
default: false
type: boolean
permissions:
contents: write
@@ -47,15 +60,27 @@ jobs:
- os: ubuntu-24.04
lib: libraea_bundle.so
extra: raea-perceive
runs-on: ${{ matrix.os }}
# a faster runner when the repo names one: vars RELEASE_MAC_RUNNER, RELEASE_LINUX_RUNNER, RELEASE_WINDOWS_RUNNER hold
# a JSON list of runs-on labels (Namespace's: a machine and a cache volume); else GitHub's
# own, a 3-core M1 with 7 GB on the Mac, where a cold build took 3 hours
runs-on: ${{ (matrix.os == 'macos-15' && vars.RELEASE_MAC_RUNNER && fromJSON(vars.RELEASE_MAC_RUNNER)) || (matrix.os == 'ubuntu-24.04' && vars.RELEASE_LINUX_RUNNER && fromJSON(vars.RELEASE_LINUX_RUNNER)) || matrix.os }}
# a cold thin-LTO build of raea-cli with the plugin catalog is the long part; GitHub's own limit is 6 hours
timeout-minutes: 340
env:
# the compile cache (the "Compile cache" step): an R2 bucket, read and written by every build
RELEASE_CACHE_ENDPOINT: ${{ secrets.RELEASE_CACHE_ENDPOINT }}
AWS_ACCESS_KEY_ID: ${{ secrets.RELEASE_CACHE_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.RELEASE_CACHE_SECRET }}
steps:
- uses: actions/checkout@v4
with:
ref: ${{ env.TAG }}
submodules: true
lfs: false
- name: Promoted from a candidate, or built (tools/release/promoted-from.sh)
env:
GH_TOKEN: ${{ github.token }}
run: bash tools/release/promoted-from.sh "$TAG" "${{ inputs.promote_from }}"
- name: Linux libraries
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y cmake ninja-build nasm libxkbcommon-dev libxkbcommon-x11-dev libasound2-dev libfontconfig1-dev libvulkan-dev libudev-dev mesa-vulkan-drivers xvfb
@@ -75,18 +100,74 @@ jobs:
curl -fsSL "$url" -o "$HOME/.local/share/raea-models/$path"
echo "$sha $HOME/.local/share/raea-models/$path" | shasum -a 256 -c -
done < tools/release/models.tsv
# rc3's build left 576 MB of macos-15's 320 GB free, and rc4's dSYMs (#88) ran it out linking raea-page-host
# (ld: write() failed, errno=28): the image's other Xcodes and the Android and .NET SDKs go first
- name: Room for the build
if: runner.os == 'macOS' && env.RAEA_PROMOTED_FROM == '' && vars.RELEASE_MAC_RUNNER == ''
run: |
df -h . | tail -1
keep=$(cd "$(xcode-select -p)/../.." && pwd -P)
for x in /Applications/Xcode*.app; do [ -L "$x" ] || [ "$(cd "$x" && pwd -P)" = "$keep" ] || sudo rm -rf "$x" & done
sudo rm -rf "$HOME/Library/Android" "$HOME/.dotnet" /usr/local/share/dotnet &
wait
echo "kept $keep"
df -h . | tail -1
# The compile cache: sccache on an R2 bucket. GitHub's own cache can't carry a release build: a tag's run reads
# only its own tag's caches and the default branch's (so rc3's never reached rc4), and the repo's 10 GB are CI's.
# A bucket is read by every tag. A cold build fills it; a candidate after a small change compiles only the crates
# that changed and the ones above them. Linking (thin LTO) and build scripts' runs aren't cached. With no secrets
# (a fork) the build runs as before, uncached.
# the build folder and cargo's downloads kept between runs on the runner's cache volume (a Namespace runner,
# whose labels attach one), so a candidate rebuilds only what changed and links;
# sccache below still serves the workspace's own crates, which a fresh checkout's file times mark as changed
- name: The build folder, kept on the runner's cache volume
if: env.RAEA_PROMOTED_FROM == '' && startsWith(runner.name, 'nsc-')
uses: namespacelabs/nscloud-cache-action@v1
with:
path: |
${{ github.workspace }}/target
~/.cargo/registry
~/.cargo/git
- name: Compile cache (sccache)
if: env.RAEA_PROMOTED_FROM == '' && env.AWS_ACCESS_KEY_ID != ''
uses: mozilla-actions/[email protected]
# the script from this workflow's own commit: a dispatched run (a dry run that fills the cache) builds an older
# tag, whose tree may not have it
- name: The compile cache's script
if: env.RAEA_PROMOTED_FROM == '' && env.AWS_ACCESS_KEY_ID != ''
uses: actions/checkout@v4
with:
ref: ${{ github.sha }}
path: .workflow
sparse-checkout: tools/release/compile-cache.sh
sparse-checkout-cone-mode: false
- name: Use the compile cache
if: env.RAEA_PROMOTED_FROM == '' && env.AWS_ACCESS_KEY_ID != ''
run: bash .workflow/tools/release/compile-cache.sh
- name: Build
if: env.RAEA_PROMOTED_FROM == ''
run: |
feat=$(bash tools/bevy-plugins.sh features sdk/raea/bench/bevy-plugins)
cargo build --profile dist --locked -p raea-cli --bin raea --no-default-features --features "$feat"
cargo build --profile dist --locked -p raea-rune-host
cargo build --profile dist --locked -p raea-page-host --features window
if [ -n "${{ matrix.extra }}" ]; then cargo build --profile dist --locked -p ${{ matrix.extra }}; fi
t() { s=$SECONDS; "$@"; echo "::notice::${{ runner.os }} $(( (SECONDS - s) / 60 )) min: ${*:7}"; }
t cargo build --profile dist --locked -p raea-cli --bin raea --no-default-features --features "$feat"
t cargo build --profile dist --locked -p raea-rune-host
t cargo build --profile dist --locked -p raea-page-host --features window
if [ -n "${{ matrix.extra }}" ]; then t cargo build --profile dist --locked -p ${{ matrix.extra }}; fi
if [ -n "${RUSTC_WRAPPER:-}" ]; then sccache --show-stats; fi
mkdir ship
cp target/dist/raea target/dist/${{ matrix.lib }} target/dist/raea-rune-host target/dist/raea-page-host ship/
if [ -n "${{ matrix.extra }}" ]; then cp target/dist/${{ matrix.extra }} ship/; fi
# the Mac's dSYMs (tools/link-jit.sh made them as it stripped each binary, #88); release.sh keeps them
if [ -d target/dist/symbols ]; then cp -R target/dist/symbols ship/; fi
- name: The candidate's binaries (tools/release/promoted-bins.sh)
if: env.RAEA_PROMOTED_FROM != ''
env:
GH_TOKEN: ${{ github.token }}
run: bash tools/release/promoted-bins.sh "$RAEA_PROMOTED_FROM" ship
# the packing and its checks need only ship/, and macos-15's disk ran out packing rc1 with target/ kept
- name: Free the build's disk
# not the cache volume's build folder, which the next candidate starts from (a bind mount on Linux)
if: ${{ !startsWith(runner.name, 'nsc-') }}
run: |
df -h . | tail -1
rm -rf target
@@ -110,22 +191,43 @@ jobs:
${{ runner.temp }}/release-check/**/*.log
retention-days: 7
if-no-files-found: ignore
# the stripped binaries' symbols (#88), for symbolicating a crash report from this release; never published
- uses: actions/upload-artifact@v4
with:
name: symbols-${{ runner.os }}
path: dist/raea-*-symbols
retention-days: 90
if-no-files-found: warn
- uses: actions/attest-build-provenance@v2
if: ${{ !inputs.dry_run }}
with:
subject-path: dist/raea-*.tar.gz
- name: Attach to the release
if: ${{ !inputs.dry_run }}
env:
GH_TOKEN: ${{ github.token }}
run: |
gh release view "$TAG" >/dev/null 2>&1 || gh release create "$TAG" ${{ contains(env.TAG, '-') && '--prerelease' || '' }} --title "raea ${TAG#v}" --notes "Built by .github/workflows/release.yml; notes follow."
gh release upload "$TAG" dist/raea-*.tar.gz dist/raea-*.tar.gz.sha256 --clobber
- uses: actions/upload-artifact@v4
if: ${{ inputs.dry_run }}
with:
name: dry-run-${{ runner.os }}
path: dist/raea-*.tar.gz*
retention-days: 3
compression-level: 0
# Windows in Git's bash on GitHub's runner, with the Visual Studio Build Tools in its image (their image terms; we
# accept no licence and download no Microsoft files). The C runtime is the DLL one (the VC++ redistributable): ort's
# prebuilt ONNX Runtime is built against it, so crt-static doesn't link (LNK2019 on __imp_ symbols, 10-29).
windows:
runs-on: windows-latest
runs-on: ${{ (vars.RELEASE_WINDOWS_RUNNER && fromJSON(vars.RELEASE_WINDOWS_RUNNER)) || 'windows-latest' }}
timeout-minutes: 350
env:
# the compile cache, as build's
RELEASE_CACHE_ENDPOINT: ${{ secrets.RELEASE_CACHE_ENDPOINT }}
AWS_ACCESS_KEY_ID: ${{ secrets.RELEASE_CACHE_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.RELEASE_CACHE_SECRET }}
defaults:
run:
shell: bash
@@ -135,8 +237,28 @@ jobs:
ref: ${{ env.TAG }}
submodules: true
lfs: false
- name: Promoted from a candidate, or built (tools/release/promoted-from.sh)
env:
GH_TOKEN: ${{ github.token }}
run: bash tools/release/promoted-from.sh "$TAG" "${{ inputs.promote_from }}"
- name: Toolchain (rust-toolchain.toml's pin)
if: env.RAEA_PROMOTED_FROM == ''
run: rustup show active-toolchain || rustup toolchain install
# nasm, which rav1d's and openh264-sys2's build scripts run: GitHub's Windows image has 2.16, Namespace's has none
# (rc3's dry run there stopped at "Unable to run nasm: program not found"). Always NASM's own 2.16.03 zip, never
# Chocolatey's: rc4 took Chocolatey's newest, and raea.exe failed to link 135 of openh264's SIMD routines
# (WelsSampleSad16x8_sse2 and the rest unresolved) though openh264's C++ was built to call them
- name: nasm
if: env.RAEA_PROMOTED_FROM == ''
run: |
v=2.16.03
curl -fsSL --retry 3 -o "$RUNNER_TEMP/nasm.zip" "https://www.nasm.us/pub/nasm/releasebuilds/$v/win64/nasm-$v-win64.zip"
unzip -q "$RUNNER_TEMP/nasm.zip" -d "$RUNNER_TEMP"
# Git Bash on Windows has no /dev/stderr (rc5 stopped here): capture, print, then match
out=$("$RUNNER_TEMP/nasm-$v/nasm.exe" -v)
echo "$out"
case $out in *"version $v"*) ;; *) echo "::error::expected NASM $v, got: $out"; exit 1 ;; esac
echo "$RUNNER_TEMP/nasm-$v" >> "$GITHUB_PATH"
# jq for Windows ends -r lines with CRLF, so tools/bevy-plugins.sh read "ahoy\r" and lost its Bevy 0.20 block
# (feature `ahoy` not found, 11-04); -b writes LF
- name: jq that writes LF
@@ -161,13 +283,52 @@ jobs:
done < <(tr -d '\r' < tools/release/models.tsv)
# the app targets' hosts a cargo call each: with raea-cli's crates in one call taffy's features unify and
# rune-taffy doesn't build; raea-perceive (`raea song`'s map, #43) a call of its own too
- name: The build folder, kept on the runner's cache volume (as build's)
if: env.RAEA_PROMOTED_FROM == '' && startsWith(runner.name, 'nsc-')
uses: namespacelabs/nscloud-cache-action@v1
with:
path: |
${{ github.workspace }}/target
~/.cargo/registry
~/.cargo/git
- name: Compile cache (sccache, as build's)
if: env.RAEA_PROMOTED_FROM == '' && env.AWS_ACCESS_KEY_ID != ''
uses: mozilla-actions/[email protected]
# the script from this workflow's own commit: a dispatched run (a dry run that fills the cache) builds an older
# tag, whose tree may not have it
- name: The compile cache's script
if: env.RAEA_PROMOTED_FROM == '' && env.AWS_ACCESS_KEY_ID != ''
uses: actions/checkout@v4
with:
ref: ${{ github.sha }}
path: .workflow
sparse-checkout: tools/release/compile-cache.sh
sparse-checkout-cone-mode: false
- name: Use the compile cache
if: env.RAEA_PROMOTED_FROM == '' && env.AWS_ACCESS_KEY_ID != ''
run: bash .workflow/tools/release/compile-cache.sh
# openh264-sys2 is built here every time, never taken whole from the cache volume's target/: a build of it whose
# assembly didn't make it into the rlib (0.1.3-rc4's Chocolatey nasm) stays fresh to cargo on a restored target/,
# and every link after it fails on the same 135 SIMD routines (v0.1.4-rc1, 11-14: only raea-cli compiled, then
# WaverageChromaFilter8_sse2 and the rest unresolved). Its C++ comes back from sccache; the assembly is seconds
- name: openh264 built here, not restored
if: env.RAEA_PROMOTED_FROM == ''
run: rm -rf target/dist/build/openh264-sys2-* target/dist/deps/libopenh264_sys2-* target/dist/.fingerprint/openh264-sys2-*
- name: Build
if: env.RAEA_PROMOTED_FROM == ''
run: |
feat=$(bash tools/bevy-plugins.sh features sdk/raea/bench/bevy-plugins)
cargo build --profile dist --locked -p raea-cli --bin raea --no-default-features --features "$feat"
cargo build --profile dist --locked -p raea-rune-host
cargo build --profile dist --locked -p raea-page-host --features window
cargo build --profile dist --locked -p raea-perceive
t() { s=$SECONDS; "$@"; echo "::notice::Windows $(( (SECONDS - s) / 60 )) min: ${*:7}"; }
t cargo build --profile dist --locked -p raea-cli --bin raea --no-default-features --features "$feat"
t cargo build --profile dist --locked -p raea-rune-host
t cargo build --profile dist --locked -p raea-page-host --features window
t cargo build --profile dist --locked -p raea-perceive
if [ -n "${RUSTC_WRAPPER:-}" ]; then sccache --show-stats; fi
- name: The candidate's binaries (tools/release/promoted-bins.sh)
if: env.RAEA_PROMOTED_FROM != ''
env:
GH_TOKEN: ${{ github.token }}
run: bash tools/release/promoted-bins.sh "$RAEA_PROMOTED_FROM" target/dist
# which DLLs raea needs from the machine (the CRT's come from the VC++ redistributable)
- name: What raea.exe imports
run: |
@@ -217,6 +378,7 @@ jobs:
for n in $(sed -n 's/^\([^ ]*\) (.*): OPEN.*/\1/p' "$RUNNER_TEMP/play.txt"); do echo "--- $n"; { grep -v "known driver" "$out/$n.log" || echo "(its log is empty)"; } | tail -25; done
exit $s
- uses: actions/attest-build-provenance@v2
if: ${{ !inputs.dry_run }}
with:
subject-path: dist/raea-*.zip
# kept even when its check fails, with the check's own files, so a failure can be looked into on a fresh runner
@@ -290,6 +452,7 @@ jobs:
if ($LASTEXITCODE -or -not (Test-Path hello.png)) { throw "raea render failed" }
Get-Item hello.png | Format-List Name, Length
- name: Attach to the release
if: ${{ !inputs.dry_run }}
env:
GH_TOKEN: ${{ github.token }}
run: |
Generated
+551 -14
View File
File diff suppressed because it is too large. Load diff
+32
View File
@@ -5,6 +5,7 @@ resolver = "2"
members = [
"core/animate",
"core/brief",
"core/facts",
"core/ease",
"core/fonts",
"core/program",
@@ -52,6 +53,7 @@ members = [
"engine/rune/js",
"engine/rune/layer",
"engine/rune/slots",
"engine/page/sound",
"engine/page/stage",
"engine/page/window",
"io/trace",
@@ -61,12 +63,15 @@ members = [
"io/gen",
"io/gen-comfy",
"io/gen-core",
"io/gen-fit",
"io/home",
"io/soft",
"io/av1",
"io/ffmpeg",
"io/apple",
"io/apple-coding",
"io/alpha",
"io/capcut",
"io/shell",
"gpu/device",
"core/k",
@@ -75,9 +80,14 @@ members = [
"systems/tone",
"systems/mix",
"systems/ml",
"systems/mlx",
"systems/speech",
"systems/layout",
"systems/vision",
"systems/columns",
"systems/fingerprint",
"systems/fingerprint-use",
"systems/fingerprint-things",
"systems/song",
"systems/perceive",
"systems/footage",
@@ -85,6 +95,7 @@ members = [
"systems/bake",
"systems/contact",
"systems/light-meter",
"systems/measure",
"systems/canvas",
"systems/tweak",
"systems/filters",
@@ -94,6 +105,8 @@ members = [
"systems/page-net",
"systems/page-ops",
"systems/frame",
"systems/hold",
"systems/layers",
"systems/splat",
"systems/sprite",
"systems/rt",
@@ -118,8 +131,10 @@ members = [
"systems/image",
"runtime/twins",
"runtime/dom",
"runtime/dom/media",
"runtime/edit",
"runtime/view",
"runtime/world",
"runtime/encode",
"runtime/plugins",
"runtime/input",
@@ -129,15 +144,21 @@ members = [
"engine/seedling",
"engine/web",
"runtime/react",
"runtime/track",
"runtime/pagestore",
"runtime/cssurls",
"bench/bridge",
"bench/bevy-parity",
"bench/bridge/swatch",
"bench/rerender/ios",
"core/alloc",
"runtime/bake",
"runtime/bundle",
"runtime/bundle/lib",
"engine/shape-web",
"runtime/calls",
"runtime/shots",
"runtime/canvas",
"runtime/export",
"runtime/live",
"runtime/page",
@@ -147,14 +168,23 @@ members = [
"runtime/scene2d",
"runtime/shared",
"apps/check",
"apps/check/flash",
"apps/direction",
"apps/notes",
"apps/fingerprint",
"apps/sound",
"apps/workspace",
"apps/workspace/registry",
"apps/ci",
"apps/tools",
"apps/engines",
"apps/interchange",
"apps/judge",
"apps/solid",
"apps/media",
"apps/targets",
"apps/game",
"apps/capcut",
"apps/play",
"tools/sdk-props",
]
@@ -263,6 +293,8 @@ split-debuginfo = "packed"
[patch.crates-io]
# the MP4 muxer, vendored
muxide = { path = "vendor/muxide" }
# usvg 0.48.1 spacing a chunk's last letter as Chrome does (changes marked "raea:", docs/layout-reads.feature LR10)
usvg = { path = "vendor/usvg" }
# bevy_seedling 0.8.0 without its cpal 0.18 paths, ported to Bevy 0.20 (changes marked "raea:")
bevy_seedling = { path = "vendor/bevy_seedling" }
# bevy_text 0.20.0 on parley 0.12, so one parley builds (changes marked "raea:", docs/bevy-upgrade.md)
-25
View File
@@ -1,25 +0,0 @@
Copyright (c) 2018 Raph Levien
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
-19
View File
@@ -1,19 +0,0 @@
Copyright (c) 2014-2020 Optimal Computing (NZ) Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
-176
View File
@@ -1,176 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
-20
View File
@@ -1,20 +0,0 @@
meshopt 0.6.2 ships no licence file of its own. Its Cargo.toml declares MIT OR Apache-2.0, by Graham Wihlidal <[email protected]>.
---- Apache-2.0: the text is LICENSES/texts/Apache-2.0.txt ----
---- MIT ----
Copyright (c) Graham Wihlidal <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-176
View File
@@ -1,176 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
-25
View File
@@ -1,25 +0,0 @@
Copyright 2020 the Vello Authors
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
-176
View File
@@ -1,176 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
-25
View File
@@ -1,25 +0,0 @@
Copyright 2020 the Vello Authors
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
@@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-25
View File
@@ -1,25 +0,0 @@
Copyright (c) 2019-2026 The RustCrypto Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
-7
View File
@@ -192,13 +192,11 @@ LICENSES/<crate>-<version>/.
fast_image_resize 6.1.0: MIT OR Apache-2.0
fastbloom 0.17.0: MIT OR Apache-2.0
fastnoise-lite 1.1.1: MIT
fearless_simd 0.4.1: Apache-2.0 OR MIT
fid-rs 0.2.0: MIT OR Apache-2.0
file-id 0.2.3: MIT OR Apache-2.0
fixed 1.31.0: MIT/Apache-2.0
flagset 0.4.7: Apache-2.0
float_next_after 2.0.0: MIT
float-cmp 0.10.0: MIT
float-ord 0.3.2: MIT / Apache-2.0
fs_extra 1.3.0: MIT
fsevent-sys 4.1.0: MIT
@@ -211,7 +209,6 @@ LICENSES/<crate>-<version>/.
ghx_proc_gen 0.10.0: MIT OR Apache-2.0
glam_matrix_extras 0.4.0: MIT OR Apache-2.0
glam 0.19.0: MIT OR Apache-2.0
glifo 0.2.0: Apache-2.0 OR MIT
gloo-timers 0.3.0: MIT OR Apache-2.0
governor 0.10.4: MIT
hash32 0.2.1: MIT OR Apache-2.0
@@ -276,7 +273,6 @@ LICENSES/<crate>-<version>/.
louds-rs 0.7.0: MIT OR Apache-2.0
lz4_flex 0.13.1: MIT
memoffset 0.9.1: MIT
meshopt 0.6.2: MIT OR Apache-2.0
metis-sys 0.3.2: MIT OR Apache-2.0
metis 0.2.2: MIT OR Apache-2.0
metrics-util 0.20.4: MIT
@@ -401,8 +397,6 @@ LICENSES/<crate>-<version>/.
unsafe-libyaml 0.2.11: MIT
urlencoding 2.1.3: MIT
usvg 0.45.1: Apache-2.0 OR MIT
vello_common 0.1.0: Apache-2.0 OR MIT
vello_cpu 0.1.0: Apache-2.0 OR MIT
vleue_navigator 0.17.0: MIT OR Apache-2.0
voracious_radix_sort 1.2.0: MIT
vox_bake 0.1.0: MIT
@@ -434,7 +428,6 @@ LICENSES/<crate>-<version>/.
zbus 5.19.0: MIT
zbus 6.2.1: MIT
zcheapstr 1.1.0: MIT
zeroize_derive 1.5.0: Apache-2.0 OR MIT
zruntime 0.2.2: MIT
zstd-safe 7.4.0: BSD-3-Clause
zstd-sys 2.1.2+zstd.1.5.7: BSD-3-Clause
+12 -4
View File
@@ -24,7 +24,7 @@
<p align="center">
<img alt="licence FSL-1.1-ALv2" src="https://img.shields.io/badge/licence-FSL--1.1--ALv2-black">
<img alt="status canary" src="https://img.shields.io/badge/status-canary-black">
<img alt="latest release" src="https://img.shields.io/github/v/release/shinyobjectz/raea?label=release&color=black">
<img alt="macOS, Apple Silicon" src="https://img.shields.io/badge/macOS-Apple%20Silicon-black">
<img alt="Linux x86_64" src="https://img.shields.io/badge/Linux-x86__64-black">
<img alt="Windows x86_64" src="https://img.shields.io/badge/Windows-x86__64-black">
@@ -32,8 +32,14 @@
---
> **Canary.** raea changes daily. Releases run on macOS (Apple Silicon), Linux (x86_64) and, new and least tested,
> Windows (x86_64). Expect breaking changes, rough edges and gaps in the docs.
> **v0.1.1** is raea's first full release: the engine and, for the first time, the desktop app, on macOS (Apple
> Silicon), Linux (x86_64) and, newest and least tested, Windows (x86_64). raea is young: expect rough edges and gaps
> in the docs.
## The app
The raea app is where you make video and games with your AI. Download it from [raea.io](https://raea.io) for the Mac,
Windows or Linux. It tells you when a new version is out; on the Mac it updates itself.
## Install
@@ -97,7 +103,9 @@ floor (`raea check hello.mp4`). `raea init` starts a project, and `raea --help`
- **Agent skills.** They live in [raea-skills](https://github.com/shinyobjectz/raea-skills), pinned here as
[`skills/`](skills): `raea` teaches an agent to write, render and check raea compositions, 3D and games
included. The installer adds it to `~/.claude/skills`, and `raea skills install --agent NAME` to other agents.
- **Claude Code plugin.** `/plugin marketplace add shinyobjectz/raea`, then `/plugin install raea@raea`.
- **Claude plugin.** The raea skill and two hooks (raea's quick check after a composition is saved, and media shown in
the raea app). In Claude Code: `/plugin install raea --marketplace shinyobjectz/raea-skills`. It's the `skills/`
folder of raea-skills, and `/plugin marketplace add shinyobjectz/raea` installs the same one.
- **Craft guides.** `raea guide` prints the floor every edit is held to and the guides for pitches, explainers, stories,
games, motion, music and layout. `raea context PROJECT` says what to read before working on a project.
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "raea-app-capcut"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "`raea export capcut`: a composition as a CapCut draft ready in its timeline, its footage and sounds as clips of their files and what raea draws as transparent overlays (docs/capcut.feature)"
[dependencies]
raea-runtime-bundle = { path = "../../runtime/bundle" }
raea-io-capcut = { path = "../../io/capcut" }
raea-io-alpha = { path = "../../io/alpha" }
raea-io-media = { path = "../../io/media", default-features = false, features = ["soft-audio", "apple"] }
raea-io-home = { path = "../../io/home" }
# the renderer's own lookup of a staticFile path (/media/x), so the export finds the files the render drew
raea-core-scene = { path = "../../core/scene" }
serde_json = "1"
image = { version = "0.25", default-features = false, features = ["jpeg"] }
+292
View File
@@ -0,0 +1,292 @@
//! `raea export capcut EDIT.tsx` (docs/capcut.feature CC2): the composition as a CapCut draft ready in its timeline.
//! And `raea render ... -o OUT.mov --alpha` (CC1), the transparent movie its overlays are, for any editor.
//! Three renders of it: as it is, with its manifest (the reference render, and what shows when: each file's runs,
//! each sound clip); with its footage and the backgrounds holding it hidden, transparent (what raea draws over the
//! footage); and with only those backgrounds (what it draws under). The footage and sounds become clips of their own
//! files at their trims and gains; what raea draws becomes clips of transparent movies (raea-io-alpha), cut where the
//! drawing comes and goes, the one under the footage left out when it's black; raea-io-capcut writes the draft.
mod media;
pub mod plan;
#[cfg(test)]
mod tests;
use std::path::{Path, PathBuf};
use std::process::Command;
use raea_io_capcut::{Clip, Kind, Media, MediaKind, Place, Timeline, Track};
use raea_runtime_bundle::flag;
use serde_json::Value;
pub type R<T> = Result<T, String>;
pub const USAGE: &str = "raea export capcut EDIT.tsx [--composition ID] [-o DIR] [--name NAME] [--alpha-codec prores|hevc|rle|png] [--no-register] (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; into CapCut's projects, entered in its project list while CapCut is closed, or a draft folder in DIR; the reference render and the overlay movie kept in out/capcut/NAME)";
/// `export capcut ...` (or what export takes), and `render ... -o OUT.mov --alpha` through `render`, the CLI's own;
/// None for anything else.
pub fn cli(args: &[String], render: impl Fn(&[String]) -> R<String>) -> Option<R<String>> {
match args.first().map(String::as_str) {
Some("export") => Some(match args.get(1).map(String::as_str) {
Some("capcut") => export(&args[2..]),
other => Err(format!("raea export takes where to export to{}: capcut\nusage: {USAGE}", other.map_or(String::new(), |o| format!(", not {o:?}")))),
}),
Some("render") => movie(args, render),
_ => None,
}
}
/// `render ... -o OUT.mov --alpha`: the frames as transparent PNGs, then one movie of them, the overlay an editor lays
/// over footage (raea-io-alpha, docs/capcut.feature CC1); None for any other render.
fn movie(args: &[String], render: impl Fn(&[String]) -> R<String>) -> Option<R<String>> {
let out = flag(args, "-o").filter(|o| args.iter().any(|a| a == "--alpha") && o.to_lowercase().ends_with(".mov"))?;
let quality = match flag(args, "--quality").map(|q| raea_io_media::parse_quality(&q)).transpose() {
Ok(q) => q.unwrap_or(0.9),
Err(e) => return Some(Err(e.to_string())),
};
Some(raea_io_alpha::render_movie(args, Path::new(&out), flag(args, "--alpha-codec").as_deref(), flag(args, "--manifest").map(PathBuf::from), quality, render))
}
/// `raea render ARGS` by this same program, with `env` set; its output said through, its failure the export's.
fn render(args: &[String], env: &[(&str, &str)]) -> R<()> {
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let mut c = Command::new(exe);
c.arg("render").args(args);
for (k, v) in env {
c.env(k, v);
}
let out = c.output().map_err(|e| e.to_string())?;
if !out.status.success() {
let said = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
return Err(format!("the render failed:\n{}", said.trim()));
}
Ok(())
}
fn export(args: &[String]) -> R<String> {
let tsx = args.first().filter(|a| !a.starts_with('-')).ok_or(USAGE)?;
let tsx = PathBuf::from(tsx).canonicalize().map_err(|e| format!("{tsx}: {e}"))?;
let dir = tsx.parent().unwrap().to_path_buf();
let codec = flag(args, "--alpha-codec").map_or(Ok(raea_io_alpha::Codec::default_here()), |c| raea_io_alpha::Codec::parse(&c))?;
let (root, in_store) = match flag(args, "-o") {
Some(o) => (PathBuf::from(o), false),
None => {
let s = raea_io_capcut::store_root().ok_or("CapCut keeps its projects only on a Mac or Windows: -o DIR writes the draft folder anywhere")?;
if !s.parent().is_some_and(Path::exists) {
return Err(format!("CapCut hasn't kept a project on this machine ({} isn't there): open CapCut once, or write the draft folder with -o DIR", s.display()));
}
if !args.iter().any(|a| a == "--no-register") && raea_io_capcut::capcut_running() {
return Err("CapCut is open: it rewrites its project list when it quits, which would drop the new draft from it. Quit CapCut and export again, or pass --no-register (the draft lands in its folder, unlisted) or -o DIR".into());
}
(s, true)
}
};
let stem = tsx.file_stem().unwrap().to_string_lossy().into_owned();
let mut name = flag(args, "--name").unwrap_or(stem);
if root.join(&name).exists() {
let base = name.clone();
name = (2..).map(|k| format!("{base} {k}")).find(|n| !root.join(n).exists()).unwrap();
}
let work = dir.join("out/capcut").join(&name);
std::fs::create_dir_all(&work).map_err(|e| format!("{}: {e}", work.display()))?;
let comp: Vec<String> = flag(args, "--composition").map(|c| vec!["--composition".into(), c]).unwrap_or_default();
let s = |p: &Path| p.display().to_string();
// 1. as it is: the reference render and its manifest
let (reference, manifest_path) = (work.join("reference.mp4"), work.join("render.json"));
render(&[[s(&tsx), "-o".into(), s(&reference), "--manifest".into(), s(&manifest_path)].as_slice(), &comp].concat(), &[])?;
let manifest: Value = serde_json::from_str(&std::fs::read_to_string(&manifest_path).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
let (w, h, fps) = (manifest["width"].as_u64().unwrap_or(0) as u32, manifest["height"].as_u64().unwrap_or(0) as u32, manifest["fps"].as_f64().unwrap_or(30.0));
let (wf, hf) = (w as f64, h as f64);
// 2. its footage hidden, transparent: what raea draws over it
let runs = plan::runs(&manifest, fps);
let frames = work.join(format!("overlay.{}.frames", std::process::id()));
let drawn_result = render(&[[s(&tsx), "-o".into(), format!("{}/", frames.display()), "--alpha".into()].as_slice(), &comp].concat(), &[("RAEA_HIDE_MEDIA", "1")]);
// footage the overlay covers (opaque over most of its box at its middle frame) is drawn over the overlay: what the
// composition draws under it, a background
let covered: Vec<bool> = runs.iter().map(|r| drawn_result.is_ok() && opaque_under(&frames, r)).collect();
let overlay = work.join(format!("overlay.{}.mov", ext_of(codec)));
let made = drawn_result.and_then(|_| raea_io_alpha::encode_dir(&frames, &overlay, codec, fps, 0.9));
// the frames folder this export made, and only it
let _ = std::fs::remove_dir_all(&frames);
let made = made?;
// 3. only the backgrounds holding the footage: what raea draws under it, unless that's black (CapCut's canvas)
let under = if runs.is_empty() {
None
} else {
let frames = work.join(format!("under.{}.frames", std::process::id()));
let out = work.join(format!("under.{}.mov", ext_of(codec)));
let done = render(&[[s(&tsx), "-o".into(), format!("{}/", frames.display()), "--alpha".into()].as_slice(), &comp].concat(), &[("RAEA_HIDE_MEDIA", "under")])
.and_then(|_| if lit(&frames) { raea_io_alpha::encode_dir(&frames, &out, codec, fps, 0.9).map(|m| Some((out, m))) } else { Ok(None) });
let _ = std::fs::remove_dir_all(&frames);
done?
};
// 4. the timeline
let mut notes: Vec<String> = Vec::new();
let mut media: Vec<Media> = Vec::new();
let mut index = std::collections::HashMap::<PathBuf, usize>::new();
let mut sounds = plan::sounds(&manifest);
let (mut main, mut rest, mut above) = (Vec::new(), Vec::new(), Vec::new());
for (r, cov) in runs.iter().zip(&covered) {
let path = plan::resolve(&dir, &r.src);
let m = add(&mut media, &mut index, path.clone(), media::video)?;
let (mw, mh) = (media[m].width as f64, media[m].height as f64);
let (place, warn) = plan::place(&r.bx, &r.fit, mw.max(1.0), mh.max(1.0), wf, hf, r.opacity);
let what = format!("{} (frames {}-{})", r.src, r.start, r.end - 1);
if let Some(wn) = warn {
notes.push(format!("{what}: {wn}"));
}
if r.moved {
notes.push(format!("{what}: moves or scales in its box; placed as its first frame shows it (CapCut keyframes don't carry yet)"));
}
if r.faded {
notes.push(format!("{what}: fades; placed at its first frame's opacity"));
}
// its own sound: the manifest's sound clip of the same file over the same frames from the same time
let own = sounds.iter().position(|c| plan::resolve(&dir, &c.src) == path && (c.from - r.start).abs() <= 1 && (c.to - r.end).abs() <= 1 && (c.at - r.at).abs() <= 1.5 / fps);
let volume = own.map_or(0.0, |k| 10f64.powf(sounds.remove(k).gain_db / 20.0));
let clip = Clip { media: m, start: r.start, frames: r.end - r.start, source_in: r.at, speed: r.rate.unwrap_or(1.0).max(0.01), volume, place, ..Clip::default() };
if *cov {
notes.push(format!("{what}: raea draws over all of it from outside what holds it (a layer before it in the page); placed over the overlay, so the overlay's drawing over it is hidden in CapCut"));
}
match (*cov, plan::full(&r.bx, wf, hf)) {
(true, _) => above.push(clip),
(false, true) => main.push(clip),
(false, false) => rest.push(clip),
}
}
// the main track first (the clips covering the canvas), the rest above it in the page's order, then the overlay,
// then footage the overlay draws under
let mut tracks: Vec<Track> = Vec::new();
if let Some((path, m)) = &under {
tracks.extend(drawn(&mut media, path, m, fps, "raea under"));
}
tracks.extend(plan::lay(Kind::Video, if under.is_some() { "footage" } else { "" }, main));
tracks.extend(plan::lay(Kind::Video, "footage", rest));
tracks.extend(drawn(&mut media, &overlay, &made, fps, "raea overlay"));
tracks.extend(plan::lay(Kind::Video, "footage over", above));
let mut audio = Vec::new();
for c in sounds {
let m = add(&mut media, &mut index, plan::resolve(&dir, &c.src), media::sound)?;
audio.push(Clip { media: m, start: c.from, frames: c.to - c.from, source_in: c.at, speed: c.rate, volume: 10f64.powf(c.gain_db / 20.0), fade_in: c.fade_in, fade_out: c.fade_out, ..Clip::default() });
}
tracks.extend(plan::lay(Kind::Audio, "sound", audio));
let notes_made = manifest["sounds"]["notes"].as_array().map_or(0, Vec::len);
if notes_made > 0 {
notes.push(format!("the Tone graph's music ({notes_made} notes) has no file to place: it is in the reference render's sound"));
}
let tl = Timeline { width: w, height: h, fps, media, tracks };
// 5. the draft
let markers = raea_io_capcut::seed(&root);
let written = raea_io_capcut::write(&tl, &root, &name, &markers, media::cover(&reference).as_deref())?;
notes.extend(written.warnings.iter().cloned());
let listed = if !in_store || args.iter().any(|a| a == "--no-register") {
"not entered in CapCut's project list".to_string()
} else {
match raea_io_capcut::register(&root, &written.dir, &written.meta, written.info_bytes, &backups()) {
Ok(b) => format!("entered in CapCut's project list (its list before: {})", b.display()),
Err(e) => format!("not entered in CapCut's project list: {e}"),
}
};
let count = |k: Kind, n: &str| tl.tracks.iter().filter(|t| t.kind == k && t.name.starts_with(n)).map(|t| t.clips.len()).sum::<usize>();
let mut said = format!(
"APPLIED CapCut draft \"{name}\" at {}: {} tracks, {}, {} ({}, {:.1} MB){}, {}; {:.2} s at {fps} fps, {w}x{h}; {listed}; markers from {}\n the reference render and the movies raea drew: {}",
written.dir.display(),
tl.tracks.len(),
many(count(Kind::Video, "") - count(Kind::Video, "raea "), "footage clip"),
many(count(Kind::Video, "raea overlay"), "overlay clip"),
codec.name(),
made.bytes as f64 / 1e6,
under.as_ref().map_or(String::new(), |(_, m)| format!(", {} under the footage ({:.1} MB)", many(count(Kind::Video, "raea under"), "clip"), m.bytes as f64 / 1e6)),
many(count(Kind::Audio, ""), "sound"),
written.duration_us as f64 / 1e6,
markers.from.as_deref().map_or("CapCut 8.5.0 (no draft CapCut made is in the store)".to_string(), |d| format!("the draft \"{d}\" CapCut made")),
work.display()
);
for n in notes {
said.push_str(&format!("\n note {n}"));
}
Ok(said)
}
/// "1 clip", "4 clips"
fn many(k: usize, what: &str) -> String {
if k == 1 { format!("1 {what}") } else { format!("{k} {what}s") }
}
/// Where CapCut's project list is copied before a draft is entered in it: the person's own folder, ~/.raea/capcut/backups
/// ($RAEA_CAPCUT_BACKUPS; %LOCALAPPDATA%\raea\capcut\backups on Windows, which sets no HOME). Never raea's home, which
/// is its install or, from a checkout, the source tree (11-11: a list's backup landed in the repository).
fn backups() -> PathBuf {
match std::env::var_os("LOCALAPPDATA").filter(|d| cfg!(windows) && !d.is_empty() && std::env::var_os("RAEA_CAPCUT_BACKUPS").is_none()) {
Some(d) => PathBuf::from(d).join("raea").join("capcut").join("backups"),
None => raea_io_home::env_path("RAEA_CAPCUT_BACKUPS", ".raea/capcut/backups"),
}
}
/// A movie raea drew, as clips of it wherever it draws, full frame on tracks named `name`; none when it draws nothing.
fn drawn(media: &mut Vec<Media>, path: &Path, m: &raea_io_alpha::Made, fps: f64, name: &str) -> Vec<Track> {
let spans = plan::spans(&m.drawn);
if spans.is_empty() {
return Vec::new();
}
let k = media.len();
media.push(Media { path: path.to_path_buf(), kind: MediaKind::Video, seconds: m.frames as f64 / fps, width: m.width, height: m.height, has_audio: false });
let clips = spans.iter().map(|&(a, b)| Clip { media: k, start: a, frames: b - a, source_in: a as f64 / fps, volume: 0.0, place: Place::centred(m.width, m.height), ..Clip::default() }).collect();
plan::lay(Kind::Video, name, clips)
}
/// A file's place in the media list, probed the first time it's named.
fn add(media: &mut Vec<Media>, index: &mut std::collections::HashMap<PathBuf, usize>, p: PathBuf, probe: fn(&Path) -> R<Media>) -> R<usize> {
if let Some(i) = index.get(&p) {
return Ok(*i);
}
media.push(probe(&p)?);
index.insert(p, media.len() - 1);
Ok(media.len() - 1)
}
fn ext_of(c: raea_io_alpha::Codec) -> &'static str {
match c {
raea_io_alpha::Codec::ProRes => "prores",
raea_io_alpha::Codec::Hevc => "hevc",
raea_io_alpha::Codec::Rle => "rle",
raea_io_alpha::Codec::Png => "png",
}
}
/// Whether the overlay is opaque over 90% of a run's box at its middle frame (a grid of points inside it).
fn opaque_under(frames: &Path, r: &plan::Run) -> bool {
let mid = (r.start + r.end - 1) / 2;
let Ok((px, w, h)) = raea_io_alpha::read_png(&frames.join(format!("frame-{mid:05}.png"))) else { return false };
let (mut n, mut opaque) = (0, 0);
for j in 0..16 {
for i in 0..16 {
let x = (r.bx[0] + r.bx[2] * (i as f64 + 0.5) / 16.0) as i64;
let y = (r.bx[1] + r.bx[3] * (j as f64 + 0.5) / 16.0) as i64;
if x < 0 || y < 0 || x >= w as i64 || y >= h as i64 {
continue;
}
n += 1;
opaque += usize::from(px[((y as usize) * w as usize + x as usize) * 4 + 3] >= 250);
}
}
n > 0 && opaque * 10 >= n * 9
}
/// Whether any frame in `frames` draws anything but black, at any alpha (a grid of points on each).
fn lit(frames: &Path) -> bool {
raea_io_alpha::frames_in(frames).iter().any(|p| {
let Ok((px, w, h)) = raea_io_alpha::read_png(p) else { return true };
(0..32).any(|j| {
(0..32).any(|i| {
let (x, y) = ((w as usize * (2 * i + 1)) / 64, (h as usize * (2 * j + 1)) / 64);
let k = (y * w as usize + x) * 4;
px[k + 3] >= 8 && px[k..k + 3].iter().any(|&c| c >= 8)
})
})
})
}
+50
View File
@@ -0,0 +1,50 @@
//! The files a draft uses, probed through raea's media backends (a picture's upright size and length, whether it has
//! sound; a sound's length), and the draft's cover: the reference render's first frame as a small JPEG.
use std::path::Path;
use raea_io_capcut::{Media, MediaKind};
use crate::R;
/// A video file: its display size (rotation applied) and length from the first backend that opens it, and whether a
/// short window of its sound decodes to samples.
pub fn video(path: &Path) -> R<Media> {
let mut why = Vec::new();
for b in raea_io_media::preferred() {
match b.open_video(path) {
Ok(d) => {
let i = d.info();
let has_audio = raea_io_media::decode_audio_window(path, 0.0, 0.05).is_ok_and(|a| a.len() > 0);
return Ok(Media { path: path.to_path_buf(), kind: MediaKind::Video, seconds: i.duration, width: i.width, height: i.height, has_audio });
}
Err(e) => why.push(format!("{}: {e}", b.name())),
}
}
Err(format!("{} didn't open as video ({})", path.display(), why.join("; ")))
}
/// A sound file: its length from its container.
pub fn sound(path: &Path) -> R<Media> {
let seconds = raea_io_media::probe_seconds(path).ok_or_else(|| format!("{}: no sound length", path.display()))?;
Ok(Media { path: path.to_path_buf(), kind: MediaKind::Audio, seconds, width: 0, height: 0, has_audio: true })
}
/// The first frame of `video`, at most 540 pixels on its long side, as a JPEG.
pub fn cover(video: &Path) -> Option<Vec<u8>> {
let mut d = raea_io_media::preferred().into_iter().find_map(|b| b.open_video(video).ok())?;
let f = d.frame_at(0.0).ok()?;
let (w, h) = (f.width as usize, f.height as usize);
let step = (w.max(h)).div_ceil(540).max(1);
let (tw, th) = (w / step, h / step);
let mut rgb = Vec::with_capacity(tw * th * 3);
for y in 0..th {
for x in 0..tw {
let k = ((y * step) * w + x * step) * 4;
rgb.extend_from_slice(&f.rgba[k..k + 3]);
}
}
let mut out = Vec::new();
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 82).encode(&rgb, tw as u32, th as u32, image::ExtendedColorType::Rgb8).ok()?;
Some(out)
}
+182
View File
@@ -0,0 +1,182 @@
//! The render's manifest as a CapCut timeline (docs/capcut.feature CC2): each run of frames showing one file as a
//! clip of it, each sound clip as an audio clip (or as its footage's own sound), each run of frames the overlay draws
//! as a clip of the overlay movie, and the tracks they go on. Pure: the export (lib.rs) renders and probes around it.
use std::path::{Path, PathBuf};
use raea_io_capcut::{Clip, Kind, Place, Track};
use serde_json::Value;
/// One file shown over a run of frames, as the manifest's frames say: its first source time and rate, its box and
/// fit at its first frame, its place in the page's order (lower draws first), and whether it moved or faded.
#[derive(Clone, Debug, PartialEq)]
pub struct Run {
pub src: String,
pub key: String,
pub start: i64,
pub end: i64,
pub at: f64,
pub last_at: f64,
pub rate: Option<f64>,
pub bx: [f64; 4],
pub fit: String,
pub opacity: f64,
pub z: usize,
pub moved: bool,
pub faded: bool,
}
/// One sound clip of the manifest: its file, frames, source time, gain, rate and fades.
#[derive(Clone, Debug, PartialEq)]
pub struct Sound {
pub src: String,
pub from: i64,
pub to: i64,
pub at: f64,
pub gain_db: f64,
pub rate: f64,
pub fade_in: f64,
pub fade_out: f64,
}
/// The footage's runs, frame by frame: a run goes on while the same element shows the same file with its source time
/// advancing at one rate; a jump in source time (a cut within one take) starts another.
pub fn runs(manifest: &Value, fps: f64) -> Vec<Run> {
let mut done: Vec<Run> = Vec::new();
let mut open: Vec<Run> = Vec::new();
let frames = manifest["frames"].as_array().cloned().unwrap_or_default();
for (i, fr) in frames.iter().enumerate() {
let f = fr["frame"].as_i64().unwrap_or(i as i64);
let mut next = Vec::new();
for (z, v) in fr["videos"].as_array().into_iter().flatten().enumerate() {
let src = v["src"].as_str().unwrap_or_default().to_string();
let key = format!("{src}|{}|{}|{}", v["loc"], v["use"], v["index"]);
let at = v["at"].as_f64().unwrap_or(0.0);
let bx: [f64; 4] = std::array::from_fn(|k| v["box"][k].as_f64().unwrap_or(0.0));
let opacity = v["opacity"].as_f64().unwrap_or(1.0);
let continues = |r: &Run| {
let step = at - r.last_at;
r.key == key && r.end == f && step > 0.0 && match r.rate {
Some(rate) => (step - rate / fps).abs() <= 0.6 / fps,
None => step * fps <= 8.0,
}
};
if let Some(k) = open.iter().position(continues) {
let mut r = open.remove(k);
r.rate.get_or_insert((at - r.last_at) * fps);
r.moved |= r.bx.iter().zip(&bx).any(|(a, b)| (a - b).abs() > 1.0);
r.faded |= (r.opacity - opacity).abs() > 0.02;
(r.end, r.last_at) = (f + 1, at);
next.push(r);
} else {
next.push(Run { src, key, start: f, end: f + 1, at, last_at: at, rate: None, bx, fit: v["fit"].as_str().unwrap_or("fill").to_string(), opacity, z, moved: false, faded: false });
}
}
done.append(&mut open);
open = next;
}
done.append(&mut open);
// the rate over the whole run (source times are whole milliseconds, so one step's can be 1% off), to hundredths
for r in &mut done {
if r.end - r.start > 1 {
r.rate = Some(((r.last_at - r.at) * fps / (r.end - r.start - 1) as f64 * 100.0).round() / 100.0);
}
}
done.sort_by_key(|r| (r.start, r.z));
done
}
/// The manifest's sound clips.
pub fn sounds(manifest: &Value) -> Vec<Sound> {
let s = &manifest["sounds"]["clips"];
s.as_array()
.into_iter()
.flatten()
.map(|c| Sound {
src: c["src"].as_str().unwrap_or_default().to_string(),
from: c["from"].as_i64().unwrap_or(0),
to: c["to"].as_i64().unwrap_or(0),
at: c["at"].as_f64().unwrap_or(0.0),
gain_db: c["gainDb"].as_f64().unwrap_or(0.0),
rate: c["rate"].as_f64().unwrap_or(1.0),
fade_in: c["fadeIn"].as_f64().unwrap_or(0.0),
fade_out: c["fadeOut"].as_f64().unwrap_or(0.0),
})
.filter(|c| c.to > c.from)
.collect()
}
/// Runs of frames that draw something.
pub fn spans(drawn: &[bool]) -> Vec<(i64, i64)> {
let mut out = Vec::new();
let mut f = 0;
while f < drawn.len() {
if !drawn[f] {
f += 1;
continue;
}
let a = f;
while f < drawn.len() && drawn[f] {
f += 1;
}
out.push((a as i64, f as i64));
}
out
}
/// Whether a box covers the whole canvas.
pub fn full(bx: &[f64; 4], w: f64, h: f64) -> bool {
bx[0] <= 1.0 && bx[1] <= 1.0 && bx[0] + bx[2] >= w - 1.0 && bx[1] + bx[3] >= h - 1.0
}
/// Where a picture of `mw` x `mh` sits to show as it does in its box with its object-fit, in CapCut's terms (scale 1:
/// fitted inside the canvas; a crop is fitted as the part it keeps). A warning when CapCut can't show it so.
pub fn place(bx: &[f64; 4], fit: &str, mw: f64, mh: f64, w: f64, h: f64, opacity: f64) -> (Place, Option<String>) {
let (bw, bh) = (bx[2].max(1.0), bx[3].max(1.0));
let (x, y) = (bx[0] + bw / 2.0, bx[1] + bh / 2.0);
let fit0 = (w / mw).min(h / mh);
let mut warn = None;
let contain = (bw / mw).min(bh / mh);
let (scale, crop) = match fit {
"cover" if full(bx, w, h) => ((bw / mw).max(bh / mh) / fit0, [0.0, 0.0, 1.0, 1.0]),
"cover" => {
let s = (bw / mw).max(bh / mh);
let (cw, ch) = (bw / (mw * s), bh / (mh * s));
let fitc = (w / (mw * cw)).min(h / (mh * ch));
(bw / (mw * cw * fitc), [(1.0 - cw) / 2.0, (1.0 - ch) / 2.0, (1.0 + cw) / 2.0, (1.0 + ch) / 2.0])
}
"none" => (1.0 / fit0, [0.0, 0.0, 1.0, 1.0]),
"scale-down" => (contain.min(1.0) / fit0, [0.0, 0.0, 1.0, 1.0]),
"contain" => (contain / fit0, [0.0, 0.0, 1.0, 1.0]),
_ => {
if ((bw / bh) - (mw / mh)).abs() > 0.01 * (mw / mh) {
warn = Some(format!("stretched to its {bw:.0}x{bh:.0} box in raea (object-fit: fill), fitted inside it in CapCut"));
}
(contain / fit0, [0.0, 0.0, 1.0, 1.0])
}
};
(Place { x, y, scale, opacity, crop }, warn)
}
/// Clips laid on as few tracks as hold them without overlap, first come first: `kind` tracks named `name`, `name 2`...
pub fn lay(kind: Kind, name: &str, clips: Vec<Clip>) -> Vec<Track> {
let mut tracks: Vec<Track> = Vec::new();
for c in clips {
let end = |t: &Track| t.clips.last().map_or(i64::MIN, |l| l.start + l.frames);
match tracks.iter_mut().find(|t| end(t) <= c.start) {
Some(t) => t.clips.push(c),
None => {
let n = tracks.len();
tracks.push(Track { kind, name: if n == 0 || name.is_empty() { name.to_string() } else { format!("{name} {}", n + 1) }, clips: vec![c] });
}
}
}
tracks
}
/// A file the manifest names, as a path, found as the renderer finds it: a staticFile path (/media/x) in the edit's
/// media/, then the project's media/ and assets/; else absolute; else relative to the composition's folder.
pub fn resolve(dir: &Path, src: &str) -> PathBuf {
let p = raea_core_scene::media_path(dir, src);
p.canonicalize().unwrap_or(p)
}
+85
View File
@@ -0,0 +1,85 @@
//! CC2a-c without a render: a manifest's frames as footage runs, its sound clips, the overlay's spans, where a picture
//! sits in CapCut's terms, and clips laid on tracks.
use serde_json::json;
use crate::plan::*;
use raea_io_capcut::{Clip, Kind};
/// 90 frames at 30 fps: one take cut into two pieces (a jump in its source time at frame 45), another file in a
/// corner from frame 60, moving one pixel at frame 70. Source times in whole milliseconds, as the manifest has them.
fn manifest() -> serde_json::Value {
let ms = |t: f64| (t * 1000.0).round() / 1000.0;
let frames: Vec<_> = (0..90)
.map(|f| {
let mut v = vec![json!({"src": "media/a.mp4", "at": ms(if f < 45 { 0.5 + f as f64 / 30.0 } else { 3.0 + (f - 45) as f64 / 30.0 }), "box": [0.0, 0.0, 1080.0, 1920.0], "fit": "cover", "opacity": 1.0})];
if f >= 60 {
v.push(json!({"src": "media/pip.mp4", "at": ms((f - 60) as f64 / 15.0), "box": [if f >= 70 { 662.0 } else { 660.0 }, 200.0, 360.0, 360.0], "opacity": 1.0}));
}
json!({"frame": f, "videos": v})
})
.collect();
json!({"width": 1080, "height": 1920, "fps": 30.0, "frames": frames, "sounds": {"clips": [{"src": "/m/music.wav", "from": 0, "to": 90, "at": 0.0, "gainDb": -6.0, "fadeOut": 0.5}]}})
}
#[test]
fn footage_runs_break_where_the_source_jumps() {
let r = runs(&manifest(), 30.0);
assert_eq!(r.iter().map(|r| (r.src.as_str(), r.start, r.end)).collect::<Vec<_>>(), [("media/a.mp4", 0, 45), ("media/a.mp4", 45, 90), ("media/pip.mp4", 60, 90)]);
assert!((r[1].at - 3.0).abs() < 1e-9);
assert_eq!((r[0].rate, r[1].rate), (Some(1.0), Some(1.0)), "a take at its own speed, though each step is 33 or 34 ms");
assert!((r[2].rate.unwrap() - 2.0).abs() < 1e-6, "the corner plays at twice its speed");
assert!(r[2].moved && !r[0].moved);
assert_eq!(r[2].fit, "fill");
}
#[test]
fn sounds_keep_gain_and_fades() {
let s = sounds(&manifest());
assert_eq!(s.len(), 1);
assert_eq!((s[0].from, s[0].to, s[0].gain_db, s[0].fade_out), (0, 90, -6.0, 0.5));
}
#[test]
fn overlay_spans_are_runs_of_drawn_frames() {
assert_eq!(spans(&[false, true, true, false, false, true]), [(1, 3), (5, 6)]);
assert!(spans(&[false; 4]).is_empty());
}
#[test]
fn pictures_sit_as_their_fit_shows_them() {
// a landscape take covering a portrait canvas: scaled past the fitted width until it fills the height
let (p, w) = place(&[0.0, 0.0, 1080.0, 1920.0], "cover", 1920.0, 1080.0, 1080.0, 1920.0, 1.0);
assert!(w.is_none() && (p.scale - (1920.0 / 1080.0) / 0.5625).abs() < 1e-9 && p.crop == [0.0, 0.0, 1.0, 1.0]);
assert_eq!((p.x, p.y), (540.0, 960.0));
// a square in a corner, contained: a third of the canvas's width
let (p, _) = place(&[660.0, 200.0, 360.0, 360.0], "contain", 640.0, 640.0, 1080.0, 1920.0, 1.0);
assert!((p.scale - 1.0 / 3.0).abs() < 1e-9 && (p.x, p.y) == (840.0, 380.0));
// a landscape take covering a square box: cropped to its middle square, which then fits as a square
let (p, _) = place(&[0.0, 0.0, 540.0, 540.0], "cover", 1920.0, 1080.0, 1080.0, 1920.0, 1.0);
assert!((p.crop[0] - 0.21875).abs() < 1e-9 && (p.crop[2] - 0.78125).abs() < 1e-9 && p.crop[1] == 0.0);
assert!((p.scale - 0.5).abs() < 1e-9);
// stretched in raea: said
assert!(place(&[0.0, 0.0, 500.0, 100.0], "fill", 640.0, 640.0, 1080.0, 1920.0, 1.0).1.is_some());
}
#[test]
fn clips_go_on_as_few_tracks_as_hold_them() {
let c = |start, frames| Clip { start, frames, ..Clip::default() };
let t = lay(Kind::Audio, "sound", vec![c(0, 90), c(10, 5), c(15, 10), c(90, 5)]);
assert_eq!(t.iter().map(|t| (t.name.as_str(), t.clips.len())).collect::<Vec<_>>(), [("sound", 2), ("sound 2", 2)]);
}
/// staticFile("x.mp4") is "/media/x.mp4" in the manifest: the export finds it where the render did, in media/ beside
/// the edit, as it finds a relative path; an absolute path stays as it is
#[test]
fn a_static_file_is_found_in_the_edits_media_folder() {
let dir = std::env::temp_dir().join(format!("raea-capcut-resolve-{}", std::process::id()));
std::fs::create_dir_all(dir.join("media")).unwrap();
std::fs::write(dir.join("media/a.mp4"), "").unwrap();
let want = dir.join("media/a.mp4").canonicalize().unwrap();
assert_eq!(resolve(&dir, "/media/a.mp4"), want);
assert_eq!(resolve(&dir, "media/a.mp4"), want);
assert_eq!(resolve(&dir, want.to_str().unwrap()), want);
std::fs::remove_dir_all(&dir).unwrap();
}
+10
View File
@@ -9,4 +9,14 @@ description = "`raea check`: the floor's measurable lines on an export, ranked P
[dependencies]
# taste.ts rules, as the raea CLI evaluates them (docs/projects.feature PJ0)
raea-core-brief = { path = "../../core/brief" }
# a transcript's words, read as `raea world` reads them (docs/direction.feature DR1)
raea-core-facts = { path = "../../core/facts" }
# a check's record named by when it was (UTC, DR3)
raea-io-trace = { path = "../../io/trace" }
# ffmpeg's flag for every decoded frame, by its version
raea-io-ffmpeg = { path = "../../io/ffmpeg" }
# caption contrast and loudness, measured as `raea world` measures a render (DR2)
raea-sys-measure = { path = "../../systems/measure" }
# the flashing screen (WCAG 2.3.1), split out to keep this crate small
raea-app-check-flash = { path = "flash" }
serde_json = "1"
+7
View File
@@ -0,0 +1,7 @@
[package]
name = "raea-app-check-flash"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "`raea check`'s flashing screen (WCAG 2.3.1): opposing swings in a frame's windows, from decoded RGB"
+232
View File
@@ -0,0 +1,232 @@
//! The flashing screen behind `raea check` (apps/check flash.rs feeds it the decoded frames): a pure measure of pixels,
//! in a crate of its own so the check stays small (tools/size.sh).
/// Flashing past WCAG 2.3.1: more than three flashes in any one second, over enough of the frame to matter. A flash is a
/// pair of opposing changes in the same pixels, so a shape sliding past isn't one. Each window, a third of the frame wide
/// and high, stands in for WCAG's quarter of a 10-degree field (the real area depends on the screen and how far away it
/// is, which a file doesn't say), and a quarter of its pixels must swing together: by 0.10 relative luminance with the
/// darker end under 0.80, or by 20 of saturated red ((R-G-B)*320, where R/(R+G+B) is at least 0.8). Every decoded frame
/// counts, on its own timestamp, and the picture is sampled twice, by area and by point, so fine patterns don't average
/// away. A screen for review, not a Harding or PEAT certification; an interlaced picture isn't split into its fields.
const FLASH_MOST: usize = 6;
const FLASH_PAIR_S: f64 = 1.0 + 1e-9;
/// A pixel in one measure: its value, and whether it can count. Red's value runs on through the saturation line, and a change
/// counts when either end of it is saturated; a one-level step across the line isn't a jump from zero.
#[derive(Clone, Copy)]
struct Px {
value: f32,
counts: bool,
}
struct Swing {
at: f64,
direction: f32,
moved: Vec<bool>,
plain: bool,
kept: bool,
}
/// One window's swings in one measure: the ones an opposite swing within a second moves back in the same pixels. The
/// general measure leaves out swings where another quarter of the window moved the other way at once (a moving pattern).
struct Swings {
by: f32,
under: f32,
mixed_counts: bool,
pivot: Vec<Px>,
extreme: Vec<Px>,
at: f64,
direction: f32,
recent: std::collections::VecDeque<Swing>,
ends: Vec<f64>,
}
impl Swings {
fn new(by: f32, under: f32, mixed_counts: bool) -> Swings {
Swings { by, under, mixed_counts, pivot: Vec::new(), extreme: Vec::new(), at: 0.0, direction: 0.0, recent: Default::default(), ends: Vec::new() }
}
fn moves(&self, a: Px, b: Px, direction: f32) -> bool {
(b.value - a.value) * direction >= self.by && a.value.min(b.value) < self.under && (a.counts || b.counts)
}
fn changed(&self, earlier: &[Px], later: &[Px], direction: f32) -> bool {
earlier.iter().zip(later).filter(|(a, b)| self.moves(**a, **b, direction)).count() * 4 >= earlier.len()
}
fn push(&mut self, t: f64, px: &[Px]) {
if self.pivot.is_empty() {
self.pivot = px.to_vec();
self.extreme = px.to_vec();
self.at = t;
return;
}
if self.direction == 0.0 {
for direction in [1.0, -1.0] {
if self.changed(&self.pivot, px, direction) {
self.direction = direction;
self.extreme = px.to_vec();
self.at = t;
break;
}
}
return;
}
if self.changed(&self.extreme, px, -self.direction) {
self.record();
self.pivot = std::mem::replace(&mut self.extreme, px.to_vec());
self.at = t;
self.direction = -self.direction;
} else if self.changed(&self.pivot, px, self.direction) && self.went_further(px) {
self.extreme = px.to_vec();
}
}
/// Whether the pixels swinging from the pivot went further than the saved extreme, judged on those pixels alone: the
/// rest of the window can dim by less than counts and still outweigh a patch that's flashing.
fn went_further(&self, px: &[Px]) -> bool {
let further: f32 = self.pivot.iter().zip(px).zip(&self.extreme).filter(|((p, n), _)| self.moves(**p, **n, self.direction)).map(|((_, n), e)| (n.value - e.value) * self.direction).sum();
further > 0.0
}
fn record(&mut self) {
if !self.changed(&self.pivot, &self.extreme, self.direction) {
return;
}
let moved: Vec<bool> = self.pivot.iter().zip(&self.extreme).map(|(a, b)| self.moves(*a, *b, self.direction)).collect();
let plain = self.mixed_counts || !self.changed(&self.pivot, &self.extreme, -self.direction);
let (at, direction) = (self.at, self.direction);
let mut kept = false;
for other in self.recent.iter_mut().rev() {
if at - other.at > FLASH_PAIR_S {
break;
}
let same = moved.iter().zip(&other.moved).filter(|(x, y)| **x && **y).count();
if other.direction == -direction && same * 4 >= moved.len() {
other.kept = true;
kept = true;
}
}
self.recent.push_back(Swing { at, direction, moved, plain, kept });
while self.recent.front().is_some_and(|s| at - s.at > FLASH_PAIR_S) {
self.retire();
}
}
/// The oldest swing leaves the second it could still pair within; only the seconds' ends are kept for good.
fn retire(&mut self) {
if let Some(s) = self.recent.pop_front()
&& s.plain
&& s.kept
{
self.ends.push(s.at);
}
}
/// The most swings in any one second, and when that second starts.
fn busiest(&mut self) -> (usize, f64) {
if self.direction != 0.0 {
self.record();
self.direction = 0.0;
}
while !self.recent.is_empty() {
self.retire();
}
self.ends.sort_by(f64::total_cmp);
let (mut best, mut from, mut j) = (0, 0.0, 0);
for i in 0..self.ends.len() {
while self.ends[i] - self.ends[j] >= 1.0 - 1e-9 {
j += 1;
}
if i - j + 1 > best {
(best, from) = (i - j + 1, self.ends[j]);
}
}
(best, from)
}
}
/// Frames of two pictures side by side, each `w` by `h` RGB: the area sample and the point sample of one frame.
pub struct FlashScreen {
w: usize,
h: usize,
last: Vec<u8>,
linear: Vec<f32>,
luma: Vec<Px>,
red: Vec<Px>,
cut: Vec<Px>,
windows: Vec<(usize, usize, Swings, Swings)>,
}
impl FlashScreen {
pub fn new(w: usize, h: usize) -> FlashScreen {
let (ww, wh) = (w / 3, h / 3);
let places = |size: usize, window: usize| {
let mut at: Vec<usize> = (0..=size - window).step_by((size / 6).max(1)).collect();
at.push(size - window);
at.dedup();
at
};
let mut windows = Vec::new();
for sample in 0..2 {
for &y in &places(h, wh) {
for &x in &places(w, ww) {
windows.push((x + sample * w, y, Swings::new(0.10, 0.80, false), Swings::new(20.0, f32::INFINITY, true)));
}
}
}
let linear = (0..=255u32)
.map(|c| {
let c = c as f32 / 255.0;
if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
})
.collect();
FlashScreen { w, h, last: Vec::new(), linear, luma: Vec::new(), red: Vec::new(), cut: Vec::new(), windows }
}
pub fn push(&mut self, rgb: &[u8], t: f64) {
if rgb == self.last {
return;
}
self.luma.clear();
self.red.clear();
for px in rgb.chunks_exact(3) {
let (r, g, b) = (self.linear[px[0] as usize], self.linear[px[1] as usize], self.linear[px[2] as usize]);
self.luma.push(Px { value: 0.2126 * r + 0.7152 * g + 0.0722 * b, counts: true });
let sum = r + g + b + 1e-9;
self.red.push(Px { value: ((r - g - b) * 320.0).max(0.0), counts: r / sum >= 0.8 });
}
let (stride, ww, wh) = (self.w * 2, self.w / 3, self.h / 3);
for (x, y, general, saturated) in &mut self.windows {
self.cut.clear();
for r in 0..wh {
self.cut.extend_from_slice(&self.luma[(*y + r) * stride + *x..][..ww]);
}
general.push(t, &self.cut);
self.cut.clear();
for r in 0..wh {
self.cut.extend_from_slice(&self.red[(*y + r) * stride + *x..][..ww]);
}
saturated.push(t, &self.cut);
}
self.last.clear();
self.last.extend_from_slice(rgb);
}
/// (swings in the worst second, when it starts, which measure) when past the limit
pub fn finish(mut self) -> Option<(usize, f64, &'static str)> {
let mut worst: Option<(usize, f64, &'static str)> = None;
for (_, _, general, saturated) in &mut self.windows {
for (swings, kind) in [(general, "general"), (saturated, "red")] {
let (n, from) = swings.busiest();
if n > FLASH_MOST && worst.is_none_or(|w| n > w.0) {
worst = Some((n, from, kind));
}
}
}
worst
}
}
#[cfg(test)]
mod tests;
+100
View File
@@ -0,0 +1,100 @@
use super::*;
/// a 96x54 picture drawn by `paint(frame index, sample, x, y)`, sample 0 the area sample and 1 the point sample, for
/// `frames` frames at `fps`
fn flash_samples(frames: usize, fps: f64, paint: impl Fn(usize, usize, usize, usize) -> [u8; 3]) -> Option<(usize, f64, &'static str)> {
let (w, h) = (96, 54);
let mut screen = FlashScreen::new(w, h);
for f in 0..frames {
let mut rgb = Vec::with_capacity(w * 2 * h * 3);
for y in 0..h {
for sample in 0..2 {
for x in 0..w {
rgb.extend_from_slice(&paint(f, sample, x, y));
}
}
}
screen.push(&rgb, f as f64 / fps);
}
screen.finish()
}
fn flash_of(seconds: usize, paint: impl Fn(usize, usize, usize) -> [u8; 3]) -> Option<(usize, f64, &'static str)> {
flash_samples(seconds * 60, 60.0, move |f, _, x, y| paint(f, x, y))
}
/// two colours taking turns `hz` times a second, over a box of the frame
fn turns(hz: usize, on: [u8; 3], off: [u8; 3], bx: (usize, usize, usize, usize)) -> Option<(usize, f64, &'static str)> {
flash_of(3, move |f, x, y| {
let inside = x >= bx.0 && x < bx.0 + bx.2 && y >= bx.1 && y < bx.1 + bx.3;
if inside && f * hz * 2 / 60 % 2 == 0 { on } else { off }
})
}
#[test]
fn flashing_is_found_past_three_a_second_and_not_at_it() {
let (white, black) = ([255, 255, 255], [0, 0, 0]);
let all = (0, 0, 96, 54);
assert_eq!(turns(3, white, black, all), None, "three a second is the limit, not past it");
let (swings, _, kind) = turns(4, white, black, all).expect("four a second");
assert_eq!((swings / 2, kind), (4, "general"));
// a small box: under a quarter of any window, and then over it
assert_eq!(turns(5, white, black, (40, 20, 10, 10)), None);
assert!(turns(5, white, black, (30, 18, 32, 18)).is_some());
// too small a change, and both ends too bright for WCAG to count it
assert_eq!(turns(5, [60, 60, 60], [30, 30, 30], all), None);
assert_eq!(turns(5, [255, 255, 255], [235, 235, 235], all), None);
// a dark saturated red: too dim to count as a general flash, past the limit as a red one
assert_eq!(turns(5, [150, 0, 0], black, all).map(|t| t.2), Some("red"));
}
#[test]
fn a_flash_of_single_frames_counts_at_any_frame_rate() {
// 120 fps with one white frame in every 30: four flashes a second, each gone within a sixtieth of a second
let found = flash_samples(360, 120.0, |f, _, _, _| if f % 30 == 1 { [255, 255, 255] } else { [0, 0, 0] });
assert_eq!(found.map(|(swings, _, kind)| (swings / 2, kind)), Some((4, "general")));
}
#[test]
fn a_flash_the_area_sample_averages_away_is_found_in_the_point_sample() {
let found = flash_samples(180, 60.0, |f, sample, _, _| {
if sample == 0 {
return [128, 128, 128];
}
if f * 5 * 2 / 60 % 2 == 0 { [255, 255, 255] } else { [0, 0, 0] }
});
assert!(found.is_some(), "the same flash in the point sample alone");
}
#[test]
fn a_shape_sliding_past_and_ordinary_cuts_are_not_flashing() {
let (white, black) = ([255, 255, 255], [0, 0, 0]);
assert_eq!(flash_of(3, move |f, x, _| if x < f { white } else { black }), None, "one wipe across the frame");
assert_eq!(flash_of(4, move |f, _, _| if (f / 30) % 2 == 0 { white } else { black }), None, "a cut every half second");
}
#[test]
fn a_patch_strobing_while_its_background_dims_is_still_found() {
// a third of a window: 0 then 124 on a 148 background, then the background settles at 124 and the patch cycles 124 and 160.
// The background's drop is under the 0.10 that counts, but it outweighs the patch in the window's mean.
let found = flash_samples(180, 60.0, |f, _, x, y| {
let patch = x < 16 && y < 12;
let level = match (patch, f) {
(true, 0) => 0,
(true, 1) => 124,
(true, _) => if (f - 2) * 5 * 2 / 60 % 2 == 0 { 160 } else { 124 },
(false, 0 | 1) => 148,
(false, _) => 124,
};
[level, level, level]
});
assert!(found.is_some(), "the patch flashes five times a second");
}
#[test]
fn a_colour_crossing_the_saturation_line_is_not_a_red_flash() {
// one level of green moves the pixel across R/(R+G+B) = 0.8 and hardly changes its red at all
let found = flash_samples(180, 60.0, |f, _, _, _| if f * 5 * 2 / 60 % 2 == 0 { [100, 49, 0] } else { [100, 50, 0] });
assert_eq!(found, None);
}
+152
View File
@@ -0,0 +1,152 @@
use super::*;
/// The defects Fingerprint's axes map to that a measure finds exactly (docs/fingerprint.feature FP4c), so the check
/// wins over a head: clipping, a dropout, and a flash frame. Each on the same decoded sound or a small grey picture;
/// each with red-team cases in tests.rs (a loud clean tone, a faded pause, a cut).
///
/// Clipping: a run of 3 samples or more at full scale (|x| 0.999 or more), or a flat top: 4 or more samples the same
/// to the bit at a level a sound rarely holds still at (0.05 or more), as a hard limiter or a clamp leaves them.
/// Counted per second; a second with CLIP_RUNS runs or more is a finding.
pub(crate) const FULL: f32 = 0.999;
pub(crate) const FLAT_LEVEL: f32 = 0.05;
pub(crate) const CLIP_RUNS: usize = 3;
pub(crate) fn clipped(x: &[f32]) -> Vec<(f64, String)> {
let mut per: Vec<usize> = vec![0; x.len() / SR + 1];
let mut i = 0;
while i < x.len() {
let v = x[i];
let mut j = i + 1;
if v.abs() >= FULL {
while j < x.len() && x[j].abs() >= FULL && x[j].signum() == v.signum() {
j += 1;
}
if j - i >= 3 {
per[i / SR] += 1;
}
} else if v.abs() >= FLAT_LEVEL {
while j < x.len() && x[j].to_bits() == v.to_bits() {
j += 1;
}
if j - i >= 4 {
per[i / SR] += 1;
}
}
i = j;
}
let mut out = Vec::new();
let mut s = 0;
while s < per.len() {
if per[s] < CLIP_RUNS {
s += 1;
continue;
}
let mut e = s;
while e + 1 < per.len() && per[e + 1] >= CLIP_RUNS {
e += 1;
}
let runs: usize = per[s..=e].iter().sum();
out.push((s as f64, format!("the sound clips: {runs} flat-topped runs over {} s; bring the level down before it hits the ceiling", e - s + 1)));
s = e + 1;
}
out
}
/// A dropout: the sound falls from level (-45 dBFS or more) to digital silence (under -80 dBFS) in one 10 ms step and
/// comes back within two, to within 10 dB of where it was, 50 ms to 3 s later. A pause that fades out or in isn't one.
pub(crate) const SILENT: f64 = -80.0;
pub(crate) const HAD_LEVEL: f64 = -45.0;
pub(crate) fn dropouts(x: &[f32]) -> Vec<(f64, String)> {
let rms: Vec<f64> = x.as_chunks::<HOP>().0.iter().map(|f| crate::sound::db(f)).collect();
let step = HOP as f64 / SR as f64;
let mut out = Vec::new();
let mut i = 1;
while i < rms.len() {
// a step that is silent, or nearly (the source cut partway through it), after one with level
if !(rms[i] < HAD_LEVEL - 20.0 && rms[i - 1] >= HAD_LEVEL) {
i += 1;
continue;
}
let mut j = i + 1;
while j < rms.len() && rms[j] < SILENT {
j += 1;
}
let gap = (j - i) as f64 * step;
let silent_inside = j > i + 1;
// back at once: within two steps, to within 10 dB of the level before the gap (a fade in takes longer)
let before = rms[i - 1];
let back = rms[j.min(rms.len())..(j + 2).min(rms.len())].iter().any(|l| *l >= HAD_LEVEL.max(before - 10.0));
if silent_inside && back && (0.05..=3.0).contains(&gap) {
out.push((i as f64 * step, format!("the sound drops out for {:.2} s and comes back; a dropout, not a pause (no fade either side)", gap)));
}
i = j.max(i + 1);
}
out
}
/// A flash frame: one or two frames whose mean brightness differs from the frames either side by FLASH_STEP or more
/// (0-1), while those two agree within FLASH_SAME: a black or white frame dropped into a shot. A cut (the brightness
/// moves and stays) and a fade aren't flash frames.
pub(crate) const FLASH_STEP: f32 = 0.25;
pub(crate) const FLASH_SAME: f32 = 0.08;
pub(crate) fn flash_frames(luma: &[f32], fps: f64) -> Vec<(f64, String)> {
let mut out = Vec::new();
let mut i = 1;
while i + 1 < luma.len() {
let found = (1..=2).find(|&k| {
let (before, after) = (luma[i - 1], luma.get(i + k - 1 + 1).copied());
let Some(after) = after else { return false };
(before - after).abs() <= FLASH_SAME && luma[i..i + k].iter().all(|&l| (l - before).abs() >= FLASH_STEP && (l - after).abs() >= FLASH_STEP)
});
match found {
Some(k) => {
out.push((i as f64 / fps, format!("{k} frame{} flash{} {} in the middle of a shot; a dropped or stray frame", if k == 1 { "" } else { "s" }, if k == 1 { "es" } else { "" }, if luma[i] < luma[i - 1] { "dark" } else { "bright" })));
i += k + 1;
}
None => i += 1,
}
}
out
}
/// Each frame's mean brightness (0-1), decoded small and grey
fn lumas(video: &str) -> R<(Vec<f32>, f64)> {
let out = Command::new("ffmpeg")
.args(["-v", "error", "-nostdin", "-i", video, "-map", "0:v:0", "-vf", "scale=32:18:flags=area,format=gray", "-f", "rawvideo", "-"])
.output()
.map_err(|e| format!("ffmpeg: {e}"))?;
if !out.status.success() {
return Err(format!("ffmpeg couldn't read the picture of {video}: {}", String::from_utf8_lossy(&out.stderr).trim()));
}
let l = out.stdout.as_chunks::<{ 32 * 18 }>().0.iter().map(|f| f.iter().map(|&p| p as f32).sum::<f32>() / (32.0 * 18.0 * 255.0)).collect();
let rate = ffmpeg_stderr(&["-hide_banner", "-i", video])?;
let fps = rate.split(" fps").next().and_then(|s| s.rsplit(", ").next()).and_then(|s| s.trim().parse().ok()).unwrap_or(30.0);
Ok((l, fps))
}
pub(crate) fn flash_frame_rule(video: &str, issues: &mut Vec<Issue>, passed: &mut Vec<String>) -> R<()> {
let (l, fps) = lumas(video)?;
let found = flash_frames(&l, fps);
if found.is_empty() {
passed.push("flash-frame: no stray black or white frame".into());
}
issues.extend(moments("flash-frame", 1, found));
Ok(())
}
/// Each moment a rule found, as an issue of that priority
pub(crate) fn moments(rule: &'static str, p: u8, found: Vec<(f64, String)>) -> impl Iterator<Item = Issue> {
found.into_iter().map(move |(at, says)| Issue { rule, p, at: Some(at), says })
}
/// The sound's defects on the decoded mix (sound.rs decodes it once)
pub(crate) fn sound_defects(x: &[f32], issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
for (rule, found, ok) in [("clipping", clipped(x), "clipping: no flat-topped runs"), ("dropout", dropouts(x), "dropout: the sound never drops to silence and back")] {
if found.is_empty() {
passed.push(ok.into());
}
issues.extend(moments(rule, 1, found));
}
}
+4 -238
View File
@@ -1,243 +1,9 @@
use super::*;
use raea_app_check_flash::FlashScreen;
/// Flashing past WCAG 2.3.1: more than three flashes in any one second, over enough of the frame to matter. A flash is a
/// pair of opposing changes in the same pixels, so a shape sliding past isn't one. Each window, a third of the frame wide
/// and high, stands in for WCAG's quarter of a 10-degree field (the real area depends on the screen and how far away it
/// is, which a file doesn't say), and a quarter of its pixels must swing together: by 0.10 relative luminance with the
/// darker end under 0.80, or by 20 of saturated red ((R-G-B)*320, where R/(R+G+B) is at least 0.8). Every decoded frame
/// counts, on its own timestamp, and the picture is sampled twice, by area and by point, so fine patterns don't average
/// away. A screen for review, not a Harding or PEAT certification; an interlaced picture isn't split into its fields.
/// The width each frame is decoded at for the flashing screen (raea-app-check-flash: its rule and its windows), twice over:
/// the area sample and the point sample side by side
const FLASH_W: usize = 192;
const FLASH_MOST: usize = 6;
const FLASH_PAIR_S: f64 = 1.0 + 1e-9;
/// A pixel in one measure: its value, and whether it can count. Red's value runs on through the saturation line, and a change
/// counts when either end of it is saturated; a one-level step across the line isn't a jump from zero.
#[derive(Clone, Copy)]
struct Px {
value: f32,
counts: bool,
}
struct Swing {
at: f64,
direction: f32,
moved: Vec<bool>,
plain: bool,
kept: bool,
}
/// One window's swings in one measure: the ones an opposite swing within a second moves back in the same pixels. The
/// general measure leaves out swings where another quarter of the window moved the other way at once (a moving pattern).
struct Swings {
by: f32,
under: f32,
mixed_counts: bool,
pivot: Vec<Px>,
extreme: Vec<Px>,
at: f64,
direction: f32,
recent: std::collections::VecDeque<Swing>,
ends: Vec<f64>,
}
impl Swings {
fn new(by: f32, under: f32, mixed_counts: bool) -> Swings {
Swings { by, under, mixed_counts, pivot: Vec::new(), extreme: Vec::new(), at: 0.0, direction: 0.0, recent: Default::default(), ends: Vec::new() }
}
fn moves(&self, a: Px, b: Px, direction: f32) -> bool {
(b.value - a.value) * direction >= self.by && a.value.min(b.value) < self.under && (a.counts || b.counts)
}
fn changed(&self, earlier: &[Px], later: &[Px], direction: f32) -> bool {
earlier.iter().zip(later).filter(|(a, b)| self.moves(**a, **b, direction)).count() * 4 >= earlier.len()
}
fn push(&mut self, t: f64, px: &[Px]) {
if self.pivot.is_empty() {
self.pivot = px.to_vec();
self.extreme = px.to_vec();
self.at = t;
return;
}
if self.direction == 0.0 {
for direction in [1.0, -1.0] {
if self.changed(&self.pivot, px, direction) {
self.direction = direction;
self.extreme = px.to_vec();
self.at = t;
break;
}
}
return;
}
if self.changed(&self.extreme, px, -self.direction) {
self.record();
self.pivot = std::mem::replace(&mut self.extreme, px.to_vec());
self.at = t;
self.direction = -self.direction;
} else if self.changed(&self.pivot, px, self.direction) && self.went_further(px) {
self.extreme = px.to_vec();
}
}
/// Whether the pixels swinging from the pivot went further than the saved extreme, judged on those pixels alone: the
/// rest of the window can dim by less than counts and still outweigh a patch that's flashing.
fn went_further(&self, px: &[Px]) -> bool {
let further: f32 = self.pivot.iter().zip(px).zip(&self.extreme).filter(|((p, n), _)| self.moves(**p, **n, self.direction)).map(|((_, n), e)| (n.value - e.value) * self.direction).sum();
further > 0.0
}
fn record(&mut self) {
if !self.changed(&self.pivot, &self.extreme, self.direction) {
return;
}
let moved: Vec<bool> = self.pivot.iter().zip(&self.extreme).map(|(a, b)| self.moves(*a, *b, self.direction)).collect();
let plain = self.mixed_counts || !self.changed(&self.pivot, &self.extreme, -self.direction);
let (at, direction) = (self.at, self.direction);
let mut kept = false;
for other in self.recent.iter_mut().rev() {
if at - other.at > FLASH_PAIR_S {
break;
}
let same = moved.iter().zip(&other.moved).filter(|(x, y)| **x && **y).count();
if other.direction == -direction && same * 4 >= moved.len() {
other.kept = true;
kept = true;
}
}
self.recent.push_back(Swing { at, direction, moved, plain, kept });
while self.recent.front().is_some_and(|s| at - s.at > FLASH_PAIR_S) {
self.retire();
}
}
/// The oldest swing leaves the second it could still pair within; only the seconds' ends are kept for good.
fn retire(&mut self) {
if let Some(s) = self.recent.pop_front()
&& s.plain
&& s.kept
{
self.ends.push(s.at);
}
}
/// The most swings in any one second, and when that second starts.
fn busiest(&mut self) -> (usize, f64) {
if self.direction != 0.0 {
self.record();
self.direction = 0.0;
}
while !self.recent.is_empty() {
self.retire();
}
self.ends.sort_by(f64::total_cmp);
let (mut best, mut from, mut j) = (0, 0.0, 0);
for i in 0..self.ends.len() {
while self.ends[i] - self.ends[j] >= 1.0 - 1e-9 {
j += 1;
}
if i - j + 1 > best {
(best, from) = (i - j + 1, self.ends[j]);
}
}
(best, from)
}
}
/// Frames of two pictures side by side, each `w` by `h` RGB: the area sample and the point sample of one frame.
pub(crate) struct FlashScreen {
w: usize,
h: usize,
last: Vec<u8>,
linear: Vec<f32>,
luma: Vec<Px>,
red: Vec<Px>,
cut: Vec<Px>,
windows: Vec<(usize, usize, Swings, Swings)>,
}
impl FlashScreen {
pub(crate) fn new(w: usize, h: usize) -> FlashScreen {
let (ww, wh) = (w / 3, h / 3);
let places = |size: usize, window: usize| {
let mut at: Vec<usize> = (0..=size - window).step_by((size / 6).max(1)).collect();
at.push(size - window);
at.dedup();
at
};
let mut windows = Vec::new();
for sample in 0..2 {
for &y in &places(h, wh) {
for &x in &places(w, ww) {
windows.push((x + sample * w, y, Swings::new(0.10, 0.80, false), Swings::new(20.0, f32::INFINITY, true)));
}
}
}
let linear = (0..=255u32)
.map(|c| {
let c = c as f32 / 255.0;
if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
})
.collect();
FlashScreen { w, h, last: Vec::new(), linear, luma: Vec::new(), red: Vec::new(), cut: Vec::new(), windows }
}
pub(crate) fn push(&mut self, rgb: &[u8], t: f64) {
if rgb == self.last {
return;
}
self.luma.clear();
self.red.clear();
for px in rgb.chunks_exact(3) {
let (r, g, b) = (self.linear[px[0] as usize], self.linear[px[1] as usize], self.linear[px[2] as usize]);
self.luma.push(Px { value: 0.2126 * r + 0.7152 * g + 0.0722 * b, counts: true });
let sum = r + g + b + 1e-9;
self.red.push(Px { value: ((r - g - b) * 320.0).max(0.0), counts: r / sum >= 0.8 });
}
let (stride, ww, wh) = (self.w * 2, self.w / 3, self.h / 3);
for (x, y, general, saturated) in &mut self.windows {
self.cut.clear();
for r in 0..wh {
self.cut.extend_from_slice(&self.luma[(*y + r) * stride + *x..][..ww]);
}
general.push(t, &self.cut);
self.cut.clear();
for r in 0..wh {
self.cut.extend_from_slice(&self.red[(*y + r) * stride + *x..][..ww]);
}
saturated.push(t, &self.cut);
}
self.last.clear();
self.last.extend_from_slice(rgb);
}
/// (swings in the worst second, when it starts, which measure) when past the limit
pub(crate) fn finish(mut self) -> Option<(usize, f64, &'static str)> {
let mut worst: Option<(usize, f64, &'static str)> = None;
for (_, _, general, saturated) in &mut self.windows {
for (swings, kind) in [(general, "general"), (saturated, "red")] {
let (n, from) = swings.busiest();
if n > FLASH_MOST && worst.is_none_or(|w| n > w.0) {
worst = Some((n, from, kind));
}
}
}
worst
}
}
/// Every decoded frame, once: -fps_mode from FFmpeg 5.1 on, -vsync before it.
fn passthrough() -> [&'static str; 2] {
let out = Command::new("ffmpeg").args(["-hide_banner", "-version"]).output().map(|o| o.stdout).unwrap_or_default();
let head = String::from_utf8_lossy(&out);
let version = head.split("version ").nth(1).and_then(|v| {
let mut parts = v.trim_start_matches('n').split(|c: char| !c.is_ascii_digit());
Some((parts.next()?.parse::<u32>().ok()?, parts.next()?.parse::<u32>().ok()?))
});
[if version.is_some_and(|v| v < (5, 1)) { "-vsync" } else { "-fps_mode" }, "passthrough"]
}
/// A frame's number and time from showinfo's log, exact: its `pts` in ticks of the time base. `pts_time` is rounded to six
/// significant digits, which is enough to push a legal third flash across the one-second line.
@@ -269,7 +35,7 @@ pub(crate) fn flashing(video: &str, probe: &Probe, issues: &mut Vec<Issue>, pass
let w = FLASH_W;
let h = (((w as f64 * probe.h / probe.w.max(1.0)) / 2.0).round() as usize * 2).max(6);
let graph = format!("showinfo,split=2[area][point];[area]scale={w}:{h}:flags=area[a];[point]scale={w}:{h}:flags=neighbor[b];[a][b]hstack=inputs=2,format=rgb24");
let sync = passthrough();
let sync = raea_io_ffmpeg::passthrough();
let mut child = Command::new("ffmpeg")
.args(["-hide_banner", "-nostats", "-nostdin", "-loglevel", "level+info", "-i", video, "-map", "0:v:0", "-vf", &graph, sync[0], sync[1], "-f", "rawvideo", "-"])
.stdin(std::process::Stdio::null())
+204
View File
@@ -0,0 +1,204 @@
//! `raea hook [AGENT]` (docs/agents.feature A5d, A5e; docs/skills.feature SK10): one runner for every agent harness's
//! tool hooks, whichever harness runs the agent (Claude Code, Codex, Gemini CLI, Kimi Code; `raea skills install
//! --agent A` adds them, and they hold inside the raea app too, which leaves each agent its own shell). Before a shell
//! command: media opened in the Mac's viewer or a browser is stopped once while the raea app is installed, the reason
//! naming `raea show`; the same command tried again goes through, so an agent that means it says so twice. After a
//! file is saved: the quick check on a composition. A stop is exit 2 with the reason on stderr, which every harness
//! hands its agent; the quick check's findings go back in the shape each one reads.
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
type R<T> = Result<T, String>;
/// What a still, a video or a sound ends with: what the raea app shows as an item.
const MEDIA: [&str; 25] = ["png", "jpg", "jpeg", "gif", "webp", "heic", "heif", "tif", "tiff", "bmp", "avif", "exr", "mp4", "mov", "m4v", "webm", "mkv", "avi", "wav", "mp3", "m4a", "aac", "flac", "aif", "aiff"];
/// A stopped command tried again within this many seconds goes through.
const AGAIN: u64 = 600;
/// The harness that sent this input, when the hook's command doesn't name it: Gemini CLI names its events BeforeTool and
/// AfterTool, Kimi Code says its client; Claude Code and Codex share one shape.
fn agent_of(v: &Value) -> &'static str {
match (v["hook_event_name"].as_str().unwrap_or(""), v["client_type"].as_str().unwrap_or("")) {
("BeforeTool" | "AfterTool", _) => "gemini",
(_, c) if c.contains("kimi") => "kimi",
_ => "claude",
}
}
/// The shell command a tool call runs, if it's a shell tool's (Bash, shell, shell_command, exec_command,
/// run_shell_command): Codex's apply_patch carries its patch in `command` too, and isn't one.
fn shell_command(v: &Value) -> Option<&str> {
let cmd = v["tool_input"]["command"].as_str()?;
(v["tool_name"].as_str() != Some("apply_patch") && !cmd.trim_start().starts_with("*** Begin Patch")).then_some(cmd)
}
/// A shell segment's words, quotes taken off (enough for `open "a b.png"`, not a shell).
fn words(seg: &str) -> Vec<String> {
let (mut out, mut cur, mut quote, mut any) = (Vec::new(), String::new(), None, false);
for c in seg.chars() {
match (quote, c) {
(Some(q), c) if c == q => quote = None,
(Some(_), c) => cur.push(c),
(None, '\'' | '"') => (quote, any) = (Some(c), true),
(None, c) if c.is_whitespace() => {
if any || !cur.is_empty() {
out.push(std::mem::take(&mut cur));
}
any = false;
}
(None, c) => cur.push(c),
}
}
if any || !cur.is_empty() {
out.push(cur);
}
out
}
/// The media files a command opens in the Mac's viewer or a browser (`open`, `open -a Preview`, `xdg-open`,
/// `qlmanage -p`); `open -a raea`, `open -R` (Finder), links and other files aren't.
pub fn opened_media(cmd: &str) -> Vec<String> {
let mut found = Vec::new();
for seg in cmd.split(['\n', ';', '|', '&']) {
let w = words(seg);
let mut it = w.iter().skip_while(|t| t.contains('=') && !t.starts_with('-') || ["command", "exec", "nohup", "env"].contains(&t.as_str()));
let Some(tool) = it.next() else { continue };
if !["open", "xdg-open", "qlmanage"].contains(&tool.rsplit_once('/').map_or(tool.as_str(), |(_, name)| name)) {
continue;
}
// the files it names, apart from the app an -a or -b names; one naming raea, or Finder's -R, opens nothing here
let (mut files, mut app, mut ours) = (Vec::new(), false, false);
for t in it {
if app {
ours |= t.to_lowercase().contains("raea");
app = false;
} else if t == "-a" || t == "-b" {
app = true;
} else if t == "-R" {
ours = true;
} else if !t.starts_with('-') && !t.contains("://") && t.rsplit_once('.').is_some_and(|(_, e)| MEDIA.contains(&e.to_lowercase().as_str())) {
files.push(t.clone());
}
}
if !ours {
found.extend(files);
}
}
found
}
/// The raea app on this Mac (RAEA_APP, /Applications or ~/Applications).
fn app_installed(home: &str) -> bool {
[std::env::var("RAEA_APP").unwrap_or_default(), "/Applications/raea.app".into(), format!("{home}/Applications/raea.app")].iter().any(|p| !p.is_empty() && std::path::Path::new(p).exists())
}
/// True when this command was stopped for this session within AGAIN seconds (the agent's second yes, which clears it);
/// else it's noted and false.
fn tried_before(dir: &Path, key: &str) -> bool {
let h = key.bytes().fold(0xcbf29ce484222325u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x100000001b3));
let at = dir.join(format!("{h:016x}"));
let fresh = std::fs::metadata(&at).and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|e| e.as_secs() < AGAIN);
if fresh {
let _ = std::fs::remove_file(&at);
return true;
}
let _ = std::fs::create_dir_all(dir).and_then(|_| std::fs::write(&at, key));
false
}
/// Why the command stops, for the agent: what to run instead, and that the same command again goes through.
pub fn steer(files: &[String]) -> String {
let list = files.iter().map(|f| if f.contains(' ') { format!("{f:?}") } else { f.clone() }).collect::<Vec<_>>().join(" ");
format!("raea: the raea app is installed here, so show this in it, not the Mac's viewer: `raea show {list}` (several stills make a storyboard; add --ask \"what you want from the person\"; inside the raea app, feed_post does the same). It brings the app's window up on it as an item the person can answer, and their answer comes to the inbox file it prints. If the Mac's viewer really is what's wanted (the person asked for it, or raea show can't), run the same command again and it goes through.")
}
/// The files a tool call saved: `file_path` or `path` (Claude Code, Kimi Code, Gemini CLI), or the files an apply_patch
/// adds or updates (Codex).
fn saved(v: &Value) -> Vec<String> {
let i = &v["tool_input"];
if let Some(p) = i["file_path"].as_str().or(i["path"].as_str()).or(i["absolute_path"].as_str()) {
return vec![p.to_string()];
}
let patch = i["command"].as_str().or(i["input"].as_str()).unwrap_or("");
patch.lines().filter_map(|l| ["*** Add File: ", "*** Update File: "].iter().find_map(|head| l.strip_prefix(head))).map(str::trim).map(String::from).collect()
}
/// Findings for the agent in the shape its harness reads after a tool: Gemini CLI's AfterTool context, Kimi Code's
/// plain stdout, Claude Code's and Codex's PostToolUse context.
fn after(agent: &str, text: &str) -> String {
match agent {
"kimi" => text.to_string(),
"gemini" => json!({"hookSpecificOutput": {"hookEventName": "AfterTool", "additionalContext": text}}).to_string(),
_ => json!({"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": text}}).to_string(),
}
}
/// `raea hook [claude|codex|gemini|kimi]`: the harness's hook input on stdin. Prints what goes back to the agent, or
/// stops the call (exit 2, the reason on stderr).
pub fn hook(args: &[String]) -> R<String> {
let named = args.first().map(String::as_str);
if named.is_some_and(|a| !["claude", "codex", "gemini", "kimi"].contains(&a)) {
return Err("usage: raea hook [claude|codex|gemini|kimi] (an agent's tool hooks; raea skills install --agent A adds them)".into());
}
let mut input = String::new();
std::io::Read::read_to_string(&mut std::io::stdin(), &mut input).map_err(|e| e.to_string())?;
let v: Value = serde_json::from_str(&input).unwrap_or_default();
let agent = named.unwrap_or_else(|| agent_of(&v));
if let Some(cmd) = shell_command(&v) {
let home = std::env::var("HOME").unwrap_or_default();
let files = opened_media(cmd);
let key = format!("{}\n{}\n{cmd}", v["session_id"].as_str().unwrap_or(""), v["cwd"].as_str().unwrap_or(""));
if !files.is_empty() && app_installed(&home) && !tried_before(&PathBuf::from(&home).join(".raea/hooks/again"), &key) {
eprintln!("{}", steer(&files));
std::process::exit(2);
}
return Ok(String::new());
}
let mut found = Vec::new();
for path in saved(&v).iter().filter(|p| p.ends_with(".tsx") && std::fs::read_to_string(p).is_ok_and(|t| t.contains("registerRoot"))) {
let (report, _) = crate::quick::quick(std::slice::from_ref(path), Vec::new())?;
found.extend(report.lines().skip(1).filter(|l| !l.starts_with("ok ")).map(String::from));
}
Ok(if found.is_empty() { String::new() } else { after(agent, &format!("raea check --quick after this save:\n{}", found.join("\n"))) })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn media_opened_in_a_viewer_is_found_and_the_rest_isnt() {
assert_eq!(opened_media("open out/a.png out/b.PNG"), ["out/a.png", "out/b.PNG"]);
assert_eq!(opened_media("cd /tmp && open -a Preview \"sheet 1.jpg\""), ["sheet 1.jpg"]);
assert_eq!(opened_media("FOO=1 /usr/bin/open cut.mp4; echo done"), ["cut.mp4"]);
assert_eq!(opened_media("qlmanage -p still.webp >/dev/null 2>&1"), ["still.webp"]);
assert_eq!(opened_media("xdg-open take.mov"), ["take.mov"]);
for none in ["open -a raea", "open -a raea out/a.png", "open -R out/a.png", "open https://x.io/a.png", "open notes.pdf", "open .", "cat a.png", "git open a.png", "echo open a.png > x"] {
assert!(opened_media(none).is_empty(), "{none}: {:?}", opened_media(none));
}
}
#[test]
fn each_harness_is_told_apart_and_answered_in_its_shape() {
assert_eq!(agent_of(&json!({"hook_event_name": "BeforeTool", "tool_name": "run_shell_command"})), "gemini");
assert_eq!(agent_of(&json!({"hook_event_name": "PreToolUse", "client_type": "kimi_code_cli"})), "kimi");
assert_eq!(agent_of(&json!({"hook_event_name": "PreToolUse", "tool_name": "Bash"})), "claude");
assert_eq!(shell_command(&json!({"tool_name": "shell_command", "tool_input": {"command": "open a.png"}})), Some("open a.png"));
assert_eq!(shell_command(&json!({"tool_name": "apply_patch", "tool_input": {"command": "*** Begin Patch\n"}})), None);
assert_eq!(saved(&json!({"tool_input": {"command": "*** Begin Patch\n*** Update File: a/E.tsx\n@@\n*** Add File: b.ts\n"}})), ["a/E.tsx", "b.ts"]);
assert_eq!(saved(&json!({"tool_input": {"path": "E.tsx"}})), ["E.tsx"]);
assert_eq!(after("kimi", "x"), "x");
assert!(after("gemini", "x").contains("AfterTool") && after("codex", "x").contains("PostToolUse"));
assert!(steer(&["a b.png".into()]).contains("`raea show \"a b.png\"`"));
}
#[test]
fn the_same_command_again_goes_through_once() {
let d = std::env::temp_dir().join(format!("raea-hook-again-{}", std::process::id()));
assert!(!tried_before(&d, "s\n/x\nopen a.png"));
assert!(tried_before(&d, "s\n/x\nopen a.png"));
assert!(!tried_before(&d, "s\n/x\nopen a.png"), "a third try is a new first");
assert!(!tried_before(&d, "other\n/x\nopen a.png"));
let _ = std::fs::remove_dir_all(&d);
}
}
+96 -48
View File
@@ -1,4 +1,4 @@
//! `raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 9:16]
//! `raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--things T.json] [--shape 9:16]
//! [--platform tiktok|reels|shorts] [-o check.json]`: the floor's measurable lines on an export (docs/craft-system.md, I; sdk/guides/craft/floor.md).
//! Each issue is ranked P0 (breaks the piece) to P3 (polish), with where it is and what to do. Rules on the file alone:
//! loudness and true peak, a steady sound that stops dead (a source run out, a cut with no fade), stretches where nothing
@@ -11,7 +11,7 @@
//! rules in their taste.ts files that carry a check (`{ text: "Captions sit clear of the bottom.", check: { form:
//! "text-above", value: 62 } }`), each a P1 when broken, since the person's rule beats the floor's default (docs/craft-system.md, J). Exits 1 when a P0 or P1 is found.
use serde_json::{Value, json};
use std::collections::BTreeMap;
use raea_core_facts::{Finding, Level, finding};
use std::process::Command;
mod sound;
@@ -20,9 +20,12 @@ mod picture;
use picture::*;
mod flash;
use flash::*;
mod defects;
use defects::*;
mod text;
use text::*;
pub mod quick;
pub mod hook;
#[cfg(test)]
mod tests;
@@ -39,35 +42,47 @@ struct Issue {
/// `raea check …` with the person's taste, none or more (taste.ts and the kinds beside it, which the raea CLI evaluates: it owns the engine):
/// its rules' checks hold the export to the person's own lines.
pub fn cli_with(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> i32 {
match run(args, tastes) {
said(run(args, tastes), "REFUSED ")
}
/// A check's report printed, and its exit code: 1 when it found an error, 2 when it couldn't check (said after
/// `refused`). `raea check EDIT.tsx` (apps/direction) ends the same way.
pub fn said(ran: R<(String, bool)>, refused: &str) -> i32 {
match ran {
Ok((report, bad)) => {
println!("{report}");
i32::from(bad)
}
Err(e) => {
eprintln!("REFUSED {e}");
eprintln!("{refused}{e}");
2
}
}
}
/// A command's words: its arguments that are neither flags nor a flag's value (`takes`: the flags that take one).
/// What `raea check` checks is its first; `raea workspace` and `raea project` read theirs the same way.
pub fn words<'a>(args: &'a [String], takes: &[&str]) -> Vec<&'a str> {
args.iter().enumerate().filter(|(i, a)| !a.starts_with('-') && !(*i > 0 && takes.contains(&args[i - 1].as_str()))).map(|(_, a)| a.as_str()).collect()
}
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)
}
pub const USAGE: &str = "raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit; P0-P3)";
pub const USAGE: &str = "raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--things T.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit, and with --things what `raea fingerprint things --json` found: a thing floating or passing through another, the camera lurching mid-move, an empty frame; its findings errors, warns and notes)";
/// A rule from the person's taste: a form raea can measure, its value, and the taste line it stands for.
#[derive(Clone, Debug, PartialEq)]
struct Taste {
form: String,
form: &'static str,
value: f64,
line: String,
}
/// The checks among a person's taste rules (taste.ts and its kinds), each with the line it stands for.
fn taste_rules(tastes: &[raea_core_brief::Taste]) -> Vec<Taste> {
tastes.iter().flat_map(|t| &t.sections).flat_map(|s| &s.rules).filter_map(|r| r.check.map(|c| Taste { form: c.form().to_string(), value: c.value(), line: r.text.clone() })).collect()
tastes.iter().flat_map(|t| &t.sections).flat_map(|s| &s.rules).filter_map(|r| r.check.map(|c| Taste { form: c.form(), value: c.value(), line: r.text.clone() })).collect()
}
fn taste_of<'a>(rules: &'a [Taste], form: &str) -> Option<&'a Taste> {
@@ -82,7 +97,7 @@ fn taste_text(rules: &[Taste], runs: &[Run], w: f64, h: f64, issues: &mut Vec<Is
for t in runs {
let [x, y, bw, bh] = t.box_;
let q = quote(&t.text);
let why = match r.form.as_str() {
let why = match r.form {
"text-hold" if t.to - t.from + 0.05 < r.value => Some(format!("{q} is on for {:.1} s, under your {:.1} s", t.to - t.from, r.value)),
"text-above" if y + bh > h * r.value / 100.0 + 1.0 => Some(format!("{q} reaches {:.0}% down the frame, below your {:.0}%", (y + bh) / h * 100.0, r.value)),
"text-below" if y < h * r.value / 100.0 - 1.0 => Some(format!("{q} starts {:.0}% down the frame, above your {:.0}%", y / h * 100.0, r.value)),
@@ -94,7 +109,7 @@ fn taste_text(rules: &[Taste], runs: &[Run], w: f64, h: f64, issues: &mut Vec<Is
};
if let Some(why) = why {
broke += 1;
issues.push(Issue { rule: "taste", p: 1, at: Some(t.from), says: format!("{why} (\"{}\")", r.line) });
issues.push(Issue { rule: r.form, p: 1, at: Some(t.from), says: format!("{why} (\"{}\")", r.line) });
}
}
if broke == 0 && r.form.starts_with("text-") {
@@ -104,17 +119,33 @@ fn taste_text(rules: &[Taste], runs: &[Run], w: f64, h: f64, issues: &mut Vec<Is
}
/// the flags `raea check` takes, each with a value
const TAKES: [&str; 7] = ["--manifest", "--words", "--perception", "--shape", "--platform", "--taste", "-o"];
const TAKES: [&str; 8] = ["--manifest", "--words", "--perception", "--things", "--shape", "--platform", "--taste", "-o"];
fn run(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {
let video = args.iter().enumerate().find(|(i, a)| !a.starts_with('-') && !(*i > 0 && TAKES.contains(&args[i - 1].as_str()))).map(|(_, a)| a.clone()).ok_or(USAGE)?;
let (video, issues, passed, fps) = measured(args, taste_rules(&tastes))?;
report(&video, issues, Vec::new(), passed, flag(args, "-o"), fps)
}
/// raea's floor on a video (`args` as raea check takes them) as Findings, printed and kept nowhere: `raea check
/// EDIT.tsx` runs it on the composition's newest render beside its other checks (apps/direction, DR4). `held`: the
/// rules of the named checks it measures on the video itself (loudness, still-max), each its form, value and line.
/// `without`: its own rules that a named check holds there instead (`reading`, which text-read holds against when
/// a text can be read, not when it's on: DR28).
pub fn floor(args: &[String], held: &[(&'static str, f64, String)], without: &[&str]) -> R<Vec<Finding>> {
let held = held.iter().map(|(form, value, line)| Taste { form: *form, value: *value, line: line.clone() }).collect();
let (_, mut issues, _, fps) = measured(args, held)?;
issues.retain(|i| without.iter().all(|w| *w != i.rule));
Ok(findings_of(issues, Vec::new(), fps))
}
/// The video's issues and what passed, measured, and its frame rate.
fn measured(args: &[String], taste: Vec<Taste>) -> R<(String, Vec<Issue>, Vec<String>, f64)> {
let video = words(args, &TAKES).first().map(|v| v.to_string()).ok_or(USAGE)?;
if !std::path::Path::new(&video).exists() {
return Err(format!("no file at {video}\n{USAGE}"));
}
let probe = Probe::of(&video)?;
let mut issues = Vec::new();
let mut passed = Vec::new();
let taste = taste_rules(&tastes);
let (mut issues, mut passed) = (Vec::new(), Vec::new());
let manifest: Option<Value> = match flag(args, "--manifest") {
Some(m) => Some(serde_json::from_str(&std::fs::read_to_string(m).map_err(|e| format!("{m}: {e}"))?).map_err(|e| format!("{m}: {e}"))?),
None => None,
@@ -127,8 +158,12 @@ fn run(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)
}
freezes(&video, &probe, taste_of(&taste, "still-max"), &mut issues, &mut passed)?;
flashing(&video, &probe, &mut issues, &mut passed)?;
flash_frame_rule(&video, &mut issues, &mut passed)?;
blotching(&video, &probe, &mut issues, &mut passed)?;
brand_kit(&[flag(args, "--manifest").unwrap_or(""), video.as_str()], &mut issues, &mut passed);
if let Some(p) = flag(args, "--things") {
things(p, &mut issues, &mut passed)?;
}
if let Some(manifest) = &manifest {
let runs = text_runs(manifest);
let (w, h) = (manifest["width"].as_f64().unwrap_or(probe.w), manifest["height"].as_f64().unwrap_or(probe.h));
@@ -143,36 +178,56 @@ fn run(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)
face_cover(&runs, &faces, &mut issues, &mut passed);
}
}
report(&video, issues, passed, flag(args, "-o"))
Ok((video, issues, passed, fps))
}
/// The issues ranked, written to -o as JSON when asked, and the report's text; true when a P0 or P1 is among them.
fn report(video: &str, mut issues: Vec<Issue>, passed: Vec<String>, out: Option<&str>) -> R<(String, bool)> {
/// What `raea fingerprint things FILE --json` found (docs/fingerprint.feature FP13c): a thing floating, two passing
/// through each other, the camera lurching mid-move, an empty frame; measured there, from depth, masks and the camera's
/// path, never by a head
fn things(p: &str, issues: &mut Vec<Issue>, passed: &mut Vec<String>) -> R<()> {
let v: Value = serde_json::from_str(&std::fs::read_to_string(p).map_err(|e| format!("{p}: {e}"))?).map_err(|e| format!("{p}: {e}"))?;
let before = issues.len();
for i in v["issues"].as_array().into_iter().flatten() {
let Some(rule) = ["floating", "passing-through", "camera-speed", "empty-frame"].into_iter().find(|r| i["rule"] == *r) else { continue };
issues.push(Issue { rule, p: i["p"].as_u64().unwrap_or(2).min(3) as u8, at: i["at"].as_f64(), says: i["says"].as_str().unwrap_or_default().into() });
}
if issues.len() == before {
passed.push("things: nothing floats, passes through, lurches or is empty".into());
}
Ok(())
}
/// The issues as Findings (docs/direction.feature DR3: P0 and P1 errors, P2 a warn, P3 a note; a time is its frame at
/// `fps`), with `more` (a render's own), worst first then by time.
fn findings_of(mut issues: Vec<Issue>, more: Vec<Finding>, fps: f64) -> Vec<Finding> {
issues.sort_by(|a, b| a.p.cmp(&b.p).then(a.at.unwrap_or(0.0).total_cmp(&b.at.unwrap_or(0.0))));
let bad = issues.iter().any(|i| i.p <= 1);
let mut found = Vec::new();
for i in &issues {
// an issue at a second is about the frame it falls on
let (f, fr) = (Finding::new(i.rule, Level::of_rank(i.p), &i.says, "raea check"), (i.at.unwrap_or(0.0) * fps).round() as i64);
found.push(if i.at.is_some() { f.frames(fr, fr + 1) } else { f });
}
finding::ranked(found.into_iter().chain(more).collect())
}
/// The findings (`findings_of`), written to -o as JSON when asked, and the report's text with the count last. True
/// when an error is among them.
fn report(video: &str, issues: Vec<Issue>, more: Vec<Finding>, passed: Vec<String>, out: Option<&str>, fps: f64) -> R<(String, bool)> {
let found = findings_of(issues, more, fps);
let bad = found.iter().any(|f| f.level == Level::Error);
if let Some(out) = out {
let j = json!({
"file": video,
"issues": issues.iter().map(|i| json!({"rule": i.rule, "p": format!("P{}", i.p), "at": i.at, "says": i.says})).collect::<Vec<_>>(),
"passed": passed,
});
let j = json!({"file": video, "fps": fps, "findings": found, "passed": passed});
std::fs::write(out, serde_json::to_string_pretty(&j).unwrap()).map_err(|e| format!("{out}: {e}"))?;
}
let mut by = BTreeMap::new();
for i in &issues {
*by.entry(i.p).or_insert(0) += 1;
let mut s = format!("raea check {video}\n");
// kept in its project's record beside its renders (DR3), what `raea findings` and `raea next` read
let kept = raea_core_facts::record::keep("raea check", std::path::Path::new(video), out.map(std::path::Path::new), &found, vec![], &raea_io_trace::utc(std::time::SystemTime::now()).1);
let kept = kept.map(|e| format!("raea check: kept in the project's record as {} (raea findings reads it)", e.id));
for line in found.iter().map(Finding::line).chain(passed.iter().map(|p| format!("ok {p}"))).chain(kept) {
s.push_str(&line);
s.push('\n');
}
let counts = by.iter().map(|(p, n)| format!("P{p} {n}")).collect::<Vec<_>>().join(", ");
let mut s = format!("raea check {}: {}\n", video, if issues.is_empty() { "nothing to fix".to_string() } else { format!("{} to fix ({counts})", issues.len()) });
for i in &issues {
let at = i.at.map(|t| format!("{t:6.2} s")).unwrap_or_else(|| " ".into());
s.push_str(&format!("P{} {:<9} {at} {}\n", i.p, i.rule, i.says));
}
for p in &passed {
s.push_str(&format!("ok {p}\n"));
}
Ok((s.trim_end().to_string(), bad))
Ok((s + &format!("raea check: {}", finding::count(&found)), bad))
}
struct Probe {
@@ -200,10 +255,8 @@ fn last_packet_end(video: &str) -> Option<f64> {
impl Probe {
fn of(video: &str) -> R<Probe> {
let out = Command::new("ffprobe")
.args(["-v", "error", "-show_entries", "stream=codec_type,width,height,r_frame_rate,duration,start_time:format=duration,start_time", "-of", "json", video])
.output()
.map_err(|e| format!("ffprobe: {e}"))?;
let entries = "stream=codec_type,width,height,r_frame_rate,duration,start_time:format=duration,start_time";
let out = Command::new("ffprobe").args(["-v", "error", "-show_entries", entries, "-of", "json", video]).output().map_err(|e| format!("ffprobe: {e}"))?;
let v: Value = serde_json::from_slice(&out.stdout).map_err(|e| format!("ffprobe: {e}"))?;
let streams = v["streams"].as_array().cloned().unwrap_or_default();
let vid = streams.iter().find(|s| s["codec_type"] == "video").ok_or("no video stream")?;
@@ -214,12 +267,7 @@ impl Probe {
Some(length) => seconds(&vid["start_time"]).unwrap_or(origin) - origin + length,
None => last_packet_end(video).map_or(duration, |end| end - origin),
};
Ok(Probe {
w: vid["width"].as_f64().unwrap_or(1920.0),
h: vid["height"].as_f64().unwrap_or(1080.0),
duration,
picture,
audio: streams.iter().any(|s| s["codec_type"] == "audio"),
})
let audio = streams.iter().any(|s| s["codec_type"] == "audio");
Ok(Probe { w: vid["width"].as_f64().unwrap_or(1920.0), h: vid["height"].as_f64().unwrap_or(1080.0), duration, picture, audio })
}
}
+38 -50
View File
@@ -1,87 +1,75 @@
//! `raea check EDIT.tsx --quick` and `raea hook claude` (docs/skills.feature SK10). The quick check renders three stills
//! of a composition (a quarter in, the middle, the last frame) with their manifest, about a second, and runs the full
//! check's text rules and the person's text taste on it: clipped and cramped text, safe areas, sizes. The hook is
//! Claude Code's PostToolUse command (`raea skills install --agent claude` adds it): after a .tsx that registers a root
//! is written, the quick check's findings go back to the agent; a clean check says nothing.
//! `raea check EDIT.tsx --quick` (docs/skills.feature SK10). The quick check renders three stills of a composition (a
//! quarter in, the middle, the last frame, of the length frame 0's render reports) with their manifest, and runs the text rules
//! and the person's text taste on it: clipped and cramped text, safe areas, sizes. Every agent's after-save hook runs
//! it (hook.rs): after a .tsx that registers a root is saved, its findings go back to the agent; a clean check says
//! nothing.
use super::*;
use std::path::Path;
/// The composition's length in frames, read from its source (the first `durationInFrames={N}`), 90 without one.
fn frames(src: &str) -> u64 {
src.split("durationInFrames={").nth(1).and_then(|r| r.split('}').next()).and_then(|n| n.trim().parse().ok()).unwrap_or(90)
/// The stills' frames: a quarter in, the middle and the last of the length a render reports (render.json's `length`,
/// the composition's own however it's written; #86 read its source's `durationInFrames={N}` and took 90 for a name).
fn samples(m: &Value) -> Option<[u64; 3]> {
let n = m["length"].as_u64()?.max(1);
Some([n / 4, n / 2, n - 1])
}
/// `raea check EDIT.tsx --quick [--shape S] [--platform P] [-o check.json]`: (report, P0 or P1 found). `tastes` are the
/// person's, evaluated by the raea CLI when --taste names them.
pub fn quick(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {
let file = args.iter().find(|a| a.ends_with(".tsx")).ok_or("raea check --quick takes a composition: EDIT.tsx")?;
let src = std::fs::read_to_string(file).map_err(|e| format!("{file}: {e}"))?;
let n = frames(&src).max(1);
let at = format!("{},{},{}", n / 4, n / 2, n - 1);
let tmp = std::env::temp_dir().join(format!("raea-quick-{}", std::process::id()));
std::fs::create_dir_all(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?;
let manifest = tmp.join("render.json");
let me = std::env::current_exe().map_err(|e| e.to_string())?;
let out = std::process::Command::new(me).arg("render").arg(file).args(["--at", &at, "-o"]).arg(format!("{}/", tmp.display())).arg("--manifest").arg(&manifest).output().map_err(|e| e.to_string())?;
let result = if out.status.success() {
on_manifest(file, &manifest, args, tastes)
// the stills are part of this check, which keeps the one entry in the project's record (DR3)
let render = |at: &str| std::process::Command::new(&me).arg("render").arg(file).args(["--at", at, "-o"]).arg(format!("{}/", tmp.display())).arg("--manifest").arg(&manifest).env("RAEA_RECORD", "off").output().map_err(|e| e.to_string());
// frame 0 first, for the length (its manifest's), then the three stills
let mut out = render("0")?;
let at = std::fs::read_to_string(&manifest).ok().and_then(|t| samples(&serde_json::from_str(&t).ok()?));
if let Some(at) = at {
let _ = std::fs::remove_file(&manifest);
out = render(&at.map(|f| f.to_string()).join(","))?;
}
// rendered when its manifest was written: a render whose stills clip exits 1 (DR3), and those findings are read here
let result = if let (Some(at), true) = (at, manifest.is_file()) {
on_manifest(file, &manifest, args, tastes, at)
} else {
// a render that fails is the finding: the agent sees why
let (err, out) = (String::from_utf8_lossy(&out.stderr), String::from_utf8_lossy(&out.stdout));
let mut why = Vec::new();
for line in err.lines().chain(out.lines()) {
if line.contains("REFUSED") || line.contains("rror") {
why.push(line);
}
}
let why = why.join("\n");
Ok((format!("raea check {file}: it doesn't render\nP0 render {why}"), true))
let why: Vec<&str> = err.lines().chain(out.lines()).filter(|l| l.contains("REFUSED") || l.contains("rror")).collect();
let f = raea_core_facts::Finding::new("render", raea_core_facts::Level::Error, why.join("\n"), "raea check --quick");
Ok((format!("raea check {file}: it doesn't render\n{}\nraea check: {}", f.line(), raea_core_facts::finding::count(&[f])), true))
};
let _ = std::fs::remove_dir_all(&tmp);
result
}
/// `raea hook claude`: Claude Code's PostToolUse input on stdin; for a saved composition, the quick check's findings as
/// the hook's additionalContext. Anything else, or a clean check, prints nothing.
pub fn hook(args: &[String]) -> R<String> {
if args.first().map(String::as_str) != Some("claude") {
return Err("usage: raea hook claude (Claude Code's PostToolUse hook; raea skills install --agent claude adds it)".into());
}
let mut input = String::new();
std::io::Read::read_to_string(&mut std::io::stdin(), &mut input).map_err(|e| e.to_string())?;
let v: serde_json::Value = serde_json::from_str(&input).unwrap_or_default();
let path = v["tool_input"]["file_path"].as_str().unwrap_or_default();
let composition = path.ends_with(".tsx") && std::fs::read_to_string(path).map(|t| t.contains("registerRoot")).unwrap_or(false);
if !composition {
return Ok(String::new());
}
let (report, _) = quick(&[path.to_string()], Vec::new())?;
if report.lines().nth(1).is_none_or(|l| l.starts_with("ok ")) {
return Ok(String::new());
}
let found: Vec<&str> = report.lines().filter(|l| !l.starts_with("ok ")).collect();
Ok(json!({"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": format!("raea check --quick after this save:\n{}", found.join("\n"))}}).to_string())
}
/// `raea check --quick`'s half (docs/skills.feature SK10): the text rules and the person's text taste on the manifest
/// of a few stills (`raea render EDIT.tsx --at ... --manifest`), no video. What it can't see (contrast, freezes,
/// sound, blotching) waits for the full check on the export.
fn on_manifest(file: &str, manifest: &Path, args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {
fn on_manifest(file: &str, manifest: &Path, args: &[String], tastes: Vec<raea_core_brief::Taste>, [a, b, c]: [u64; 3]) -> R<(String, bool)> {
let at = manifest.display();
let m: Value = serde_json::from_str(&std::fs::read_to_string(manifest).map_err(|e| format!("{at}: {e}"))?).map_err(|e| format!("{at}: {e}"))?;
let (mut issues, mut passed) = (Vec::new(), Vec::new());
let (mut issues, mut passed) = (Vec::new(), vec![format!("looked at frames {a}, {b} and {c} of {}", c + 1)]);
let runs = text_runs(&m);
let (w, h) = (m["width"].as_f64().unwrap_or(1080.0), m["height"].as_f64().unwrap_or(1920.0));
text_rules(&runs, None, w, h, flag(args, "--shape"), flag(args, "--platform"), &mut issues, &mut passed);
taste_text(&taste_rules(&tastes), &runs, w, h, &mut issues, &mut passed);
report(file, issues, passed, flag(args, "-o"))
// and what the render of the stills found (the 3D's clipping, DR3)
let more = serde_json::from_value(m["findings"].clone()).unwrap_or_default();
report(file, issues, more, passed, flag(args, "-o"), m["fps"].as_f64().unwrap_or(30.0))
}
#[cfg(test)]
mod tests {
use serde_json::json;
/// the length is the render's, so a `durationInFrames={DUR}` (#86: 300 frames, read as 90) is sampled to its end
#[test]
fn frames_come_from_the_source() {
assert_eq!(super::frames("<Composition durationInFrames={240} fps={30} />"), 240);
assert_eq!(super::frames("no composition"), 90);
fn frames_come_from_the_render() {
assert_eq!(super::samples(&json!({"length": 240})), Some([60, 120, 239]));
assert_eq!(super::samples(&json!({"length": 300})), Some([75, 150, 299]));
assert_eq!(super::samples(&json!({"length": 1})), Some([0, 0, 0]));
// a render that reported no length: no stills to look at, so the frame-0 render's failure is the finding
assert_eq!(super::samples(&json!({"width": 640})), None);
}
}
+13 -9
View File
@@ -27,6 +27,12 @@ pub(crate) fn pct(v: &[f64], q: f64) -> f64 {
/// a bed that stops under a voice shows in the band the voice doesn't fill (a projector's clatter in the highs). A band's
/// level is its share of the step's mean square (Parseval, undoing the Hann window's power), so a tone reads the same in
/// its band as in the mix
/// A stretch of sound's level in dB (its RMS)
pub(crate) fn db(f: &[f32]) -> f64 {
let ms = f.iter().map(|&v| (v as f64).powi(2)).sum::<f64>() / f.len().max(1) as f64;
20.0 * (ms.sqrt() + 1e-9).log10()
}
pub(crate) fn levels(x: &[f32]) -> (Vec<f64>, [Vec<f64>; 3]) {
use std::f64::consts::PI;
let n = x.len() / HOP;
@@ -44,8 +50,7 @@ pub(crate) fn levels(x: &[f32]) -> (Vec<f64>, [Vec<f64>; 3]) {
let scale = 2.0 / (HOP * HOP) as f64 / (hann.iter().map(|h| h * h).sum::<f64>() / HOP as f64);
let (mut rms, mut bands) = (Vec::with_capacity(n), [Vec::with_capacity(n), Vec::with_capacity(n), Vec::with_capacity(n)]);
for f in x.chunks_exact(HOP) {
let ms = f.iter().map(|&v| (v as f64).powi(2)).sum::<f64>() / HOP as f64;
rms.push(20.0 * (ms.sqrt() + 1e-9).log10());
rms.push(db(f));
let w: Vec<f64> = f.iter().zip(&hann).map(|(&v, h)| v as f64 * h).collect();
let mut e = [0.0; 3];
for (b, tw) in &bins {
@@ -163,7 +168,8 @@ pub(crate) fn sound(video: &str, words: Option<&[Word]>, issues: &mut Vec<Issue>
}
let x: Vec<f32> = out.stdout.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect();
let (rms, bands) = levels(&x);
let found = |list: Vec<(f64, String)>, p: u8| list.into_iter().map(move |(at, says)| Issue { rule: "sound", p, at: Some(at), says });
sound_defects(&x, issues, passed);
let found = |list: Vec<(f64, String)>, p: u8| crate::defects::moments("sound", p, list);
let stops = dead_stops(&rms, &bands);
if stops.is_empty() {
passed.push("sound: no steady sound stops dead".into());
@@ -206,17 +212,15 @@ pub(crate) fn ffmpeg_stderr(args: &[&str]) -> R<String> {
/// -14 LUFS integrated (±1) and a true peak at or below -1 dBTP (the floor's mix line)
pub(crate) fn loudness(video: &str, taste: Option<&Taste>, issues: &mut Vec<Issue>, passed: &mut Vec<String>) -> R<()> {
let err = ffmpeg_stderr(&["-hide_banner", "-nostats", "-i", video, "-vn", "-af", "ebur128=peak=true", "-f", "null", "-"])?;
let summary = err.rsplit("Summary:").next().unwrap_or("");
let num = |key: &str| summary.lines().find(|l| l.trim_start().starts_with(key)).and_then(|l| l.split_whitespace().nth(1)).and_then(|x| x.parse::<f64>().ok());
let (Some(i), peak) = (num("I:"), num("Peak:")) else { return Ok(()) };
// the same measure `raea world` joins to a render as its Mix (raea-sys-measure, DR2)
let Some((i, peak)) = raea_sys_measure::loudness(std::path::Path::new(video)) else { return Ok(()) };
let mut ok = true;
let target = taste.map_or(-14.0, |t| t.value);
if (i - target).abs() > 1.0 {
ok = false;
let says = format!("{i:.1} LUFS integrated; master at {target} (±1) with <Mix lufs={{{target}}} />");
issues.push(match taste {
Some(t) => Issue { rule: "taste", p: 1, at: None, says: format!("{says} (\"{}\")", t.line) },
Some(t) => Issue { rule: t.form, p: 1, at: None, says: format!("{says} (\"{}\")", t.line) },
None => Issue { rule: "loudness", p: 1, at: None, says },
});
}
@@ -258,7 +262,7 @@ pub(crate) fn freezes(video: &str, probe: &Probe, taste: Option<&Taste>, issues:
for &(s, d) in &stretches {
let says = format!("nothing changes for {d:.1} s; give it a reason to hold, or cut it shorter");
issues.push(match taste {
Some(t) => Issue { rule: "taste", p: 1, at: Some(s), says: format!("{says} (\"{}\")", t.line) },
Some(t) => Issue { rule: t.form, p: 1, at: Some(s), says: format!("{says} (\"{}\")", t.line) },
None => Issue { rule: "frozen", p: if d >= 6.0 || d >= probe.duration * 0.5 { 1 } else { 2 }, at: Some(s), says },
});
}
+91 -92
View File
@@ -64,8 +64,8 @@ fn taste_checks_hold_text_to_the_persons_line() {
]}]})).unwrap();
let rules = taste_rules(&[taste]);
assert_eq!(rules, vec![
Taste { form: "text-above".into(), value: 62.0, line: "Captions sit clear of the bottom.".into() },
Taste { form: "text-hold".into(), value: 2.0, line: "Text holds two seconds".into() },
Taste { form: "text-above", value: 62.0, line: "Captions sit clear of the bottom.".into() },
Taste { form: "text-hold", value: 2.0, line: "Text holds two seconds".into() },
]);
let low = Run { text: "Render anything.".into(), from: 1.0, to: 4.0, box_: [800.0, 800.0, 300.0, 60.0], boxes: vec![[800.0, 800.0, 300.0, 60.0]], color: String::new(), size: 48.0 };
let high = Run { text: "raea".into(), from: 5.0, to: 6.0, box_: [800.0, 300.0, 300.0, 60.0], boxes: vec![[800.0, 300.0, 300.0, 60.0]], color: String::new(), size: 48.0 };
@@ -73,7 +73,7 @@ fn taste_checks_hold_text_to_the_persons_line() {
taste_text(&rules, &[low, high], 1920.0, 1080.0, &mut issues, &mut passed);
let says: Vec<_> = issues.iter().map(|i| (i.rule, i.p, i.at)).collect();
// the low caption breaks the placement line (860 of 1080 is 80%); the short one breaks the hold
assert_eq!(says, vec![("taste", 1, Some(1.0)), ("taste", 1, Some(5.0))]);
assert_eq!(says, vec![("text-above", 1, Some(1.0)), ("text-hold", 1, Some(5.0))], "a taste line is the named check of its form (DR4)");
}
/// `RAEA_CHECK_ARGS="film.mp4 --manifest film.render.json --taste DIR" cargo test -p raea-runtime-react --lib
@@ -292,72 +292,6 @@ fn a_sign_the_camera_carries_off_isnt_clipped_but_a_title_held_off_is() {
assert_eq!(rules, vec![("safe-area", "THE NIGHT MARKET".to_string()), ("clipped", "WIDE".to_string())]);
}
/// a 96x54 picture drawn by `paint(frame index, sample, x, y)`, sample 0 the area sample and 1 the point sample, for
/// `frames` frames at `fps`
fn flash_samples(frames: usize, fps: f64, paint: impl Fn(usize, usize, usize, usize) -> [u8; 3]) -> Option<(usize, f64, &'static str)> {
let (w, h) = (96, 54);
let mut screen = FlashScreen::new(w, h);
for f in 0..frames {
let mut rgb = Vec::with_capacity(w * 2 * h * 3);
for y in 0..h {
for sample in 0..2 {
for x in 0..w {
rgb.extend_from_slice(&paint(f, sample, x, y));
}
}
}
screen.push(&rgb, f as f64 / fps);
}
screen.finish()
}
fn flash_of(seconds: usize, paint: impl Fn(usize, usize, usize) -> [u8; 3]) -> Option<(usize, f64, &'static str)> {
flash_samples(seconds * 60, 60.0, move |f, _, x, y| paint(f, x, y))
}
/// two colours taking turns `hz` times a second, over a box of the frame
fn turns(hz: usize, on: [u8; 3], off: [u8; 3], bx: (usize, usize, usize, usize)) -> Option<(usize, f64, &'static str)> {
flash_of(3, move |f, x, y| {
let inside = x >= bx.0 && x < bx.0 + bx.2 && y >= bx.1 && y < bx.1 + bx.3;
if inside && f * hz * 2 / 60 % 2 == 0 { on } else { off }
})
}
#[test]
fn flashing_is_found_past_three_a_second_and_not_at_it() {
let (white, black) = ([255, 255, 255], [0, 0, 0]);
let all = (0, 0, 96, 54);
assert_eq!(turns(3, white, black, all), None, "three a second is the limit, not past it");
let (swings, _, kind) = turns(4, white, black, all).expect("four a second");
assert_eq!((swings / 2, kind), (4, "general"));
// a small box: under a quarter of any window, and then over it
assert_eq!(turns(5, white, black, (40, 20, 10, 10)), None);
assert!(turns(5, white, black, (30, 18, 32, 18)).is_some());
// too small a change, and both ends too bright for WCAG to count it
assert_eq!(turns(5, [60, 60, 60], [30, 30, 30], all), None);
assert_eq!(turns(5, [255, 255, 255], [235, 235, 235], all), None);
// a dark saturated red: too dim to count as a general flash, past the limit as a red one
assert_eq!(turns(5, [150, 0, 0], black, all).map(|t| t.2), Some("red"));
}
#[test]
fn a_flash_of_single_frames_counts_at_any_frame_rate() {
// 120 fps with one white frame in every 30: four flashes a second, each gone within a sixtieth of a second
let found = flash_samples(360, 120.0, |f, _, _, _| if f % 30 == 1 { [255, 255, 255] } else { [0, 0, 0] });
assert_eq!(found.map(|(swings, _, kind)| (swings / 2, kind)), Some((4, "general")));
}
#[test]
fn a_flash_the_area_sample_averages_away_is_found_in_the_point_sample() {
let found = flash_samples(180, 60.0, |f, sample, _, _| {
if sample == 0 {
return [128, 128, 128];
}
if f * 5 * 2 / 60 % 2 == 0 { [255, 255, 255] } else { [0, 0, 0] }
});
assert!(found.is_some(), "the same flash in the point sample alone");
}
#[test]
fn a_frame_gets_its_exact_time_from_the_log() {
// lines FFmpeg 9.0.2 logged with -loglevel level+info
@@ -382,34 +316,99 @@ fn only_a_lines_own_severity_counts_as_an_error() {
assert_eq!(log_level("frame= 300 fps=0.0"), None);
}
/// A centred line in a left: 0; right: 0 box isn't in the left zone: its letters are tested where the render recorded
/// them (#89); a left-aligned one is, the finding naming the edge, and a manifest without ink is tested by the box.
#[test]
fn a_shape_sliding_past_and_ordinary_cuts_are_not_flashing() {
let (white, black) = ([255, 255, 255], [0, 0, 0]);
assert_eq!(flash_of(3, move |f, x, _| if x < f { white } else { black }), None, "one wipe across the frame");
assert_eq!(flash_of(4, move |f, _, _| if (f / 30) % 2 == 0 { white } else { black }), None, "a cut every half second");
fn safe_area_tests_the_letters_not_the_box() {
let safe_area = |ink: Value| {
let m = json!({"fps": 1.0, "frames": [{"frame": 0, "text": [{"text": "centred", "box": [0, 160, 640, 40], "ink": ink}]}]});
let (mut issues, mut passed) = (vec![], vec![]);
text_rules(&text_runs(&m), None, 640.0, 360.0, None, None, &mut issues, &mut passed);
issues.into_iter().filter(|i| i.rule == "safe-area").map(|i| i.says).collect::<String>()
};
assert_eq!(safe_area(json!([250, 160, 140, 40])), "");
let left = safe_area(json!([0, 160, 140, 40]));
assert!(left.contains("at the left") && left.contains("its letters 0,160 140x40"), "{left}");
assert!(safe_area(Value::Null).contains("its box 0,160 640x40"));
}
#[test]
fn a_patch_strobing_while_its_background_dims_is_still_found() {
// a third of a window: 0 then 124 on a 148 background, then the background settles at 124 and the patch cycles 124 and 160.
// The background's drop is under the 0.10 that counts, but it outweighs the patch in the window's mean.
let found = flash_samples(180, 60.0, |f, _, x, y| {
let patch = x < 16 && y < 12;
let level = match (patch, f) {
(true, 0) => 0,
(true, 1) => 124,
(true, _) => if (f - 2) * 5 * 2 / 60 % 2 == 0 { 160 } else { 124 },
(false, 0 | 1) => 148,
(false, _) => 124,
};
[level, level, level]
});
assert!(found.is_some(), "the patch flashes five times a second");
fn a_card_sharing_one_word_with_another_line_isnt_held_to_it() {
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 2.0, box_: [0.0; 4], boxes: vec![], color: String::new(), size: 48.0 };
let said = |ws: &[(&str, f64)]| ws.iter().map(|(t, s)| Word { text: (*t).into(), start: *s, end: *s }).collect::<Vec<Word>>();
let words = said(&[("at", 37.9), ("wirestock", 38.2), ("i", 38.9), ("worked", 39.0), ("on", 39.2), ("a", 39.3), ("sora", 39.5), ("campaign", 40.2)]);
let (mut issues, mut passed) = (vec![], vec![]);
// one word of three shared with the line, said 1.35 s before: not a caption of it (the film's false P1)
cues(&[run("Wirestock × OpenAI Sora", 39.55)], &words, &mut issues, &mut passed);
// one word of four, "campaign": the same
cues(&[run("Classroom of Tomorrow campaign", 39.55)], &words, &mut issues, &mut passed);
assert!(issues.is_empty(), "{:?}", issues.iter().map(|i| &i.says).collect::<Vec<_>>());
// a one-word card is held only to the word said right by it: "wirestock" 1.35 s earlier is another moment
cues(&[run("Wirestock", 39.55)], &words, &mut issues, &mut passed);
assert!(issues.is_empty(), "{:?}", issues.iter().map(|i| &i.says).collect::<Vec<_>>());
// a real caption late by 0.4 s is still found
cues(&[run("a Sora campaign", 39.7)], &words, &mut issues, &mut passed);
assert_eq!(issues.len(), 1, "{:?}", issues.iter().map(|i| &i.says).collect::<Vec<_>>());
}
#[test]
fn a_colour_crossing_the_saturation_line_is_not_a_red_flash() {
// one level of green moves the pixel across R/(R+G+B) = 0.8 and hardly changes its red at all
let found = flash_samples(180, 60.0, |f, _, _, _| if f * 5 * 2 / 60 % 2 == 0 { [100, 49, 0] } else { [100, 50, 0] });
assert_eq!(found, None);
fn clipping_is_found_and_a_loud_clean_tone_isnt() {
// a clean tone near full scale, then the same tone clamped (a limiter's flat tops), then pushed past full scale
let loud = tone(3.0, &[(0.0, 3.0, -1.0)]);
assert!(clipped(&loud).is_empty(), "{:?}", clipped(&loud));
let clamped: Vec<f32> = loud.iter().map(|v| (v * 10.0).clamp(-0.3, 0.3)).collect();
assert_eq!(clipped(&clamped).len(), 1);
let over: Vec<f32> = loud.iter().map(|v| (v * 2.0).clamp(-1.0, 1.0)).collect();
assert_eq!(clipped(&over).len(), 1);
// one transient hitting full scale once isn't clipping
let mut once = tone(3.0, &[(0.0, 3.0, -20.0)]);
once[SR] = 1.0;
assert!(clipped(&once).is_empty());
}
#[test]
fn a_dropout_is_found_and_a_faded_pause_isnt() {
// a bed at -20 dBFS with 0.6 s cut out of it, as the bootstrap's dropout does
let mut cut = tone(4.0, &[(0.0, 4.0, -20.0)]);
cut[(1.7 * SR as f64) as usize..(2.3 * SR as f64) as usize].iter_mut().for_each(|v| *v = 0.0);
let found = dropouts(&cut);
assert_eq!(found.len(), 1, "{found:?}");
assert!((found[0].0 - 1.7).abs() < 0.02, "{found:?}");
// a pause that fades out over 300 ms and back in isn't one, nor a sound that stops and stays stopped
let gain = |t: f32| ((1.7 - t) / 0.3).max((t - 2.3) / 0.3).clamp(0.0, 1.0);
let paused: Vec<f32> = tone(4.0, &[(0.0, 4.0, -20.0)]).into_iter().enumerate().map(|(i, v)| v * gain(i as f32 / SR as f32)).collect();
assert!(dropouts(&paused).is_empty(), "{:?}", dropouts(&paused));
assert!(dropouts(&tone(4.0, &[(0.0, 2.0, -20.0)])).is_empty());
}
#[test]
fn a_flash_frame_is_found_and_a_cut_or_a_fade_isnt() {
let mut shot = vec![0.5f32; 60];
shot[30] = 0.0;
assert_eq!(flash_frames(&shot, 30.0).len(), 1);
shot[31] = 0.0;
assert_eq!(flash_frames(&shot, 30.0).len(), 1, "two frames are one flash");
let cut: Vec<f32> = (0..60).map(|i| if i < 30 { 0.6 } else { 0.1 }).collect();
assert!(flash_frames(&cut, 30.0).is_empty());
let fade: Vec<f32> = (0..60).map(|i| 0.6 * (1.0 - i as f32 / 59.0)).collect();
assert!(flash_frames(&fade, 30.0).is_empty());
// a white frame, too
let mut white = vec![0.3f32; 20];
white[10] = 1.0;
assert_eq!(flash_frames(&white, 30.0)[0].0, 10.0 / 30.0);
}
#[test]
fn things_found_are_findings_and_an_unknown_rule_is_not() {
let p = std::env::temp_dir().join(format!("raea-check-things-{}.json", std::process::id()));
let found = r#"{"issues": [{"rule": "floating", "p": 2, "at": 1.5, "to": 3.0, "says": "cup floats"}, {"rule": "made-up", "p": 0, "at": 0.0, "says": "x"}]}"#;
std::fs::write(&p, found).unwrap();
let (mut issues, mut passed) = (Vec::new(), Vec::new());
things(p.to_str().unwrap(), &mut issues, &mut passed).unwrap();
assert_eq!(issues.iter().map(|i| (i.rule, i.p, i.at)).collect::<Vec<_>>(), [("floating", 2, Some(1.5))]);
std::fs::write(&p, r#"{"issues": []}"#).unwrap();
things(p.to_str().unwrap(), &mut Vec::new(), &mut passed).unwrap();
let _ = std::fs::remove_file(&p);
assert_eq!(passed.len(), 1, "nothing found is a pass");
}
+29 -63
View File
@@ -8,7 +8,8 @@ pub(crate) struct Run {
pub(crate) from: f64,
pub(crate) to: f64,
pub(crate) box_: [f64; 4],
/// its box on every frame it shows its whole text: a text the camera carries (a sign on a panning street) moves
/// where its letters are on every frame it shows its whole text (the manifest's `ink`, else its box: a centred line in
/// a full-width box is nowhere near x = 0, #89): a text the camera carries (a sign on a panning street) moves
/// through the frame's edges and zones, which only counts against it when no frame shows it clear
pub(crate) boxes: Vec<[f64; 4]>,
pub(crate) color: String,
@@ -61,7 +62,8 @@ pub(crate) fn text_runs(manifest: &Value) -> Vec<Run> {
let mut next = Vec::new();
for x in shown {
let text = x["text"].as_str().unwrap_or("").trim().to_string();
let b = x["box"].as_array().map(|b| [0, 1, 2, 3].map(|i| b.get(i).and_then(Value::as_f64).unwrap_or(0.0))).unwrap_or([0.0; 4]);
let quad = |k: &str| x[k].as_array().map(|b| [0, 1, 2, 3].map(|i| b.get(i).and_then(Value::as_f64).unwrap_or(0.0)));
let (b, ink) = (quad("box").unwrap_or([0.0; 4]), quad("ink"));
let k = key(&text);
let found = open.iter().position(|r| {
let rk = key(&r.text);
@@ -77,7 +79,7 @@ pub(crate) fn text_runs(manifest: &Value) -> Vec<Run> {
if text.len() >= r.text.len() {
r.text = text;
r.box_ = b;
r.boxes.push(b);
r.boxes.push(ink.unwrap_or(b));
}
r.to = t + 1.0 / fps;
r.color = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string();
@@ -169,7 +171,9 @@ pub(crate) fn text_rules(runs: &[Run], heard: Option<&[Word]>, w: f64, h: f64, s
issues.push(Issue { rule: "clipped", p: 0, at: Some(r.from), says: format!("{q} runs off the frame (box {x:.0},{y:.0} {bw:.0}x{bh:.0} in {w:.0}x{h:.0}); fit it or break the line") });
} else if r.boxes.iter().all(zoned) {
unsafe_ += 1;
issues.push(Issue { rule: "safe-area", p: 1, at: Some(r.from), says: format!("{q} sits in the app's UI zone (keep {zt:.0} px top, {zb:.0} bottom, {zl:.0} left, {zr:.0} right clear)") });
let [ix, iy, iw, ih] = *r.boxes.last().unwrap_or(&r.box_);
let edge = if iy < zt { format!("the top (keep {zt:.0} px clear)") } else if iy + ih > h - zb { format!("the bottom (keep {zb:.0} px clear)") } else if ix < zl { format!("the left (keep {zl:.0} px clear)") } else { format!("the right (keep {zr:.0} px clear)") };
issues.push(Issue { rule: "safe-area", p: 1, at: Some(r.from), says: format!("{q} sits in the app's UI zone at {edge}: its {} {ix:.0},{iy:.0} {iw:.0}x{ih:.0} in {w:.0}x{h:.0}", if r.boxes.last() == Some(&r.box_) { "box" } else { "letters" }) });
}
let words = r.text.split_whitespace().count() as f64;
let need = (0.3 * words).max(1.0);
@@ -195,20 +199,6 @@ pub(crate) fn quote(s: &str) -> String {
format!("\u{201c}{s}\u{201d}")
}
pub(crate) fn rgb_of(css: &str) -> [f64; 3] {
let n: Vec<f64> = css.split(|c: char| !(c.is_ascii_digit() || c == '.')).filter(|s| !s.is_empty()).filter_map(|s| s.parse().ok()).collect();
[n.first().copied().unwrap_or(255.0), n.get(1).copied().unwrap_or(255.0), n.get(2).copied().unwrap_or(255.0)]
}
/// relative luminance (WCAG) of an sRGB colour 0-255
pub(crate) fn lum([r, g, b]: [f64; 3]) -> f64 {
let c = |v: f64| {
let v = v / 255.0;
if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
};
0.2126 * c(r) + 0.7152 * c(g) + 0.0722 * c(b)
}
/// Caption contrast: at each text's middle frame, the pixels behind it against its colour, at least 3:1. The pixels
/// behind are the half of the box least like the text.
pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe, issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
@@ -217,29 +207,13 @@ pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe,
let mut measured = 0;
for r in runs.iter().filter(|r| r.size >= 20.0).take(80) {
let [x, y, bw, bh] = r.box_;
// even sizes and offsets: the decoder's 4:2:0 frame crops to them
let (cx, cy, cw, ch) = ((x * sx).max(0.0) as u32 & !1, (y * sy).max(0.0) as u32 & !1, ((bw * sx) as u32).max(2) & !1, ((bh * sy) as u32).max(2) & !1);
if cx + cw > probe.w as u32 || cy + ch > probe.h as u32 {
let crop = [(x * sx).max(0.0) as u32, (y * sy).max(0.0) as u32, (bw * sx) as u32, (bh * sy) as u32];
if crop[0] + crop[2] > probe.w as u32 || crop[1] + crop[3] > probe.h as u32 {
continue;
}
let t = (r.from + r.to) / 2.0;
let Ok(out) = Command::new("ffmpeg")
.args(["-v", "error", "-ss", &format!("{t:.3}"), "-i", video, "-frames:v", "1", "-vf", &format!("crop={cw}:{ch}:{cx}:{cy}"), "-f", "rawvideo", "-pix_fmt", "rgb24", "-"])
.output()
else {
continue;
};
if out.stdout.len() < (cw * ch * 3) as usize {
continue;
}
let text = lum(rgb_of(&r.color));
let mut ls: Vec<f64> = out.stdout.chunks_exact(3).map(|p| lum([p[0] as f64, p[1] as f64, p[2] as f64])).collect();
ls.sort_by(|a, b| (b - text).abs().total_cmp(&(a - text).abs()));
let behind = &ls[..ls.len() / 2];
let mut sorted = behind.to_vec();
sorted.sort_by(f64::total_cmp);
let bg = sorted[sorted.len() / 2];
let ratio = (text.max(bg) + 0.05) / (text.min(bg) + 0.05);
// the same measure `raea world` joins to a text from its render (raea-sys-measure, DR2)
let Some(ratio) = raea_sys_measure::contrast(std::path::Path::new(video), t, crop, &r.color) else { continue };
measured += 1;
if ratio < 3.0 {
low += 1;
@@ -251,35 +225,18 @@ pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe,
}
}
pub(crate) struct Word {
pub(crate) text: String,
pub(crate) start: f64,
/// when the word ends, in seconds (its start when the transcript doesn't say)
pub(crate) end: f64,
}
/// A transcript's word: its text, start and end in seconds (its end is its start when the transcript doesn't say).
pub(crate) use raea_core_facts::Word;
/// raea's transcript shape (an array of {text|word, start|from|start_ms, …}), or a flat array of {w, t}
/// A transcript's words: {text, start} in seconds (or t, or start_ms), or {text, from} in frames at `fps`, as the app's
/// words.json and `raea render --words` have them.
/// A transcript's words (raea_core_facts::transcript_words: {text, start} in seconds, or t, start_ms, or {text, from}
/// in frames at `fps`), as the app's words.json and `raea render --words` have them.
pub(crate) fn transcript(path: &str, fps: f64) -> R<Vec<Word>> {
let v: Value = serde_json::from_str(&std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?).map_err(|e| format!("{path}: {e}"))?;
let list = v.as_array().ok_or_else(|| format!("{path}: expected an array of words ({{text, start}} in seconds or {{text, from}} in frames)"))?;
Ok(list
.iter()
.filter_map(|w| {
let text = w.get("text").or_else(|| w.get("word")).or_else(|| w.get("w"))?.as_str()?.to_string();
// the time keys a transcript may use, each with what turns it into seconds
let secs = |keys: &[(&str, f64)]| keys.iter().find_map(|(k, to_s)| Some(w.get(*k)?.as_f64()? * to_s));
let start = secs(&[("start", 1.0), ("t", 1.0), ("a", 1.0), ("start_ms", 0.001), ("from", 1.0 / fps)])?;
let end = secs(&[("end", 1.0), ("b", 1.0), ("end_ms", 0.001), ("to", 1.0 / fps)]).unwrap_or(start);
Some(Word { text, start, end })
})
.collect())
v.as_array().ok_or_else(|| format!("{path}: expected an array of words ({{text, start}} in seconds or {{text, from}} in frames)"))?;
Ok(raea_core_facts::transcript_words(&v, fps))
}
pub(crate) fn norm(s: &str) -> String {
s.chars().filter(|c| c.is_alphanumeric()).collect::<String>().to_lowercase()
}
pub(crate) use raea_core_facts::word_key as norm;
pub(crate) const SMALL: [&str; 24] = ["the", "and", "you", "your", "for", "with", "that", "this", "its", "it's", "are", "was", "our", "out", "from", "into", "then", "than", "but", "not", "all", "can", "has", "have"];
@@ -291,12 +248,21 @@ pub(crate) fn cues(runs: &[Run], words: &[Word], issues: &mut Vec<Issue>, passed
for r in runs {
let shown: Vec<String> = r.text.split_whitespace().map(norm).filter(|t| !t.is_empty()).collect();
let Some((k, i)) = shown.iter().enumerate().filter(|(_, t)| t.len() >= 3 && !SMALL.contains(&t.as_str())).find_map(|(k, t)| {
words.iter().enumerate().filter(|(_, w)| norm(&w.text) == *t && (w.start - r.from).abs() <= 2.0).min_by(|(_, a), (_, b)| (a.start - r.from).abs().total_cmp(&(b.start - r.from).abs())).map(|(i, _)| (k, i))
// a one-word card matches only a word said right by it: the same word said 2 s earlier is another moment
let near = if shown.len() == 1 { 0.75 } else { 2.0 };
words.iter().enumerate().filter(|(_, w)| norm(&w.text) == *t && (w.start - r.from).abs() <= near).min_by(|(_, a), (_, b)| (a.start - r.from).abs().total_cmp(&(b.start - r.from).abs())).map(|(i, _)| (k, i))
}) else {
continue;
};
// back over the words the text shows before it, while the voice says them in the same order just before
let back = (1..=k.min(i)).take_while(|&n| norm(&words[i - n].text) == shown[k - n]).last().unwrap_or(0);
// a caption says what the voice says: at least half its words, in order, around the anchor. A card that only
// shares one word with another line ("Wirestock x OpenAI Sora" against "At Wirestock, I worked on...") isn't
// a caption of it, and holding it to that word's time was a false P1
let fwd = (1..).take_while(|&n| k + n < shown.len() && i + n < words.len() && norm(&words[i + n].text) == shown[k + n]).last().unwrap_or(0);
if (back + 1 + fwd) * 2 < shown.len() {
continue;
}
let w = &words[i - back];
let tok = norm(&w.text);
checked += 1;
+24
View File
@@ -0,0 +1,24 @@
[package]
name = "raea-app-direction"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "How raea takes direction (docs/direction.feature): `raea world`, a composition's frame as one world of facts, queried across media"
[dependencies]
raea-runtime-world = { path = "../../runtime/world" }
raea-runtime-bundle = { path = "../../runtime/bundle" }
raea-core-facts = { path = "../../core/facts" }
# a render's record named by when it was (UTC)
raea-io-trace = { path = "../../io/trace" }
serde_json = "1"
# `raea check PROJECT | EDIT.tsx` (DR4): taste and controllers' rules, the floor on a composition's newest render, the
# project's compositions
raea-core-brief = { path = "../../core/brief" }
raea-app-check = { path = "../check" }
raea-app-registry = { path = "../workspace/registry" }
# the project's notes, whose asks' checks raea check runs beside its rules (DR6)
raea-app-notes = { path = "../notes" }
# a TS check's run printing nothing to the terminal (its ECHO)
raea-runtime-react = { path = "../../runtime/react", default-features = false }
+378
View File
@@ -0,0 +1,378 @@
//! `raea check PROJECT|EDIT.tsx` (docs/direction.feature DR4): every check that applies, run over each
//! composition's worlds. The rules come from raea's floor, the person's taste (and the workspace's), and the
//! workspace's and the project's controllers; each is one of raea's named checks (systems.rs) or a project's TS check
//! (ts.rs), and where it was written changes nothing about how it runs. A check that needs a render runs on the
//! composition's newest render; with none, it waits, and the command says what for. `raea check VIDEO.mp4` is the
//! floor alone (apps/check).
use std::path::{Path, PathBuf};
use raea_core_brief::{controller, taste};
use raea_core_facts::{finding, record, Facts, Finding, Level, Rule, Shot};
use raea_runtime_bundle::flag;
use raea_runtime_world::{Ask, Render};
use serde_json::{json, Value};
use crate::systems::{self, Frames};
use crate::ts;
type R<T> = Result<T, String>;
pub const USAGE: &str = "raea check [PROJECT|EDIT.tsx] [--composition ID] [--only ID] [--taste T] [--render OUT | --no-render] [--json] (every check that applies to each composition, over its frames: raea's floor on its newest render, the person's taste, the workspace's and the project's rules (a controller's rule fields: one of raea's checks by name, or a project's .ts check); what needs a render and has none waits, and says so)";
/// The flags raea check takes with a value (its own, and the floor's on a video).
const TAKES: [&str; 10] = ["--composition", "--only", "--taste", "--render", "--manifest", "--words", "--perception", "--shape", "--platform", "-o"];
/// What the CLI lends `raea check`: its TS evaluator and headless run, and the taste kinds a mode needs (as `raea
/// context` reads the person's taste).
pub struct Host {
pub ts: ts::Host,
pub kinds: fn(&str) -> &'static [&'static str],
}
/// The person's taste folder: RAEA_TASTE, else ~/.raea/taste.
pub fn taste_dir() -> Option<PathBuf> {
std::env::var_os("RAEA_TASTE").map(PathBuf::from).or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".raea/taste")))
}
/// The .ts files `--taste` names: the file, or every .ts in the folder. A file named under the person's taste folder
/// that isn't there yet is a note, not a refusal: the skill prescribes --taste on that folder's own taste file, and a
/// machine with none yet should still check (#89); any other missing path is left to the reader to refuse.
pub fn taste_files(args: &[String]) -> Vec<PathBuf> {
let Some(t) = flag(args, "--taste").map(PathBuf::from) else { return vec![] };
if t.extension().is_some_and(|x| x == "ts") {
let home = taste_dir().map(std::path::absolute).and_then(Result::ok);
if !t.is_file() && t.parent().map(std::path::absolute).and_then(Result::ok) == home {
eprintln!("note: no taste yet ({} isn't there); checking without it", t.display());
return vec![];
}
return vec![t];
}
let mut v: Vec<PathBuf> = std::fs::read_dir(&t).into_iter().flatten().filter_map(|e| e.ok().map(|e| e.path())).filter(|f| f.extension().is_some_and(|x| x == "ts")).collect();
v.sort();
v
}
/// The taste files a project is held to: `--taste`'s when given, else the person's taste.ts (RAEA_TASTE, or
/// ~/.raea/taste) and the kinds its brief's modes need, then the workspace's house rules.
fn tastes(project: &Path, given: Vec<PathBuf>, host: &Host) -> Vec<PathBuf> {
if !given.is_empty() {
return given;
}
let mut out = Vec::new();
if let Some(dir) = taste_dir().filter(|d| d.join("taste.ts").is_file()) {
out.push(dir.join("taste.ts"));
let brief: Value = (host.ts.eval)(&project.join("brief.ts")).ok().and_then(|j| serde_json::from_str(&j).ok()).unwrap_or_default();
for m in brief["mode"].as_array().into_iter().flatten().filter_map(Value::as_str) {
for f in (host.kinds)(&m.trim().to_ascii_lowercase()).iter().map(|k| dir.join(format!("{k}.ts"))) {
if f.is_file() && !out.contains(&f) {
out.push(f);
}
}
}
}
out.extend(record::up(project, ".raea/workspace").map(|ws| ws.join("taste.ts")).filter(|f| f.is_file()));
out
}
/// One rule as it runs: a named check, or a project's check file's declaration.
enum How {
Named(systems::Named),
File(ts::Meta),
}
/// Every rule `project` is held to (`given`: `--taste`'s files) with its notes' asks (DR6), the notes, and a finding
/// for each file of rules or note raea couldn't read.
fn rules(project: &Path, given: Vec<PathBuf>, host: &Host) -> (Vec<Rule>, Vec<Finding>, Vec<raea_app_notes::Kept>) {
let (mut out, mut bad) = held(project, given, host);
let notes = raea_app_notes::read(project, host.ts.eval);
let (asks, unread) = raea_app_notes::check::rules(project, &notes);
out.extend(asks);
bad.extend(unread);
// a check's path made plain (no `..`), as its import will name it
for r in out.iter_mut() {
if let Some(p) = r.file() {
r.check = raea_runtime_bundle::normalize(p).display().to_string();
}
}
(out, bad, notes)
}
/// raea's floor, the person's taste and the workspace's and project's controllers' rules, and a finding for each file
/// of them raea couldn't read.
fn held(project: &Path, given: Vec<PathBuf>, host: &Host) -> (Vec<Rule>, Vec<Finding>) {
// raea's own: the floor, and the reading check (DR28: its findings keep their own levels, so no rule level)
let read = Rule { level: None, ..Rule::named("text-read", "text can be read for as long as it needs, and OCR reads it", Default::default(), Level::Warn, "raea") };
let mut out = vec![Rule::named("floor", "raea's floor", Default::default(), Level::Error, "raea"), read];
let mut bad = Vec::new();
let name = |f: &Path| f.strip_prefix(project).unwrap_or(f).display().to_string();
for f in tastes(project, given, host) {
match (host.ts.eval)(&f).and_then(|j| raea_core_brief::read::<taste::Taste>(&name(&f), &j)) {
Ok(t) => out.extend(t.sections.iter().flat_map(|s| &s.rules).filter_map(|r| Some(Rule::of_taste(&r.text, r.check?, &name(&f))))),
Err(e) => bad.push(Finding::new("taste", Level::Error, format!("raea can't read it: {e}"), "raea check").about(name(&f), None)),
}
}
let ws = record::up(project, ".raea/workspace");
for (dir, scope) in ws.iter().map(|w| (raea_app_registry::shared_dir(w, "controllers"), "workspace")).chain([(project.join("controllers"), "project")]) {
// a workspace's own folder is its project's too: read once
if scope == "project" && ws.as_deref() == Some(project) {
continue;
}
let mut files: Vec<PathBuf> = std::fs::read_dir(&dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "ts")).collect();
files.sort();
for f in files {
match (host.ts.eval)(&f).and_then(|j| controller::of_json(&j)) {
Ok(c) => out.extend(Rule::of_controller(&c, &dir, &format!("{scope} {}", name(&f)))),
Err(e) => bad.push(Finding::new("controller", Level::Error, format!("raea can't read it: {e}"), "raea check").about(name(&f), None)),
}
}
}
(out, bad)
}
/// The compositions `target` names: each (its file, its id when the file registers several).
fn compositions(target: &Path, args: &[String]) -> R<Vec<(PathBuf, Option<String>)>> {
let one = flag(args, "--composition");
let (dir, file) = if target.is_dir() { (target.to_path_buf(), None) } else { (target.parent().unwrap_or(Path::new(".")).to_path_buf(), Some(target.canonicalize().map_err(|e| format!("{}: {e}", target.display()))?)) };
let reg = raea_app_registry::scan(&dir, &[]);
let mut out: Vec<(PathBuf, Option<String>)> = Vec::new();
for c in &reg.compositions {
let path = reg.dir.join(&c.file);
let path = path.canonicalize().unwrap_or(path);
let id = (c.how == raea_app_registry::How::Registered).then(|| c.id.clone());
if file.as_ref().is_none_or(|f| *f == path) && one.as_ref().is_none_or(|o| Some(o) == id.as_ref()) {
out.push((path, id));
}
}
if out.is_empty() {
match (file, one) {
// a file the scan didn't register (outside a project): itself
(Some(f), one) => out.push((f, one)),
(None, one) => return Err(format!("no composition in {}{}", dir.display(), one.map(|o| format!(" named {o}")).unwrap_or_default())),
}
}
Ok(out)
}
/// What one composition's checks found, each check that waits with what for, and its newest render, its named shots
/// (each from its first frame to its end) and its rate, for a note's clip (DR6).
struct Checked {
file: PathBuf,
id: Option<String>,
found: Vec<Finding>,
waits: Vec<(String, String)>,
render: Option<raea_app_notes::check::Rendered>,
shots: Vec<(String, i64, Option<i64>)>,
fps: f64,
}
/// One composition checked against `rules` (`--only`'s already picked), every frame read when `whole` or a check
/// ranges over them.
fn check_one(tsx: &Path, id: Option<String>, rules: &[Rule], args: &[String], whole: bool, host: &Host) -> R<Checked> {
let named = systems::named();
let mut found = Vec::new();
let mut hows = Vec::new();
for r in rules {
match r.file() {
Some(f) => match ts::meta(f, &host.ts) {
Ok(m) => hows.push((r, How::File(m))),
Err(e) => found.push(Finding::new(&r.id, Level::Error, e, &r.by)),
},
None => match named.iter().find(|n| n.name == r.check) {
Some(n) => hows.push((r, How::Named(n.clone()))),
None => found.push(Finding::new(&r.id, Level::Error, format!("raea has no check named {} (its checks: {}, or a .ts check's path)", r.check, named.iter().map(|n| n.name).collect::<Vec<_>>().join(", ")), &r.by)),
},
}
}
let frames: Vec<&Frames> = hows.iter().map(|(_, h)| match h { How::Named(n) => &n.frames, How::File(m) => &m.frames }).collect();
// every frame when a check ranges over them (cuts and lines are found in them), else the frames named and the first
let whole = whole || frames.iter().any(|f| f.whole());
let mut asked: Vec<i64> = if whole { Vec::new() } else { frames.iter().flat_map(|f| if let Frames::At(v) = f { v.clone() } else { vec![] }).chain([0]).collect() };
asked.sort();
asked.dedup();
// the render joins the first frame (what it is, or that there is none) and where a TS check needs it
let join_all = hows.iter().any(|(_, h)| match h {
How::File(m) => m.render && m.frames.whole(),
How::Named(n) => n.render && n.frames.whole(),
});
let join_on = (!join_all).then(|| hows.iter().flat_map(|(_, h)| match h { How::File(m) if m.render => if let Frames::At(v) = &m.frames { v.clone() } else { vec![] }, _ => vec![] }).chain([0]).collect());
let render_how = match (flag(args, "--render"), args.iter().any(|a| a == "--no-render")) {
(Some(o), _) => Render::From(o.into()),
(None, true) => Render::Off,
(None, false) => Render::Newest,
};
let mut opts_args = vec![tsx.display().to_string()];
if let Some(i) = &id {
opts_args.extend(["--composition".to_string(), i.clone()]);
}
let opts = raea_runtime_bundle::comp_opts(&opts_args)?;
let worlds = raea_runtime_world::read(tsx, &opts, &Ask { frames: asked, layout: true, render: render_how, join_on })?;
let rendered = worlds.first().and_then(|w| w.resources.get("Rendered")).cloned();
let mut waits = Vec::new();
let needs = |w: &mut Vec<(String, String)>, r: &Rule| w.push((r.id.clone(), "a render (raea render EDIT.tsx)".into()));
if let Some(r) = rendered.as_ref().filter(|r| r["stale"] == true) {
found.push(Finding::new("render", Level::Note, "the newest render is older than the composition's last change: what it measured may have moved", "raea check").about(r["out"].as_str().unwrap_or("").to_string(), None));
}
// raea's named checks: the text forms over every frame; the floor (and the loudness and stillness it measures) on the render
// the forms the floor measures on the video (each its form, value and line), and where each was written
let (mut held, mut bys) = (Vec::new(), Vec::new());
let mut floor = false;
for (r, h) in &hows {
let How::Named(n) = h else { continue };
match n.name {
"floor" => floor = true,
"loudness" | "still-max" => {
held.push((n.name, r.number("value").unwrap_or(if n.name == "loudness" { -14.0 } else { 3.0 }), r.text.clone()));
bys.push(r.by.clone());
}
"text-read" if rendered.is_none() => needs(&mut waits, r),
"text-read" => found.extend(crate::read::read(r, &worlds)),
_ => found.extend(systems::text(r, &worlds)),
}
}
if floor || !held.is_empty() {
match &rendered {
Some(r) if is_video(r["out"].as_str().unwrap_or("")) => {
let a = [r["out"].as_str().unwrap_or("").to_string(), "--manifest".into(), r["manifest"].as_str().unwrap_or("").to_string()];
// where text-read runs, the floor's own reading rule (held against when a text is on) is its
let without: &[&str] = if hows.iter().any(|(_, h)| matches!(h, How::Named(n) if n.name == "text-read")) { &["reading"] } else { &[] };
for mut f in raea_app_check::floor(&a, &held, without)? {
match held.iter().position(|h| h.0 == f.check) {
Some(k) => f.by = bys[k].clone(),
None if !floor => continue,
None => f.by = "raea".into(),
}
found.push(f);
}
}
Some(_) => waits.extend(hows.iter().filter(|(_, h)| matches!(h, How::Named(n) if n.render && n.name != "text-read")).map(|(r, _)| (r.id.clone(), "a video render (its render is stills)".to_string()))),
None => hows.iter().filter(|(_, h)| matches!(h, How::Named(n) if n.render && n.name != "text-read")).for_each(|(r, _)| needs(&mut waits, r)),
}
}
// the project's own checks, in one run
let mut files: Vec<PathBuf> = Vec::new();
let mut plan = Vec::new();
for (r, h) in &hows {
let How::File(m) = h else { continue };
if m.render && rendered.is_none() {
needs(&mut waits, r);
continue;
}
let k = files.iter().position(|f| *f == m.file).unwrap_or_else(|| {
files.push(m.file.clone());
files.len() - 1
});
let mut on = m.frames.pick(&worlds);
if let (true, Some(j)) = (m.render, &join_on_of(&worlds)) {
on.retain(|f| j.contains(f));
}
plan.push(ts::Planned { check: k, frames: on, values: r.values.clone(), level: r.level, by: r.by.clone() });
}
found.extend(ts::run(&files, &plan, &worlds, &host.ts)?);
let render = rendered.map(|r| {
// how many frames it drew, as its manifest lists them
let m: Value = std::fs::read(r["manifest"].as_str().unwrap_or("")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
raea_app_notes::check::Rendered { out: PathBuf::from(r["out"].as_str().unwrap_or("")), stale: r["stale"] == true, frames: m["frames"].as_array().map_or(0, |f| f.len() as i64) }
});
let mut shots: Vec<(String, i64, Option<i64>)> = worlds.iter().flat_map(|w| w.find(&["Shot"]).into_iter().filter_map(|e| w.get::<Shot>(e.id)).filter_map(|s| Some((s.name?, s.from, s.to)))).collect();
shots.sort();
shots.dedup();
let fps = worlds.first().map_or(30.0, |w| w.fps);
Ok(Checked { file: tsx.to_path_buf(), id, found: finding::ranked(found), waits, render, shots, fps })
}
/// Whether `r` runs on the composition `tsx` (`id` where its file registers several) of `project`: a rule a note's ask
/// scopes to one (`of`) runs there alone.
fn applies(r: &Rule, project: &Path, tsx: &Path, id: Option<&str>) -> bool {
r.of.as_ref().is_none_or(|of| raea_app_notes::check::is_of(of, &named_as(project, tsx, id)))
}
/// A composition as a note's ask names it: its file from the project, `#ID` after it where the file registers several.
fn named_as(project: &Path, tsx: &Path, id: Option<&str>) -> String {
format!("{}{}", record::rel(project, tsx), id.map(|i| format!("#{i}")).unwrap_or_default())
}
/// `rules` run on `project`'s compositions (`--composition` picks one), each where it applies, as `raea check` runs
/// its own: what `raea notes check` runs a project's asks through (DR6).
pub fn run(project: &Path, rules: &[Rule], args: &[String], whole: bool, host: &Host) -> R<Vec<raea_app_notes::check::Ran>> {
let mut out = Vec::new();
for (tsx, id) in compositions(project, args)? {
let mine: Vec<Rule> = rules.iter().filter(|r| applies(r, project, &tsx, id.as_deref())).cloned().collect();
let c = check_one(&tsx, id, &mine, args, whole, host)?;
out.push(raea_app_notes::check::Ran { of: named_as(project, &c.file, c.id.as_deref()), found: c.found, waits: c.waits, render: c.render, shots: c.shots, fps: c.fps });
}
Ok(out)
}
/// The frames the render joined (each with what it rendered, or says it waits), or None when it joined none.
fn join_on_of(worlds: &[Facts]) -> Option<Vec<i64>> {
let on: Vec<i64> = worlds.iter().filter(|w| w.resources.contains_key("Rendered")).map(|w| w.frame).collect();
(!on.is_empty()).then_some(on)
}
/// Whether `raea check`'s arguments name a file that isn't a composition (a video, a still: the floor alone, apps/check)
/// rather than a project, a folder or an EDIT.tsx.
pub fn of_video(args: &[String]) -> bool {
raea_app_check::words(args, &TAKES).first().is_some_and(|a| !a.ends_with(".tsx") && !Path::new(a).is_dir())
}
fn is_video(out: &str) -> bool {
Path::new(out).extension().and_then(|x| x.to_str()).is_some_and(|x| matches!(x.to_ascii_lowercase().as_str(), "mp4" | "mov"))
}
/// `raea check PROJECT|EDIT.tsx ...`: the report, and whether an error is among what it found.
pub fn check(args: &[String], host: &Host) -> R<(String, bool)> {
let target = raea_app_check::words(args, &TAKES).first().map_or_else(|| PathBuf::from("."), PathBuf::from);
// the folder it is in, made whole (`lyric.tsx`'s is the empty path): a rule's check is a path from it
let here = if target.is_dir() { target.clone() } else { target.parent().filter(|p| !p.as_os_str().is_empty()).map_or_else(|| PathBuf::from("."), Path::to_path_buf) };
let here = here.canonicalize().map_err(|e| format!("{}: {e}", here.display()))?;
let project = record::up(&here, ".raea/project").unwrap_or(here);
let (mut rules, unread, notes) = rules(&project, taste_files(args), host);
if let Some(only) = flag(args, "--only") {
rules.retain(|r| r.id == only);
if rules.is_empty() {
return Err(format!("--only {only}: no rule here has that id"));
}
}
let mut all = Vec::new();
for (tsx, id) in compositions(&target, args)? {
let mine: Vec<Rule> = rules.iter().filter(|r| applies(r, &project, &tsx, id.as_deref())).cloned().collect();
all.push(check_one(&tsx, id, &mine, args, false, host)?);
}
let stamp = raea_io_trace::utc(std::time::SystemTime::now()).1;
// what the notes' asks found, kept with what each has been through (DR6): an ask's first run that passes is refused
let ran: Vec<raea_app_notes::check::Ran> = all.iter().map(|c| raea_app_notes::check::Ran { of: named_as(&project, &c.file, c.id.as_deref()), found: c.found.clone(), waits: c.waits.clone(), render: None, shots: Vec::new(), fps: c.fps }).collect();
let mut kept = raea_app_notes::state::read(&project);
let (asks, _) = raea_app_notes::check::settle(&project, &notes, &rules, &ran, &stamp, &mut kept);
if !asks.is_empty() {
raea_app_notes::state::write(&project, &kept)?;
}
let mut bad = unread.iter().any(|f| f.level == Level::Error);
if args.iter().any(|a| a == "--json") {
let v: Vec<Value> = all.iter().map(|c| json!({"file": c.file, "composition": c.id, "findings": c.found, "waits": c.waits.iter().map(|(r, w)| json!({"rule": r, "for": w})).collect::<Vec<_>>()})).collect();
bad |= all.iter().any(|c| c.found.iter().any(|f| f.level == Level::Error));
return Ok((serde_json::to_string_pretty(&json!({"unread": unread, "compositions": v, "asks": asks})).unwrap_or_default(), bad));
}
let mut out: Vec<String> = unread.iter().map(Finding::line).collect();
let mut every = unread.clone();
for c in &all {
out.push(format!("raea check {}{}", c.file.display(), c.id.as_ref().map(|i| format!(" ({i})")).unwrap_or_default()));
// a note's ask's finding says which ask, as two asks can run one check
out.extend(c.found.iter().map(|f| if f.by.starts_with("note ") { format!("{} [{}]", f.line(), f.by) } else { f.line() }));
out.extend(c.waits.iter().map(|(r, w)| format!("waits {r}: needs {w}")));
// kept in its project's record (DR3), what raea findings and raea next read
if let Some(e) = record::keep("raea check", &c.file, None, &c.found, vec![], &stamp) {
out.push(format!("raea check: kept in the project's record as {} (raea findings reads it)", e.id));
}
bad |= c.found.iter().any(|f| f.level == Level::Error);
every.extend(c.found.iter().cloned());
}
out.extend(asks.iter().map(|a| format!("raea check: note {a}")));
out.push(format!("raea check: {}", finding::count(&every)));
Ok((out.join("\n"), bad))
}
/// `raea check ...`: its exit code (1 on an error found, 2 when it couldn't check).
pub fn cli(args: &[String], host: &Host) -> i32 {
raea_app_check::said(check(args, host), "raea check: ")
}
+155
View File
@@ -0,0 +1,155 @@
//! `raea findings` (docs/direction.feature DR3): what renders and checks found, read from the project's record
//! (core/facts record.rs). For each thing rendered or checked, its latest entry against the one before (or the one
//! `--since` names): what was fixed, what is new and what is carried, and since which render.
use std::path::{Path, PathBuf};
use raea_core_facts::record::{self, Entry};
use raea_core_facts::{Finding, finding};
use raea_runtime_bundle::flag;
use serde_json::{Value, json};
pub const USAGE: &str = "raea findings [PROJECT|EDIT.tsx] [--about NAME] [--check ID] [--open] [--since RENDER] [--json] (what each render and raea check found, from the project's record: fixed, new and carried since the one before, or since RENDER; --open: only what stands)";
/// The oldest entry of the unbroken run up to the latest that all found `f`.
fn carried_since(entries: &[&Entry], f: &Finding) -> String {
let key = record::same(f);
let run = entries.iter().rev().take_while(|e| e.findings.iter().any(|g| record::same(g) == key));
run.last().map(|e| e.id.clone()).unwrap_or_default()
}
/// One thing's latest entry against the one before it (or `since`), each list filtered by `keep`.
fn compare(entries: &[&Entry], since: Option<&str>, keep: &dyn Fn(&Finding) -> bool, open: bool) -> Option<Value> {
let (now, earlier) = entries.split_last()?;
let before = match since {
Some(id) => earlier.iter().rev().find(|e| e.id.starts_with(id)),
None => earlier.last(),
};
let none = Vec::new();
let ch = record::changes(before.map_or(&none, |b| &b.findings), &now.findings);
let list = |fs: Vec<&Finding>| fs.into_iter().filter(|f| keep(f)).cloned().collect::<Vec<Finding>>();
let carried: Vec<Value> = list(ch.carried).into_iter().map(|f| json!({"since": carried_since(entries, &f), "finding": f})).collect();
let renamed: Vec<Value> = ch.renamed.into_iter().filter(|(_, n)| keep(n)).map(|(was, f)| json!({"was": was.about.iter().map(|a| &a.name).collect::<Vec<_>>(), "finding": f})).collect();
let fixed = if open { Vec::new() } else { list(ch.fixed) };
Some(json!({"of": now.of, "kind": now.kind, "id": now.id, "by": now.by, "commit": now.commit, "out": now.out, "against": before.map(|b| &b.id),
"new": list(ch.new), "carried": carried, "renamed": renamed, "fixed": fixed, "despite": now.despite}))
}
/// One thing's lines: its entry, then what is new, carried and fixed.
fn lines(r: &Value) -> Vec<String> {
let read = Finding::read;
let mut t = vec![format!(
"{} {} ({} {}{}, against {})",
r["of"].as_str().unwrap_or(""),
r["kind"].as_str().filter(|k| !k.is_empty()).unwrap_or("run"),
r["by"].as_str().unwrap_or(""),
r["id"].as_str().unwrap_or(""),
r["commit"].as_str().map(|c| format!(" at {c}")).unwrap_or_default(),
r["against"].as_str().unwrap_or("nothing: its first")
)];
t.extend(r["new"].as_array().into_iter().flatten().filter_map(read).map(|f| format!(" new {}", f.line())));
for c in r["carried"].as_array().into_iter().flatten() {
if let Some(f) = read(&c["finding"]) {
t.push(format!(" carried {} (since {})", f.line(), c["since"].as_str().unwrap_or("")));
}
}
for c in r["renamed"].as_array().into_iter().flatten() {
if let Some(f) = read(&c["finding"]) {
let was: Vec<&str> = c["was"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
t.push(format!(" renamed {} (the same, about {} before: not fixed)", f.line(), was.join(", ")));
}
}
t.extend(r["fixed"].as_array().into_iter().flatten().filter_map(read).map(|f| format!(" fixed {}", f.line())));
// what was let through, and why: the error stands in the count all the same
for d in r["despite"].as_array().into_iter().flatten() {
t.push(format!(" despite {}: {}", d["check"].as_str().unwrap_or(""), d["why"].as_str().unwrap_or("")));
}
t
}
/// What stands across the reports: each one's new and carried.
fn standing(reports: &[Value]) -> Vec<Finding> {
let mut out = Vec::new();
for r in reports {
out.extend(r["new"].as_array().into_iter().flatten().filter_map(Finding::read));
out.extend(["carried", "renamed"].iter().flat_map(|k| r[*k].as_array().into_iter().flatten()).filter_map(|c| Finding::read(&c["finding"])));
}
out
}
/// `raea findings ...` (args from "findings").
pub fn cli(args: &[String]) -> Result<String, String> {
if args.iter().any(|a| a == "--help" || a == "-h") {
return Ok(USAGE.into());
}
let target = args.get(1).filter(|a| !a.starts_with("--")).map_or_else(|| PathBuf::from("."), PathBuf::from);
// made absolute first: a bare name's parent is "", which names no folder
let from = if target.is_file() { target.canonicalize().unwrap_or_else(|_| target.clone()).parent().map_or_else(|| PathBuf::from("."), Path::to_path_buf) } else { target.clone() };
let project = record::up(&from, ".raea/project").ok_or_else(|| format!("raea findings: {} isn't in a raea project (no .raea/project at or above it), so nothing is recorded\n{USAGE}", target.display()))?;
let (about, check, since) = (flag(args, "--about"), flag(args, "--check"), flag(args, "--since"));
let keep = |f: &Finding| about.as_deref().is_none_or(|n| f.about.iter().any(|a| a.name == n || a.key.as_deref() == Some(n))) && check.as_deref().is_none_or(|c| f.check == c);
let all = record::read(&project);
let only = target.is_file().then(|| record::rel(&project, &target));
// each thing by what kind of output it was (a video against the video before it, a review against a review)
let mut ofs: Vec<(&str, &str)> = all.iter().filter(|e| only.as_deref().is_none_or(|w| w == e.of)).map(|e| (&*e.of, &*e.kind)).collect();
ofs.sort();
ofs.dedup();
let open = args.iter().any(|a| a == "--open");
let reports: Vec<Value> = ofs.iter().filter_map(|(of, kind)| compare(&all.iter().filter(|e| e.of == *of && e.kind == *kind).collect::<Vec<_>>(), since.as_deref(), &keep, open)).collect();
let count = finding::count(&standing(&reports));
if args.iter().any(|a| a == "--json") {
return Ok(serde_json::to_string_pretty(&json!({"project": project, "entries": all.len(), "reports": reports, "standing": count})).unwrap_or_default());
}
let mut t = vec![format!("raea findings: {} ({} entries in .raea/record)", project.display(), all.len())];
if reports.is_empty() {
t.push(" nothing recorded yet: a render or raea check of a file in this project keeps what it found".into());
}
t.extend(reports.iter().flat_map(lines));
t.push(format!("raea findings: {count} standing"));
Ok(t.join("\n"))
}
#[cfg(test)]
mod tests {
use super::*;
use raea_core_facts::Level;
fn entry(id: &str, fs: Vec<Finding>) -> Entry {
Entry { id: id.into(), at: 0, by: "raea render".into(), of: "edit.tsx".into(), out: None, kind: "video".into(), commit: None, findings: fs, despite: vec![] }
}
#[test]
fn the_latest_render_against_the_one_before_says_fixed_new_and_carried_since_when() {
let clips = Finding::new("clips", Level::Error, "rider in seat", "raea render").about("rider", None);
let tilt = Finding::new("tilted", Level::Warn, "vase leans", "raea render").about("vase", None);
let float = Finding::new("floats", Level::Error, "lamp floats", "raea render").about("lamp", None);
let es = [entry("a", vec![clips.clone(), tilt.clone()]), entry("b", vec![clips.clone(), tilt]), entry("c", vec![clips, float])];
let refs: Vec<&Entry> = es.iter().collect();
let all = |_: &Finding| true;
let r = compare(&refs, None, &all, false).unwrap();
assert_eq!((r["against"].as_str(), r["new"][0]["check"].as_str(), r["fixed"][0]["check"].as_str()), (Some("b"), Some("floats"), Some("tilted")));
assert_eq!((r["carried"][0]["finding"]["check"].as_str(), r["carried"][0]["since"].as_str()), (Some("clips"), Some("a")));
// against a named render, and only what stands
let r = compare(&refs, Some("a"), &all, true).unwrap();
assert_eq!((r["against"].as_str(), r["fixed"].as_array().map(Vec::len)), (Some("a"), Some(0)));
assert_eq!(finding::count(&standing(&[r])), "2 errors, 0 warns, 0 notes");
let lamp = |f: &Finding| f.about.iter().any(|a| a.name == "lamp");
assert_eq!(compare(&refs, None, &lamp, false).unwrap()["carried"].as_array().map(Vec::len), Some(0));
}
#[test]
fn a_renamed_part_or_an_error_let_through_is_never_read_as_fixed() {
let crate_ = Finding::new("clips", Level::Error, "crate in pillar", "raea render").about("crate", None).about("pillar", None).frames(0, 30).measure("depth", 0.241, "m", None);
let mut boxed = crate_.clone();
boxed.about[0].name = "box".into();
boxed.says = "box in pillar".into();
let mut let_through = entry("b", vec![boxed]);
let_through.despite = vec![record::Despite { check: "clips".into(), why: "posed through it".into() }];
let es = [entry("a", vec![crate_]), let_through];
let r = compare(&es.iter().collect::<Vec<_>>(), None, &|_: &Finding| true, false).unwrap();
assert_eq!((r["fixed"].as_array().map(Vec::len), r["new"].as_array().map(Vec::len), r["renamed"][0]["was"][0].as_str()), (Some(0), Some(0), Some("crate")));
let text = lines(&r).join("\n");
assert!(text.contains(" renamed error clips frames 0-29 box, pillar") && text.contains(" despite clips: posed through it"), "{text}");
assert_eq!(finding::count(&standing(&[r])), "1 error, 0 warns, 0 notes");
}
}
+19
View File
@@ -0,0 +1,19 @@
//! How raea takes direction (docs/direction.feature). `raea world` (world.rs): a composition's frame as one world of
//! facts, its 3D, page and timeline as entities with components, printed or queried across media.
mod world;
pub use world::{cli, find, Find, USAGE};
// how `raea render` ends: its findings counted last, and 1 on an error not let through (DR3)
mod rendered;
pub use rendered::rendered;
// `raea findings`: the project's record read back, fixed, new and carried (DR3)
pub mod findings;
// `raea check PROJECT | EDIT.tsx`: every rule's check, raea's named ones and a project's TS ones, over the worlds (DR4)
pub mod check;
pub mod systems;
pub mod ts;
// text-read: each text's reading time held to when it can be read, and what OCR reads of it (DR28)
pub mod read;
+243
View File
@@ -0,0 +1,243 @@
//! `text-read`, raea's reading check (docs/direction.feature DR28). Each text on screen is given three times: the
//! frames it is in the world (`on`), the frames it can be read on (`visible`: in the frame, at an opacity, size and
//! contrast against what is behind it that can be read, and covered by no other layer past a share), and the frames
//! OCR reads its words on (`read`, the render's Ocr). Its reading time is held against `visible`, not `on`: a text
//! faded in over half its time, or behind a part for some of it, has less time to be read than it is up, and the
//! finding says which frames were lost and why. A text that can be read where OCR doesn't read it is broken. raea
//! check runs it on every composition's newest render with no rule asking for it, as raea's own, beside the floor.
use std::collections::BTreeMap;
use raea_core_facts::{Contrast, Covers, Facts, Finding, Layer, Level, Line, Ocr, Rule, Text, word_key as norm};
use crate::systems::{ident, quote};
/// Frames OCR may miss inside what it reads before that's a fault (a word dropped for a frame or two, as textread's
/// GAP allows).
const GAP: usize = 3;
/// What the check holds a text to, each a value its rule may change: seconds a word (`word`) and at least (`least`),
/// as the floor's reading rule; the least opacity, letter height (px at 1080 on the short side) and contrast that can
/// be read; the most of it another layer may cover; the share of its words OCR must read.
struct Limits {
word: f64,
least: f64,
opacity: f64,
size: f64,
contrast: f64,
covered: f64,
share: f64,
}
impl Limits {
fn of(rule: &Rule) -> Limits {
let v = |n: &str, d: f64| rule.number(n).unwrap_or(d);
Limits { word: v("word", 0.3), least: v("least", 1.0), opacity: v("opacity", 0.5), size: v("size", 24.0), contrast: v("contrast", 3.0), covered: v("covered", 0.5), share: v("share", 0.5) }
}
}
/// One frame a text is on: why it can't be read there (None: it can), whether OCR read it (None: OCR didn't run),
/// and what OCR read.
struct Seen {
frame: i64,
lost: Option<String>,
read: Option<bool>,
ocr: String,
}
/// A text across the frames: its words, its layer key, the largest it's set, and each frame it's on.
struct Track {
words: String,
key: Option<String>,
size: f64,
seen: Vec<Seen>,
}
/// An entity's opacity: its own layer's, else its nearest parent's.
fn opacity(w: &Facts, mut e: u32) -> f64 {
loop {
if let Some(l) = w.get::<Layer>(e) {
return l.opacity;
}
match w.entities.get(e as usize).and_then(|x| x.parent) {
Some(p) => e = p,
None => return 1.0,
}
}
}
/// Why a text can't be read on this frame (`covered`: the most of it one layer covers), or None.
fn lost(w: &Facts, e: u32, t: &Text, l: &Limits, covered: f64) -> Option<String> {
if let Some(b) = t.box_ {
let inside = |a: f64, z: f64| (z.min(1.0) - a.max(0.0)).max(0.0);
let area = ((b[2] - b[0]) * (b[3] - b[1])).max(1e-9);
if inside(b[0], b[2]) * inside(b[1], b[3]) / area < 0.9 {
return Some("partly off the frame".into());
}
}
let o = opacity(w, e);
if o < l.opacity {
return Some(format!("at {:.0}% opacity", o * 100.0));
}
if let Some(s) = t.size.filter(|s| *s < l.size) {
return Some(format!("{s:.0} px high"));
}
// covered before contrast: what covers it is what its pixels then measure against
if covered > l.covered {
return Some(format!("{:.0}% covered", covered * 100.0));
}
w.get::<Contrast>(e).filter(|c| c.ratio < l.contrast).map(|c| format!("{:.1}:1 against what's behind it", c.ratio))
}
/// The words said or sung over the piece, each with its start in seconds.
fn said(worlds: &[Facts]) -> Vec<(String, f64)> {
let Some(w) = worlds.iter().find(|w| !w.find(&["Line"]).is_empty()) else { return Vec::new() };
w.find(&["Line"]).iter().filter_map(|e| w.get::<Line>(e.id)).flat_map(|l| l.words).map(|x| (norm(&x.text), x.start)).collect()
}
/// Runs of frames one after another in `frames` (sorted), each [first, the frame after its last).
fn runs(frames: impl IntoIterator<Item = i64>) -> Vec<[i64; 2]> {
let mut out: Vec<[i64; 2]> = Vec::new();
for f in frames {
match out.last_mut() {
Some(r) if r[1] == f => r[1] = f + 1,
_ => out.push([f, f + 1]),
}
}
out
}
/// Runs closer than `gap` frames to the one before, joined.
fn joined(runs: Vec<[i64; 2]>, gap: i64) -> Vec<[i64; 2]> {
let mut out: Vec<[i64; 2]> = Vec::new();
for r in runs {
match out.last_mut() {
Some(p) if r[0] - p[1] < gap => p[1] = r[1],
_ => out.push(r),
}
}
out
}
/// A number of frames as a person reads it: "2 frames" under a tenth of a second, else seconds.
fn span(frames: i64, fps: f64) -> String {
match frames {
1 => "1 frame".into(),
n if (n as f64) < 0.1 * fps => format!("{n} frames"),
n => format!("{:.1} s", n as f64 / fps),
}
}
/// "frames 10-22 at 20% opacity; frames 30-41 60% covered": the frames of [from, to) lost, grouped by why (three
/// groups at most); a frame it isn't drawn on is "not shown".
fn why_lost(from: i64, to: i64, seen: &[&Seen]) -> String {
let mut groups: Vec<([i64; 2], &str)> = Vec::new();
for f in from..to {
let why = match seen.iter().find(|s| s.frame == f) {
Some(s) => match s.lost.as_deref() {
Some(w) => w,
None => continue,
},
None => "not shown",
};
match groups.last_mut() {
Some((r, w)) if r[1] == f && *w == why => r[1] = f + 1,
_ => groups.push(([f, f + 1], why)),
}
}
let shown: Vec<String> = groups.iter().take(3).map(|([a, b], w)| if b - a == 1 { format!("frame {a} {w}") } else { format!("frames {a}-{} {w}", b - 1) }).collect();
let more = groups.len().saturating_sub(3);
format!("{}{}", shown.join("; "), if more > 0 { format!("; and {more} more") } else { String::new() })
}
/// The check's findings over `worlds` (every frame of the composition, in order, with its render joined).
pub fn read(rule: &Rule, worlds: &[Facts]) -> Vec<Finding> {
let l = Limits::of(rule);
let Some(fps) = worlds.first().map(|w| w.fps) else { return Vec::new() };
let lvl = |d: Level| rule.level.unwrap_or(d);
let mut tracks: BTreeMap<String, Track> = BTreeMap::new();
// what wasn't measured, and what it waits for
let mut waits: BTreeMap<String, String> = BTreeMap::new();
for w in worlds {
for c in ["Ocr", "Covers"] {
if let Some(why) = w.resources.get("Waits").and_then(|v| v.get(c)).and_then(|v| v.as_str()) {
waits.entry(c.to_string()).or_insert_with(|| why.to_string());
}
}
// the most of each layer one other layer covers
let mut covered: BTreeMap<u32, f64> = BTreeMap::new();
for e in w.find(&["Covers"]) {
for c in w.get::<Covers>(e.id).map(|c| c.0).unwrap_or_default() {
let s = covered.entry(c.layer).or_default();
*s = s.max(c.share);
}
}
for e in w.find(&["Text"]) {
let Some(t) = w.get::<Text>(e.id) else { continue };
let (id, key) = ident(w, e.id, &t);
let lost = lost(w, e.id, &t, &l, covered.get(&e.id).copied().unwrap_or(0.0));
let ocr = w.get::<Ocr>(e.id);
let tr = tracks.entry(id).or_insert_with(|| Track { words: t.words.clone(), key, size: 0.0, seen: Vec::new() });
// a text laid out with no size known is held as a caption
tr.size = tr.size.max(t.size.unwrap_or(f64::INFINITY));
tr.seen.push(Seen { frame: w.frame, lost, read: ocr.as_ref().map(|o| o.share >= l.share), ocr: ocr.map(|o| o.words).unwrap_or_default() });
}
}
let said = said(worlds);
let mut out = Vec::new();
// a text that leaves and comes back within half a second is one text that blinks, not two
let blink = (0.5 * fps).round() as i64;
for tr in tracks.values().filter(|t| t.size >= l.size) {
for [from, to] in joined(runs(tr.seen.iter().map(|s| s.frame)), blink) {
let seen: Vec<&Seen> = tr.seen.iter().filter(|s| (from..to).contains(&s.frame)).collect();
let at = |f: Finding| f.about(tr.words.clone(), tr.key.clone());
let q = quote(&tr.words);
// the time it needs to be read, against the time it can be: a caption the voice says as it shows needs none
let n = tr.words.split_whitespace().count();
let need = (l.word * n as f64).max(l.least);
let can_frames = seen.iter().filter(|s| s.lost.is_none()).count() as i64;
let can = can_frames as f64 / fps;
let (a, b) = (from as f64 / fps, to as f64 / fps);
let tokens: Vec<String> = tr.words.split_whitespace().map(norm).filter(|t| !t.is_empty()).collect();
let spoken = !tokens.is_empty() && tokens.iter().all(|t| said.iter().any(|(w, s)| w == t && *s >= a - 0.3 && *s <= b + 0.1));
if can + 0.05 < need && !spoken {
let says = if can_frames == 0 {
format!("{q} is up {} but can't be read on any frame of it ({}); {n} words need {need:.1} s", span(to - from, fps), why_lost(from, to, &seen))
} else if can_frames < to - from {
format!("{q} is up {} but can be read for {} ({}); {n} words need {need:.1} s", span(to - from, fps), span(can_frames, fps), why_lost(from, to, &seen))
} else {
format!("{q} is on for {}; {n} words need {need:.1} s", span(to - from, fps))
};
out.push(at(Finding::new(&rule.id, lvl(Level::Warn), says, &rule.by)).frames(from, to).measure("readable", (can * 10.0).round() / 10.0, "s", Some((need * 10.0).round() / 10.0)));
}
// what can be read and OCR doesn't read is broken; a word with fewer than two letters or digits isn't held
if norm(&tr.words).chars().count() < 2 {
continue;
}
let judged: Vec<&&Seen> = seen.iter().filter(|s| s.lost.is_none() && s.read.is_some()).collect();
let unread: Vec<[i64; 2]> = runs(judged.iter().filter(|s| s.read == Some(false)).map(|s| s.frame)).into_iter().filter(|[a, b]| (b - a) as usize > GAP).collect();
for [ua, ub] in &unread {
let got = judged.iter().find(|s| s.frame == *ua).map_or("", |s| s.ocr.as_str());
let heard = if got.trim().is_empty() { "OCR reads nothing in its box".to_string() } else { format!("OCR reads {} in its box", quote(got)) };
let says = format!("{q} can be read on frames {ua}-{} and OCR doesn't read it there ({heard}): it's broken", ub - 1);
out.push(at(Finding::new(&rule.id, lvl(Level::Error), says, &rule.by)).frames(*ua, *ub).fix("set it so it reads: a face, weight, size or treatment OCR reads, and nothing drawn through it"));
}
let read = judged.iter().filter(|s| s.read == Some(true)).count();
if unread.is_empty() && !judged.is_empty() && read * 2 < judged.len() {
let says = format!("{q} is read by OCR on {read} of the {} frames it can be read on", judged.len());
out.push(at(Finding::new(&rule.id, lvl(Level::Warn), says, &rule.by)).frames(from, to).measure("read", read as f64, "frames", Some(judged.len() as f64 / 2.0)));
}
}
}
// what it didn't see, said
if let Some(why) = waits.get("Ocr") {
out.push(Finding::new(&rule.id, Level::Note, format!("no text was held to what OCR reads: OCR waits for {why}"), &rule.by));
}
if let Some(why) = waits.get("Covers") {
out.push(Finding::new(&rule.id, Level::Note, format!("what covers each text wasn't counted: it waits for {why}"), &rule.by));
}
out
}
#[cfg(test)]
mod tests;
+98
View File
@@ -0,0 +1,98 @@
use super::*;
use raea_core_facts::{Medium, Waits, Word};
/// A caption of `words` on 60 frames at 30 fps: frame f at `opacity(f)`, read by OCR at `share(f)` (None: OCR
/// didn't run), 40 px high in the middle of the frame, 7:1 against its ground.
fn caption(words: &str, opacity: impl Fn(i64) -> f64, share: impl Fn(i64) -> Option<f64>) -> Vec<Facts> {
(0..60)
.map(|f| {
let mut w = Facts::new(f, 1080, 1920, 30.0);
let e = w.spawn(None);
w.put(e, &Text { words: words.into(), font: None, size: Some(40.0), box_: Some([0.1, 0.45, 0.9, 0.5]), extruded: 0.0, lines: Some(1), needs: None });
w.put(e, &Layer { medium: Medium::Type2d, order: 1, opacity: opacity(f), blend: None });
w.put(e, &Contrast { ratio: 7.0 });
match share(f) {
Some(s) => w.put(e, &Ocr { words: if s > 0.0 { words.into() } else { String::new() }, share: s }),
None => w.set(&Waits([("Ocr".to_string(), "OCR (on the Mac)".to_string())].into())),
}
w
})
.collect()
}
fn rule() -> Rule {
Rule { level: None, ..Rule::named("text-read", "", Default::default(), Level::Warn, "raea") }
}
#[test]
fn a_caption_up_long_enough_that_ocr_reads_holds() {
assert!(read(&rule(), &caption("Fresh bread every morning", |_| 1.0, |_| Some(1.0))).is_empty());
// OCR dropping it for a frame or two isn't a fault
let found = read(&rule(), &caption("Fresh bread every morning", |_| 1.0, |f| Some(if f == 20 || f == 21 { 0.0 } else { 1.0 })));
assert!(found.is_empty(), "{found:?}");
}
#[test]
fn reading_time_is_held_to_the_frames_it_can_be_read_on() {
// up 2 s, but under half opacity for its first 40 frames: 0.7 s to read seven words
let found = read(&rule(), &caption("one two three four five six seven", |f| if f < 40 { 0.2 } else { 1.0 }, |_| Some(1.0)));
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!((found[0].level, found[0].frames), (Level::Warn, Some([0, 60])));
assert!(found[0].says.contains("is up 2.0 s but can be read for 0.7 s (frames 0-39 at 20% opacity); 7 words need 2.1 s"), "{}", found[0].says);
// the frames it couldn't be read on aren't held to OCR
let found = read(&rule(), &caption("one two three four five six seven", |f| if f < 40 { 0.2 } else { 1.0 }, |f| Some(if f < 40 { 0.0 } else { 1.0 })));
assert_eq!(found.len(), 1, "{found:?}");
}
#[test]
fn a_caption_said_as_it_shows_needs_no_reading_time() {
let mut worlds = caption("one two three four five six seven", |f| if f < 40 { 0.2 } else { 1.0 }, |_| Some(1.0));
for w in &mut worlds {
let l = w.spawn(None);
let words = "one two three four five six seven".split(' ').enumerate().map(|(i, t)| Word { text: t.into(), start: 0.2 * i as f64, end: 0.2 * i as f64 + 0.15 }).collect();
w.put(l, &Line { text: "one two three four five six seven".into(), from: 0.0, to: Some(2.0), words, needs: None });
}
assert!(read(&rule(), &worlds).is_empty());
}
#[test]
fn text_that_can_be_read_and_that_ocr_doesnt_read_is_broken() {
let found = read(&rule(), &caption("Fresh bread every morning", |_| 1.0, |_| Some(0.0)));
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!((found[0].level, found[0].frames), (Level::Error, Some([0, 60])));
assert!(found[0].says.contains("can be read on frames 0-59 and OCR doesn't read it there (OCR reads nothing in its box): it's broken"), "{}", found[0].says);
// read on a frame here and there, never long enough to be a broken run: a warn
let found = read(&rule(), &caption("Fresh bread every morning", |_| 1.0, |f| Some(if f % 3 == 0 { 1.0 } else { 0.0 })));
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(found[0].level, Level::Warn);
assert!(found[0].says.contains("is read by OCR on 20 of the 60 frames it can be read on"), "{}", found[0].says);
}
#[test]
fn what_it_did_not_measure_it_says() {
let found = read(&rule(), &caption("Fresh bread every morning", |_| 1.0, |_| None));
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(found[0].level, Level::Note);
assert!(found[0].says.contains("OCR waits for OCR (on the Mac)"), "{}", found[0].says);
}
#[test]
fn small_type_and_a_lone_mark_arent_held() {
let mut worlds = caption("x", |_| 1.0, |_| Some(0.0));
assert!(read(&rule(), &worlds).is_empty(), "one letter: nothing for OCR to read, and a second is enough");
for w in &mut worlds {
w.put(0, &Text { words: "a label in the corner".into(), font: None, size: Some(12.0), box_: Some([0.0, 0.0, 0.2, 0.02]), extruded: 0.0, lines: Some(1), needs: None });
}
assert!(read(&rule(), &worlds).is_empty(), "under 24 px: not a caption");
}
#[test]
fn a_text_that_blinks_is_one_text_up_the_whole_time() {
// drawn on one frame in ten: one finding over all of it, its frames off said as not shown
let worlds: Vec<Facts> = caption("Fresh bread every morning", |_| 1.0, |_| Some(1.0)).into_iter().map(|w| if w.frame % 10 == 0 { w } else { Facts::new(w.frame, 1080, 1920, 30.0) }).collect();
let found = read(&rule(), &worlds);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(found[0].frames, Some([0, 51]));
let says = "is up 1.7 s but can be read for 0.2 s (frames 1-9 not shown; frames 11-19 not shown; frames 21-29 not shown; and 2 more); 4 words need 1.2 s";
assert!(found[0].says.contains(says), "{}", found[0].says);
}
+86
View File
@@ -0,0 +1,86 @@
//! How `raea render` ends (docs/direction.feature DR3): what the render found, counted on the last line it prints
//! whatever its output is piped through, and its exit: 1 while an error stands that nothing lets through. An error is
//! let through by `--despite CHECK WHY` (a check's name, or `all`), or for a harness that renders many pieces and
//! compares pixels, not scenes, by RAEA_DESPITE="CHECK: why" (which a raea before this ignores, as it would refuse the
//! flag). What was let through, and why, is written into the render's manifest.
use std::path::PathBuf;
use std::time::SystemTime;
use raea_core_facts::record::{self, Despite};
use raea_core_facts::{Finding, Level, finding};
use serde_json::{Value, json};
/// Each `--despite CHECK WHY`, then RAEA_DESPITE's.
fn despite(args: &[String], env: Option<String>) -> Vec<(String, String)> {
let mut out: Vec<(String, String)> = args.windows(3).filter(|w| w[0] == "--despite").map(|w| (w[1].clone(), w[2].clone())).collect();
if let Some((check, why)) = env.as_deref().and_then(|e| e.split_once(':')) {
out.push((check.trim().to_string(), why.trim().to_string()));
}
out
}
/// The last line and the exit, for `found` with `through` letting errors past.
fn ending(found: &[Finding], through: &[(String, String)]) -> (String, i32) {
let excused = |f: &Finding| through.iter().any(|(c, _)| c == "all" || *c == f.check);
let errors = |past: bool| found.iter().filter(|f| f.level == Level::Error && excused(f) == past).count();
let mut line = format!("raea render: {}", finding::count(found));
if errors(true) > 0 {
let why: Vec<String> = through.iter().map(|(c, w)| format!("--despite {c} {w:?}")).collect();
line.push_str(&format!("; {} let through by {}", errors(true), why.join(", ")));
}
(line, i32::from(errors(false) > 0))
}
/// `raea render`'s exit, once its findings' count is printed; 0 for any other command. Its findings (the clipping
/// check's, its exposure's) go into its manifest, with what was let through and why, and into its project's record.
pub fn rendered(args: &[String]) -> i32 {
if args.first().map(String::as_str) != Some("render") {
return 0;
}
let found = finding::taken();
let through = despite(args, std::env::var("RAEA_DESPITE").ok());
let excused: Vec<Despite> = through.iter().map(|(c, w)| Despite { check: c.clone(), why: w.clone() }).collect();
let out = raea_runtime_bundle::flag(args, "-o").or_else(|| raea_runtime_bundle::flag(args, "--review")).map(PathBuf::from);
// the manifest every render writes beside its output (DR2), or where --manifest put it
let manifest = raea_runtime_bundle::flag(args, "--manifest").map(PathBuf::from).or_else(|| Some(raea_runtime_world::manifest_for(out.as_deref()?, std::path::Path::new(args.get(1)?))));
if let Some(m) = manifest {
if let Some(mut v) = std::fs::read(&m).ok().and_then(|b| serde_json::from_slice::<Value>(&b).ok()) {
v["findings"] = json!(found);
if !excused.is_empty() {
v["despite"] = json!(excused);
}
let _ = std::fs::write(&m, v.to_string());
}
}
// a render that is part of another (a review's tiles, a quick check's stills) leaves the entry to that one
let file = args.get(1).filter(|a| !a.starts_with('-') && std::env::var("RAEA_RECORD").as_deref() != Ok("off")).map(PathBuf::from);
if let Some(e) = file.and_then(|f| record::keep("raea render", &f, out.as_deref(), &found, excused, &raea_io_trace::utc(SystemTime::now()).1)) {
println!("raea render: kept in the project's record as {} (raea findings reads it)", e.id);
}
let (line, code) = ending(&found, &through);
println!("{line}");
code
}
#[cfg(test)]
mod tests {
use super::*;
fn s(v: &[&str]) -> Vec<String> {
v.iter().map(|a| a.to_string()).collect()
}
#[test]
fn an_error_fails_the_render_unless_it_is_let_through_and_says_by_what() {
let found = vec![Finding::new("clips", Level::Error, "rider in seat", "raea render"), Finding::new("tilted", Level::Warn, "vase leans", "raea render")];
assert_eq!(ending(&found, &[]), ("raea render: 1 error, 1 warn, 0 notes".into(), 1));
let through = despite(&s(&["render", "a.tsx", "--despite", "clips", "the rider is posed through it"]), None);
assert_eq!(ending(&found, &through), ("raea render: 1 error, 1 warn, 0 notes; 1 let through by --despite clips \"the rider is posed through it\"".into(), 0));
// another check's despite lets nothing through
assert_eq!(ending(&found, &despite(&s(&["render", "--despite", "floats", "x"]), None)).1, 1);
// a harness's
assert_eq!(ending(&found, &despite(&s(&["render"]), Some("all: P26 compares pixels".into()))).1, 0);
assert_eq!(ending(&[], &[]), ("raea render: 0 errors, 0 warns, 0 notes".into(), 0));
}
}
+179
View File
@@ -0,0 +1,179 @@
//! raea's own checks by name (docs/direction.feature DR4): each a system over a composition's worlds, held to its
//! rule's values, as a project's TS check is (sdk/raea/src/check.ts). Taste's six forms are six of them, with the same
//! names and values: the four text forms run over every frame's Text with no render; loudness and still-max are
//! measured on the newest render itself, in the floor's pass (`floor`: raea check's floor on that render).
use std::collections::BTreeMap;
use raea_core_facts::{Facts, Finding, Rule, Source, Text};
/// Where a check runs: every frame; the frame before each cut and the cut's first frame; every frame a line is
/// said or sung on; once, on the first frame; or these.
#[derive(Debug, Clone, PartialEq)]
pub enum Frames {
All,
Cuts,
Lines,
Once,
At(Vec<i64>),
}
impl Frames {
/// As a check file declares it ("all", "cuts", "lines", "once" or a list of frames).
pub fn of(v: &serde_json::Value) -> Result<Frames, String> {
match v {
serde_json::Value::Null => Ok(Frames::All),
serde_json::Value::String(s) => match s.as_str() {
"all" => Ok(Frames::All),
"cuts" => Ok(Frames::Cuts),
"lines" => Ok(Frames::Lines),
"once" => Ok(Frames::Once),
o => Err(format!("frames is \"all\", \"cuts\", \"lines\", \"once\" or a list of frames, not \"{o}\"")),
},
serde_json::Value::Array(a) => a.iter().map(|f| f.as_i64().ok_or("frames lists frame numbers")).collect::<Result<_, _>>().map(Frames::At).map_err(str::to_string),
o => Err(format!("frames is \"all\", \"cuts\", \"lines\", \"once\" or a list of frames, not {o}")),
}
}
/// Whether running here needs the frames of the whole piece read (cuts and lines are found in them).
pub fn whole(&self) -> bool {
matches!(self, Frames::All | Frames::Cuts | Frames::Lines)
}
/// The frames of `worlds` (every frame read, in order) it runs on.
pub fn pick(&self, worlds: &[Facts]) -> Vec<i64> {
let first = worlds.first().map_or(0, |w| w.frame);
match self {
Frames::All => worlds.iter().map(|w| w.frame).collect(),
Frames::Once => vec![first],
Frames::At(v) => v.clone(),
Frames::Lines => worlds.iter().filter(|w| !w.find(&["Line"]).is_empty()).map(|w| w.frame).collect(),
Frames::Cuts => {
let mut cuts: Vec<i64> = worlds.iter().flat_map(|w| w.find(&["Shot"]).into_iter().filter_map(|e| e.components["Shot"]["from"].as_i64())).filter(|f| *f > first).collect();
cuts.sort();
cuts.dedup();
cuts.into_iter().flat_map(|c| [c - 1, c]).collect()
}
}
}
}
/// One of raea's checks: its name, whether it needs a render, where it runs, and its line when no rule gives one.
#[derive(Debug, Clone)]
pub struct Named {
pub name: &'static str,
pub render: bool,
pub frames: Frames,
pub text: &'static str,
}
/// raea's named checks.
pub fn named() -> Vec<Named> {
let n = |name, render, frames, text| Named { name, render, frames, text };
vec![
n("text-hold", false, Frames::All, "text holds long enough to read"),
n("text-above", false, Frames::All, "text sits above a line down the frame"),
n("text-below", false, Frames::All, "text sits below a line down the frame"),
n("text-margin", false, Frames::All, "text keeps a margin from the frame's edges"),
n("loudness", true, Frames::Once, "the mix is at its loudness"),
n("still-max", true, Frames::Once, "the picture is never still for too long"),
n("floor", true, Frames::Once, "raea's floor: what every finished piece must meet"),
n("text-read", true, Frames::All, "text on screen can be read for as long as it needs, and OCR reads what can be read (read.rs)"),
]
}
/// A text's identity across frames: its layer key, else its words.
pub(crate) fn ident(f: &Facts, e: u32, t: &Text) -> (String, Option<String>) {
let key = f.get::<Source>(e).and_then(|s| s.key);
(key.clone().unwrap_or_else(|| t.words.clone()), key)
}
/// A run of frames on which one text measures past its rule: the text, its key, the frames (end exclusive) and the
/// worst measure in the run.
#[derive(Debug, Clone, PartialEq)]
pub struct Run {
pub words: String,
pub key: Option<String>,
pub from: i64,
pub to: i64,
pub value: f64,
}
/// Each text's runs of frames on which `bad` gives a measure, the worst of each run by `worse`.
fn runs(worlds: &[Facts], bad: impl Fn(&Facts, &Text) -> Option<f64>, worse: fn(f64, f64) -> bool) -> Vec<Run> {
let mut open: BTreeMap<String, Run> = BTreeMap::new();
let mut done = Vec::new();
for w in worlds {
for e in w.find(&["Text"]) {
let Some(t) = w.get::<Text>(e.id) else { continue };
let Some(v) = bad(w, &t) else { continue };
let (id, key) = ident(w, e.id, &t);
match open.get_mut(&id) {
Some(r) if r.to == w.frame => {
r.to = w.frame + 1;
if worse(v, r.value) {
r.value = v;
}
}
_ => {
if let Some(r) = open.insert(id, Run { words: t.words.clone(), key, from: w.frame, to: w.frame + 1, value: v }) {
done.push(r);
}
}
}
}
}
done.extend(open.into_values());
done.sort_by_key(|r| (r.from, r.words.clone()));
done
}
pub(crate) fn quote(s: &str) -> String {
let s: String = s.split_whitespace().collect::<Vec<_>>().join(" ");
if s.chars().count() > 40 { format!("\"{}…\"", s.chars().take(39).collect::<String>()) } else { format!("\"{s}\"") }
}
/// A text form's findings over `worlds` (every frame of the composition, in order), held to `rule`'s `value`.
pub fn text(rule: &Rule, worlds: &[Facts]) -> Vec<Finding> {
let level = rule.level.unwrap_or(raea_core_facts::Level::Error);
let Some(v) = rule.number("value") else {
return vec![Finding::new(&rule.id, level, format!("{} needs a value (values: {{ value: N }})", rule.check), &rule.by)];
};
let Some(first) = worlds.first() else { return Vec::new() };
let (w, h, fps) = (first.width as f64, first.height as f64, first.fps);
// the runs of text past the line across the frame at `v`%: by its edge `k` (1 its top, 3 its bottom), below the
// line (`down`) or above it
let past = |k: usize, down: bool| {
let worse: fn(f64, f64) -> bool = if down { |a, b| a > b } else { |a, b| a < b };
// a pixel past it, so text that only touches the line holds it
let line = v + (if down { 100.0 } else { -100.0 }) / h;
runs(worlds, move |_, t| t.box_.map(|b| b[k] * 100.0).filter(|y| worse(*y, line)), worse)
};
// the runs that break the form, each with its measure as its value; what's said of one ({n} its measure, {v} the
// rule's); and the unit
let (got, says, unit): (Vec<Run>, &str, &str) = match rule.check.as_str() {
"text-hold" => {
let on = runs(worlds, |_, _| Some(0.0), |_, _| false).into_iter().map(|r| Run { value: (r.to - r.from) as f64 / fps, ..r });
(on.filter(|r| r.value + 0.05 < v).collect(), "is on for {n} s, under {v} s", "s")
}
"text-above" => (past(3, true), "reaches {n}% down the frame, below {v}%", "%"),
"text-below" => (past(1, false), "starts {n}% down the frame, above {v}%", "%"),
"text-margin" => {
let s = w.min(h) / 1080.0;
let margin = move |b: [f64; 4]| (b[0] * w).min(b[1] * h).min(w - b[2] * w).min(h - b[3] * h) / s;
(runs(worlds, |_, t| t.box_.map(margin).filter(|m| m + 1.0 < v), |a, b| a < b), "is {n} px from the edge, inside {v}", "px")
}
other => return vec![Finding::new(&rule.id, level, format!("{other} isn't a text check"), &rule.by)],
};
let shown = |x: f64| if unit == "s" { format!("{x:.1}") } else { format!("{x:.0}") };
got.iter()
.map(|r| {
let said = format!("{} {}", quote(&r.words), says.replace("{n}", &shown(r.value)).replace("{v}", &shown(v)));
let said = if rule.text.is_empty() { said } else { format!("{said} (\"{}\")", rule.text) };
Finding::new(&rule.id, level, said, &rule.by).about(r.words.clone(), r.key.clone()).frames(r.from, r.to).measure(&rule.check, (r.value * 10.0).round() / 10.0, unit, Some(v))
})
.collect()
}
#[cfg(test)]
mod tests;
+75
View File
@@ -0,0 +1,75 @@
use super::*;
use raea_core_facts::{Level, Shot};
use serde_json::{json, Map, Value};
/// Frames 0..n of a 1080x1920 piece at 30 fps, each holding the texts `on(frame)` gives (words, box).
fn piece(n: i64, on: impl Fn(i64) -> Vec<(&'static str, [f64; 4])>) -> Vec<Facts> {
(0..n)
.map(|f| {
let mut w = Facts::new(f, 1080, 1920, 30.0);
for (words, b) in on(f) {
let e = w.spawn(None);
w.put(e, &Text { words: words.into(), font: None, size: Some(64.0), box_: Some(b), extruded: 0.0, lines: Some(1), needs: None });
}
w
})
.collect()
}
fn rule(check: &str, v: f64) -> Rule {
Rule::named(check, "", Map::from_iter([("value".to_string(), Value::from(v))]), Level::Error, "taste taste.ts")
}
#[test]
fn a_text_on_too_briefly_is_found_once_over_its_frames() {
// "GO" is on frames 10 to 24 (half a second), "STAY" all 90
let w = piece(90, |f| {
let mut v = vec![("STAY", [0.1, 0.1, 0.9, 0.2])];
if (10..25).contains(&f) {
v.push(("GO", [0.1, 0.5, 0.9, 0.6]));
}
v
});
let got = text(&rule("text-hold", 2.0), &w);
assert_eq!(got.len(), 1, "{got:?}");
assert_eq!((got[0].frames, got[0].about[0].name.as_str()), (Some([10, 25]), "GO"));
assert!(got[0].says.starts_with("\"GO\" is on for 0.5 s, under 2.0 s"), "{}", got[0].says);
assert_eq!(got[0].measure.as_ref().map(|m| (m.value, m.limit)), Some((0.5, Some(2.0))));
}
#[test]
fn placement_and_margin_name_the_worst_frame_of_a_run() {
// a caption whose bottom slides down from 70% to 85% over frames 0 to 30
let w = piece(31, |f| vec![("SALE", [0.2, 0.6, 0.8, 0.70 + 0.005 * f as f64])]);
let above = text(&rule("text-above", 80.0), &w);
assert_eq!(above.len(), 1);
assert_eq!(above[0].frames, Some([21, 31]), "past 80% from frame 21: {above:?}");
assert!(above[0].says.contains("reaches 85% down the frame, below 80%"), "{}", above[0].says);
assert!(text(&rule("text-below", 50.0), &w).is_empty(), "it starts at 60%, below 50%");
// 0.2 of 1080 is 216 px from the left and right; the bottom is 0.15 of 1920 = 288 px at its lowest
assert!(text(&rule("text-margin", 200.0), &w).is_empty());
assert_eq!(text(&rule("text-margin", 250.0), &w).len(), 1);
}
#[test]
fn a_rule_with_no_value_says_so() {
let r = Rule { level: Some(Level::Warn), ..Rule::named("text-hold", "", Map::new(), Level::Error, "project controllers/rules.ts") };
let got = text(&r, &piece(3, |_| vec![]));
assert_eq!((got.len(), got[0].level), (1, Level::Warn));
assert!(got[0].says.contains("needs a value"));
}
#[test]
fn cuts_are_the_frame_before_and_the_first_frame_of_each_shot_after_the_first() {
let mut w = piece(60, |_| vec![]);
for f in &mut w {
let (from, to) = if f.frame < 20 { (0, Some(20)) } else { (20, None) };
let e = f.spawn(None);
f.put(e, &Shot { name: None, from, to });
}
assert_eq!(Frames::Cuts.pick(&w), vec![19, 20]);
assert_eq!(Frames::Once.pick(&w), vec![0]);
assert_eq!(Frames::of(&json!("lines")).unwrap(), Frames::Lines);
assert_eq!(Frames::of(&json!([3, 4])).unwrap(), Frames::At(vec![3, 4]));
assert!(Frames::of(&json!("every")).unwrap_err().contains("not \"every\""));
}
+105
View File
@@ -0,0 +1,105 @@
//! A project's own checks in TypeScript (sdk/raea/src/check.ts, DR4): each file's declaration read first (its id,
//! line, what it needs and where it runs), then one run of every planned check over the worlds it ranges over, in the
//! engine's V8 with nothing drawn. raea/check's `runChecks` runs them; what they found comes back as Findings.
use std::path::{Path, PathBuf};
use raea_core_facts::{Facts, Finding, Level};
use serde_json::{json, Value};
use crate::systems::Frames;
type R<T> = Result<T, String>;
/// What the CLI lends a check: its evaluator of a .ts module's default export (as JSON), and its headless run of a
/// bundle (exit code and what it printed).
pub struct Host {
pub eval: fn(&Path) -> R<String>,
pub run: fn(&Path, f64) -> R<(i32, String)>,
}
/// A check file's declaration.
#[derive(Debug, Clone)]
pub struct Meta {
pub file: PathBuf,
pub id: String,
pub text: String,
pub render: bool,
pub level: Level,
pub frames: Frames,
}
/// The declaration of the check `file`'s default export is.
pub fn meta(file: &Path, host: &Host) -> R<Meta> {
let name = file.display();
let v: Value = serde_json::from_str(&(host.eval)(file)?).map_err(|e| format!("{name}: {e}"))?;
let s = |k: &str| v[k].as_str().map(str::to_string);
let id = s("id").ok_or_else(|| format!("{name}: its default export isn't a check({{ id, text }}, system) from \"raea/check\""))?;
let render = match v["needs"].as_str() {
None => false,
Some("render") => true,
Some(o) => return Err(format!("{name}: a check needs \"render\" or nothing, not \"{o}\"")),
};
let level = match s("level").as_deref() {
None => Level::Error,
Some(w @ ("error" | "warn" | "note")) => Level::of_word(w),
Some(o) => return Err(format!("{name}: a check's level is error, warn or note, not \"{o}\"")),
};
let frames = Frames::of(&v["frames"]).map_err(|e| format!("{name}: {e}"))?;
Ok(Meta { file: file.to_path_buf(), id, text: s("text").unwrap_or_default(), render, level, frames })
}
/// One planned run: the check (its index in `files`), its frames, and its rule's values, level (None: the check's
/// own) and `by`.
pub struct Planned {
pub check: usize,
pub frames: Vec<i64>,
pub values: serde_json::Map<String, Value>,
pub level: Option<Level>,
pub by: String,
}
/// Every planned check run on its frames of `worlds`, in one bundle: what each found (its rule's level where the
/// finding names none, its `by` the rule's), and a finding for each check that threw.
pub fn run(files: &[PathBuf], plan: &[Planned], worlds: &[Facts], host: &Host) -> R<Vec<Finding>> {
if plan.is_empty() {
return Ok(Vec::new());
}
let work = std::env::temp_dir().join(format!("raea-check-{}", std::process::id()));
std::fs::create_dir_all(&work).map_err(|e| e.to_string())?;
let data = work.join("worlds.json");
std::fs::write(&data, serde_json::to_string(worlds).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
let imports: String = files.iter().enumerate().map(|(i, f)| format!("import c{i} from {:?};\n", f.canonicalize().unwrap_or_else(|_| f.clone()).display().to_string())).collect();
let checks = (0..files.len()).map(|i| format!("c{i}")).collect::<Vec<_>>().join(", ");
let planned: Vec<Value> = plan.iter().map(|p| json!({"check": p.check, "frames": p.frames, "values": p.values, "level": p.level, "by": p.by})).collect();
let entry = format!(
"import {{ declared, runChecks }} from \"raea/check\";\n{imports}import worlds from {data:?};\nconst call = (globalThis as any).__raea_call;\n\
try {{ const checks = [{checks}]; declared(checks); const r = runChecks(checks, {plan}, worlds as any); call(\"print\", JSON.stringify({{ text: JSON.stringify(r) }})); call(\"done\", JSON.stringify({{ code: 0 }})); }}\n\
catch (e: any) {{ call(\"print\", JSON.stringify({{ text: \"error: \" + (e && e.message ? e.message : String(e)) }})); call(\"done\", JSON.stringify({{ code: 1 }})); }}\n",
data = data.display().to_string(),
plan = Value::Array(planned),
);
let js = work.join("checks.js");
let ran = raea_runtime_bundle::bundle_entry(&entry, &js, &[]).and_then(|_| {
// what the checks print is raea's to read: nothing reaches the terminal
let echo = raea_runtime_react::native::ECHO.swap(false, std::sync::atomic::Ordering::Relaxed);
let ran = (host.run)(&js, 120.0);
raea_runtime_react::native::ECHO.store(echo, std::sync::atomic::Ordering::Relaxed);
ran
});
let _ = std::fs::remove_dir_all(&work);
let (code, printed) = ran?;
let last = printed.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("");
if code != 0 {
return Err(format!("the project's checks: {}", last.strip_prefix("error: ").unwrap_or(last)));
}
let got: Value = serde_json::from_str(last).map_err(|e| format!("the project's checks printed {last:?}: {e}"))?;
// a finding that doesn't read is said as it came, never dropped
let unread = |f: &Value| Finding::new(f["check"].as_str().unwrap_or("check"), Level::Error, format!("a finding raea couldn't read: {f}"), "raea check");
let mut out: Vec<Finding> = got["findings"].as_array().into_iter().flatten().map(|f| Finding::read(f).unwrap_or_else(|| unread(f))).collect();
for t in got["threw"].as_array().into_iter().flatten() {
let id = t["check"].as_str().unwrap_or("check");
out.push(Finding::new(id, Level::Error, format!("the check threw {}", t["says"].as_str().unwrap_or("")), "raea check").fix("fix the check: it ran on none of the frames after this one"));
}
Ok(out)
}
+229
View File
@@ -0,0 +1,229 @@
//! `raea world EDIT.tsx`: a composition's frame as one world (docs/direction.feature DR1), read with React stepped and
//! nothing drawn; the page laid out unless `--no-layout`. `--find` is one query of it, raea/ecs's find: the entities
//! with every component `with` names, none `without` names, and each `where` field equal (`"Layer.medium": "2d-type"`).
use raea_runtime_world::{Ask, Entity, Facts, Render};
use raea_runtime_bundle::flag;
use serde_json::{json, Value};
pub const USAGE: &str = "raea world EDIT.tsx [--composition ID] [--frame N | --at A-B|A,B] [--find JSON] [--no-layout] [--render OUT | --no-render] [--json] (a frame as one world: its layers, text, parts, camera, shots, clips, cues and lines as entities with components, each measured, with what its newest render measured (contrast, light and movement, loudness, onsets, covers) or what waits for one; --find '{\"with\": [\"Text\", \"Layer\"], \"where\": {\"Layer.medium\": \"2d-type\"}}' is one query across media)";
/// A query: the components an entity has, those it hasn't, and fields (Component.field.field) equal to a value.
#[derive(Debug, Default, PartialEq)]
pub struct Find {
pub with: Vec<String>,
pub without: Vec<String>,
pub fields: Vec<(String, Value)>,
}
impl Find {
pub fn parse(s: &str) -> Result<Find, String> {
let v: Value = serde_json::from_str(s).map_err(|e| format!("--find takes JSON ({{\"with\": [...], \"without\": [...], \"where\": {{\"Comp.field\": value}}}}): {e}"))?;
let names = |k: &str| -> Result<Vec<String>, String> {
match &v[k] {
Value::Null => Ok(Vec::new()),
Value::Array(a) => a.iter().map(|n| n.as_str().map(str::to_string).ok_or_else(|| format!("--find's {k} lists component names"))).collect(),
_ => Err(format!("--find's {k} is a list of component names")),
}
};
let fields = match &v["where"] {
Value::Null => Vec::new(),
Value::Object(m) => m.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
_ => return Err("--find's where is an object of \"Component.field\": value".into()),
};
let known = ["with", "without", "where"];
if let Some(k) = v.as_object().and_then(|o| o.keys().find(|k| !known.contains(&k.as_str()))) {
return Err(format!("--find has no \"{k}\" (it takes with, without and where)"));
}
Ok(Find { with: names("with")?, without: names("without")?, fields })
}
fn holds(&self, e: &Entity) -> bool {
let at = |path: &str| -> Option<&Value> {
let mut keys = path.split('.');
let mut v = e.components.get(keys.next()?)?;
for k in keys {
v = v.get(k)?;
}
Some(v)
};
self.with.iter().all(|c| e.components.contains_key(c)) && !self.without.iter().any(|c| e.components.contains_key(c)) && self.fields.iter().all(|(p, v)| at(p) == Some(v))
}
}
/// The entities of `w` that `q` finds, in id order.
pub fn find<'a>(w: &'a Facts, q: &Find) -> Vec<&'a Entity> {
w.entities.iter().filter(|e| q.holds(e)).collect()
}
fn frames(args: &[String]) -> Result<Vec<i64>, String> {
let n = |s: &str, k: &str| s.trim().parse::<i64>().map_err(|_| format!("{k} takes frame numbers, got \"{s}\""));
match (flag(args, "--frame").as_deref(), flag(args, "--at").as_deref()) {
(Some(_), Some(_)) => Err("give --frame or --at, not both".into()),
(Some(f), None) => Ok(vec![n(f, "--frame")?]),
// as render's --at: a list (A,B,C), or a range (A-B), each frame its own world
(None, Some(r)) => match r.split_once('-') {
Some((a, b)) => {
let (a, b) = (n(a, "--at")?, n(b, "--at")?);
if b < a {
return Err(format!("--at {r} runs backwards"));
}
Ok((a..=b).collect())
}
None => r.split(',').map(|f| n(f, "--at")).collect(),
},
(None, None) => Ok(vec![0]),
}
}
/// One entity as a line: its id, parent and each component's gist.
fn line(e: &Entity) -> String {
let s = raea_runtime_world::text_of;
let r2 = |v: &Value| v.as_array().map(|a| a.iter().map(|x| format!("{:.2}", x.as_f64().unwrap_or(0.0))).collect::<Vec<_>>().join(", ")).unwrap_or_default();
let mut out = format!("#{}{}", e.id, e.parent.map(|p| format!(" in #{p}")).unwrap_or_default());
for (name, c) in &e.components {
let gist = match name.as_str() {
"Layer" => format!("{} at {}{}", s(&c["medium"]), c["order"], if c["opacity"].as_f64().unwrap_or(1.0) < 1.0 { format!(", opacity {}", c["opacity"]) } else { String::new() }),
"Text" => format!("\"{}\"{}{}{}", s(&c["words"]), c["size"].as_f64().map(|v| format!(" {v} px")).unwrap_or_default(), if c["box"].is_array() { format!(" box ({})", r2(&c["box"])) } else { String::new() }, c["needs"].as_str().map(|n| format!(" (needs {n})")).unwrap_or_default()),
"Part" => format!("{} \"{}\"{}{}", s(&c["kind"]), s(&c["name"]), if c["min"].is_array() { format!(" box ({}) to ({})", r2(&c["min"]), r2(&c["max"])) } else { " (not measured)".into() }, c["triangles"].as_u64().map(|t| format!(", {t} triangles")).unwrap_or_default()),
"Camera" => format!("eye ({}) looking at ({}){}", r2(&c["eye"]), r2(&c["look"]), if c["velocity"].is_array() { format!(", moving ({}) m/s", r2(&c["velocity"])) } else { String::new() }),
"Shot" => format!("{} frames {} to {}", c["name"].as_str().unwrap_or("(unnamed)"), c["from"], c["to"].as_i64().map_or("the end".into(), |t| t.to_string())),
"Clip" => format!("{} at {}s of it, {} words", s(&c["source"]), c["time"].as_f64().map_or("?".into(), |t| format!("{t:.2}")), c["words"].as_array().map_or(0, Vec::len)),
"Cue" => format!("{} from {:.2}s{}", s(&c["source"]), c["at"].as_f64().unwrap_or(0.0), c["gain"].as_f64().map(|g| format!(" at {g} dB")).unwrap_or_default()),
"Line" => format!("\"{}\" from {:.2}s{}", s(&c["text"]), c["from"].as_f64().unwrap_or(0.0), c["needs"].as_str().map(|n| format!(" (needs {n})")).unwrap_or_default()),
"Source" => format!("{}:{}{}", s(&c["file"]), c["line"], c["component"].as_str().map(|n| format!(" <{n}>")).unwrap_or_default()),
"Contrast" => format!("{}:1 against its pixels", c["ratio"]),
"Picture" => picture(c),
"Onset" => c["at"].as_f64().map_or_else(|| "not heard where it starts".into(), |a| format!("heard at {a:.2}s ({:+} ms)", c["late_ms"].as_f64().unwrap_or(0.0))),
"Covers" => c.as_array().into_iter().flatten().map(|x| format!("#{} {:.0}%", x["layer"], x["share"].as_f64().unwrap_or(0.0) * 100.0)).collect::<Vec<_>>().join(", "),
_ => c.get("to").map_or_else(|| c.to_string(), |t| format!("#{t}")),
};
out.push_str(&format!(" {name} {gist}"));
}
out
}
/// A picture's light and movement as words.
fn picture(c: &Value) -> String {
let moved = c["motion"].as_f64().map(|m| format!(", motion {m:.3}")).unwrap_or_default();
format!("luma {:.3}{moved}{}", c["luma"].as_f64().unwrap_or(0.0), c["frames"].as_u64().map(|n| format!(" over {n} frames")).unwrap_or_default())
}
/// The frame's resources as lines: the render its facts came from, its mix and picture, what waits for one.
fn resources(w: &Facts) -> Vec<String> {
let r = &w.resources;
let mut out = Vec::new();
if let Some(x) = r.get("Rendered") {
let stale = if x["stale"] == true { " (made before the composition last changed: its measures are of that version)" } else { "" };
out.push(format!(" rendered: {}{}{stale}", raea_runtime_world::text_of(&x["out"]), x["record"].as_str().map(|i| format!(" ({i})")).unwrap_or_default()));
}
if let Some(m) = r.get("Mix") {
out.push(match m["lufs"].as_f64() {
Some(l) => format!(" mix: {l:.1} LUFS{}", m["peak"].as_f64().map(|p| format!(", true peak {p:.1} dBTP")).unwrap_or_default()),
None => " mix: no sound".into(),
});
}
if let Some(p) = r.get("Picture") {
out.push(format!(" picture: {}", picture(p)));
}
if let Some(Value::Object(ws)) = r.get("Waits") {
let mut by: Vec<(String, Vec<&str>)> = Vec::new();
for (c, on) in ws {
let on = raea_runtime_world::text_of(on);
match by.iter_mut().find(|(o, _)| *o == on) {
Some((_, cs)) => cs.push(c),
None => by.push((on, vec![c])),
}
}
out.extend(by.into_iter().map(|(on, cs)| format!(" waits for {on}: {}", cs.join(", "))));
}
out
}
/// Which render's facts join: `--render OUT`, none with `--no-render`, else the newest in the project's record.
fn render(args: &[String]) -> Result<Render, String> {
match (flag(args, "--render"), args.iter().any(|a| a == "--no-render")) {
(Some(_), true) => Err("give --render or --no-render, not both".into()),
(Some(o), false) => Ok(Render::From(o.into())),
(None, true) => Ok(Render::Off),
(None, false) => Ok(Render::Newest),
}
}
fn run(args: &[String]) -> Result<String, String> {
let edit = args.iter().find(|a| a.ends_with(".tsx")).ok_or(USAGE)?;
let q = flag(args, "--find").as_deref().map(Find::parse).transpose()?;
let ask = Ask { frames: frames(args)?, layout: !args.iter().any(|a| a == "--no-layout"), render: render(args)?, join_on: None };
let worlds = raea_runtime_world::read(std::path::Path::new(edit), &raea_runtime_bundle::comp_opts(args)?, &ask)?;
if args.iter().any(|a| a == "--json") {
let one = |w: &Facts| match &q {
Some(q) => json!({"frame": w.frame, "found": find(w, q)}),
None => serde_json::to_value(w).unwrap_or(Value::Null),
};
let v = if worlds.len() == 1 { one(&worlds[0]) } else { Value::Array(worlds.iter().map(one).collect()) };
return Ok(serde_json::to_string_pretty(&v).unwrap_or_default());
}
let mut out = Vec::new();
for w in &worlds {
let shown = q.as_ref().map_or_else(|| w.entities.iter().collect(), |q| find(w, q));
out.push(format!("frame {} ({}x{} at {} fps): {} of {} entities", w.frame, w.width, w.height, w.fps, shown.len(), w.entities.len()));
out.extend(resources(w));
out.extend(shown.into_iter().map(line));
}
Ok(out.join("\n"))
}
/// `raea world ...`: its exit code.
pub fn cli(args: &[String]) -> i32 {
let got = run(args);
match &got {
Ok(s) => println!("{s}"),
Err(e) => eprintln!("raea world: {e}"),
}
if got.is_ok() { 0 } else { 2 }
}
#[cfg(test)]
mod tests {
use super::*;
use raea_runtime_world::{Layer, Medium, Part, Text};
fn world() -> Facts {
let mut w = Facts::new(0, 1920, 1080, 30.0);
let lyric = w.spawn(None);
w.put(lyric, &Layer { medium: Medium::Type2d, order: 2, opacity: 1.0, blend: None });
w.put(lyric, &Text { words: "GIVE IT BACK".into(), font: None, size: Some(96.0), box_: Some([0.1, 0.1, 0.6, 0.2]), extruded: 0.0, lines: Some(1), needs: None });
let scene = w.spawn(None);
w.put(scene, &Layer { medium: Medium::Scene3d, order: 0, opacity: 1.0, blend: None });
let sign = w.spawn(Some(scene));
w.put(sign, &Text { words: "OPEN".into(), font: None, size: None, box_: None, extruded: 0.2, lines: Some(1), needs: None });
w.put(sign, &Part { kind: "text3d".into(), name: "sign".into(), tags: vec![], at: [0.0; 3], rotation: [0.0, 0.0, 0.0, 1.0], scale: [1.0; 3], min: None, max: None, own: None, triangles: None, src: None, material: None, color: None });
let hidden = w.spawn(None);
w.put(hidden, &Layer { medium: Medium::Type2d, order: 3, opacity: 1.0, blend: None });
w.put(hidden, &Text { words: "UNDER".into(), font: None, size: None, box_: None, extruded: 0.0, lines: None, needs: None });
w.relate(hidden, "MaskedBy", sign);
w
}
#[test]
fn one_find_spans_media() {
let w = world();
let flat = Find::parse(r#"{"with": ["Text", "Layer"], "where": {"Layer.medium": "2d-type"}, "without": ["MaskedBy"]}"#).unwrap();
let got: Vec<u32> = find(&w, &flat).iter().map(|e| e.id).collect();
assert_eq!(got, vec![0], "the 2D lyric no part masks, not the 3D sign or the masked line");
let words_in_3d = Find::parse(r#"{"with": ["Text", "Part"], "where": {"Text.extruded": 0.2}}"#).unwrap();
assert_eq!(find(&w, &words_in_3d).len(), 1);
assert!(line(&w.entities[0]).contains("\"GIVE IT BACK\" 96 px box (0.10, 0.10, 0.60, 0.20)"), "{}", line(&w.entities[0]));
}
#[test]
fn a_bad_query_or_range_says_what_it_takes() {
assert!(Find::parse(r#"{"has": ["Text"]}"#).unwrap_err().contains("no \"has\""));
assert!(Find::parse("Text").is_err());
let a = |s: &[&str]| s.iter().map(|x| x.to_string()).collect::<Vec<_>>();
assert_eq!(frames(&a(&["e.tsx", "--at", "3-5"])).unwrap(), vec![3, 4, 5]);
assert!(frames(&a(&["--at", "5-3"])).unwrap_err().contains("backwards"));
assert_eq!(frames(&a(&["--at", "3,7"])).unwrap(), vec![3, 7], "a list, as render's --at");
assert_eq!(frames(&a(&["e.tsx"])).unwrap(), vec![0]);
}
}
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "raea-app-engines"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "The `raea` verbs that script other engines from TypeScript: Blender (`setup blender`, `blender run`) and Godot with GodotJS (`setup godot`, `godot run|types|open`)"
[dependencies]
# Blender found or downloaded, its scripts in Python, and the helpers Godot's setup shares (apps/tools/src/blender.rs)
raea-app-tools = { path = "../tools" }
raea-io-home = { path = "../../io/home" }
# a TypeScript script bundled and run on raea's engine, posting raea/blender's batches to the bridge (blender.post)
raea-runtime-bundle = { path = "../../runtime/bundle" }
raea-runtime-export = { path = "../../runtime/export" }
raea-runtime-calls = { path = "../../runtime/calls" }
# a composition's 3D as scene.json, a Godot project from it, and changes read back (raea scene export, raea godot export|back,
# raea blender open|back)
raea-app-interchange = { path = "../interchange" }
serde_json = "1"
# Godot with GodotJS, unpacked from its release zip (`raea setup godot`), and the script path the bundler imports
zip = { version = "9", default-features = false, features = ["deflate-flate2"] }
dunce = "1"
+142
View File
@@ -0,0 +1,142 @@
//! The Blender a TypeScript script drives (`raea blender run SCRIPT.ts`, sdk/blender): a headless Blender started with
//! raea's bridge (sdk/blender/python/headless.py), which serves raea/blender's batches on 127.0.0.1 behind a token,
//! and ends with this process. The CLI runs the script on raea's engine, posting each batch (the native call
//! blender.post, runtime/calls/src/blender.rs); Node and Bun start their own (sdk/blender/src/launch.ts).
use std::hash::{BuildHasher, Hasher};
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
type R<T> = Result<T, String>;
/// A script raea runs as TypeScript (against raea/blender) rather than as Python.
pub fn is_ts(script: &str) -> bool {
[".ts", ".tsx", ".mts", ".js", ".mjs"].iter().any(|e| script.ends_with(e))
}
/// The bridge script in the SDK raea ships (its home's sdk/, else this checkout's).
pub fn bridge_script() -> R<PathBuf> {
let shipped = raea_io_home::home().join("sdk/blender/python/headless.py");
if shipped.is_file() {
return Ok(shipped);
}
let here = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../sdk/blender/python/headless.py");
if here.is_file() {
return Ok(here);
}
Err(format!("raea/blender's bridge isn't here ({}): reinstall raea", shipped.display()))
}
/// 128 bits from the OS's random keys (each RandomState is seeded from them), as hex.
fn token() -> String {
let word = || {
let mut h = std::collections::hash_map::RandomState::new().build_hasher();
h.write_u128(Instant::now().elapsed().as_nanos() ^ u128::from(std::process::id()));
h.finish()
};
format!("{:016x}{:016x}", word(), word())
}
pub struct Bridge {
pub port: u16,
pub token: String,
child: Child,
}
/// Blender's own lines nobody needs from a script's run: its banner and its goodbye.
fn banner(l: &str) -> bool {
let t = l.trim();
t.starts_with("Blender quit") || (t.starts_with("Blender ") && t.as_bytes().get(8).is_some_and(u8::is_ascii_digit))
}
/// A headless Blender serving raea/blender: `file` (a .blend) opened, `args` after `--` (Python's sys.argv). Its
/// output after the bridge starts goes to stderr, as the script's prints.
pub fn start(blender: &Path, file: Option<&Path>, args: &[String]) -> R<Bridge> {
let script = bridge_script()?;
let token = token();
let mut cmd = Command::new(blender);
cmd.args(["--background", "--factory-startup"]);
if let Some(f) = file {
cmd.arg(f);
}
cmd.args(["--python-exit-code", "1", "--python"]).arg(&script).arg("--").args(args);
cmd.env("RAEA_BLENDER_TOKEN", &token).env("RAEA_BLENDER_PORT", "0").env("RAEA_BLENDER_PARENT", std::process::id().to_string());
let mut child = cmd.stdout(Stdio::piped()).stderr(Stdio::inherit()).spawn().map_err(|e| format!("{}: {e}", blender.display()))?;
let mut lines = BufReader::new(child.stdout.take().ok_or("Blender's output")?).lines();
let mut early = Vec::new();
let port = loop {
match lines.next() {
Some(Ok(l)) => match l.trim().strip_prefix("RAEA_BLENDER_READY ") {
Some(ready) => {
let v: serde_json::Value = serde_json::from_str(ready).map_err(|e| format!("the bridge's ready line {ready}: {e}"))?;
break v.get("port").and_then(serde_json::Value::as_u64).ok_or("the bridge's port")? as u16;
}
None => early.push(l),
},
_ => {
let st = child.wait().map_err(|e| e.to_string())?;
let tail = early[early.len().saturating_sub(30)..].join("\n");
return Err(format!("Blender exited ({st}) before raea's bridge started:\n{tail}"));
}
}
};
std::thread::spawn(move || {
for l in lines.map_while(Result::ok) {
if !banner(&l) {
eprintln!("{l}");
}
}
});
Ok(Bridge { port, token, child })
}
impl Bridge {
/// Waits for Blender to exit (after the bridge was asked to quit), killing it after 10 s.
pub fn wait(mut self) {
let t0 = Instant::now();
while t0.elapsed() < Duration::from_secs(10) {
if let Ok(Some(_)) = self.child.try_wait() {
return;
}
std::thread::sleep(Duration::from_millis(20));
}
let _ = self.child.kill();
let _ = self.child.wait();
}
}
impl Drop for Bridge {
/// A run that ends early (an error, a panic) leaves no Blender behind.
fn drop(&mut self) {
if let Ok(None) = self.child.try_wait() {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn typescript_scripts_by_extension() {
assert!(is_ts("scene.ts") && is_ts("a/b.tsx") && is_ts("x.mjs"));
assert!(!is_ts("convert.py") && !is_ts("blender/repair.py"));
}
#[test]
fn tokens_differ_and_are_128_bits() {
let (a, b) = (token(), token());
assert_eq!(a.len(), 32);
assert_ne!(a, b);
}
#[test]
fn the_banner_is_dropped_and_prints_kept() {
assert!(banner("Blender 5.2.1 LTS (hash 1a2b3c built 2026-10-01)") && banner("Blender quit"));
assert!(!banner("Blender found 3 objects") && !banner("made Cube"));
}
}
+61
View File
@@ -0,0 +1,61 @@
//! `raea blender run SCRIPT.ts [FILE.blend] [ARGS...]`: a headless Blender with raea's bridge (FILE.blend opened, ARGS
//! its sys.argv after --), the script on raea's engine with each batch posted to it (blender.post), Blender quit after.
use std::path::{Path, PathBuf};
use raea_runtime_calls::blender::{BRIDGE, post};
use serde_json::json;
use crate::{R, blender_bridge};
/// What an entry does once its work is a promise: the session closed (sdk/blender/src/blender.ts's
/// __raea_blender_end), so a failure in Blender the script never awaited fails the run, as an uncaught Python exception
/// would; then the run's exit.
pub(crate) const CLOSE: &str = ".then(() => (globalThis as any).__raea_blender_end?.()).then(() => call(\"done\", JSON.stringify({ code: 0 })), (e: any) => { call(\"print\", JSON.stringify({ text: \"error: \" + String(e) + (e && e.name === \"BlenderError\" ? (e.pythonTrace ? \"\\n\" + e.pythonTrace : \"\") : e && e.stack ? \"\\n\" + e.stack : \"\") })); call(\"done\", JSON.stringify({ code: 1 })); });";
/// The script's default export, called and awaited.
pub(crate) const DEFAULT: &str = "Promise.resolve().then(() => (typeof (M as any).default === \"function\" ? (M as any).default() : undefined))";
/// `--timeout SECS` taken out of ARGS (Blender's sys.argv), and its seconds.
pub(crate) fn timeout(rest: &mut Vec<String>) -> f64 {
let mut secs = 3600.0;
if let Some(i) = rest.iter().position(|a| a == "--timeout") {
secs = rest.get(i + 1).and_then(|t| t.parse().ok()).unwrap_or(secs);
rest.drain(i..(i + 2).min(rest.len()));
}
secs
}
/// An entry's bundle run against a headless Blender started with the bridge (`file` opened, `rest` its sys.argv):
/// the bundle's exit code. Blender is quit after, and killed if the run ends any other way.
pub(crate) fn session(entry: &str, file: Option<&Path>, rest: &[String], secs: f64) -> R<i32> {
let (bin, _) = raea_app_tools::blender::find().ok_or("no Blender: raea setup blender finds or downloads one")?;
let bridge = blender_bridge::start(&bin, file, rest)?;
*BRIDGE.lock().map_err(|e| e.to_string())? = Some((bridge.port, bridge.token.clone()));
let out = std::env::temp_dir().join(format!("raea-blender-{}.js", std::process::id()));
let ran = raea_runtime_bundle::bundle_entry(entry, &out, &[]).and_then(|_| raea_runtime_export::run_bundle(&out, secs));
let _ = std::fs::remove_file(&out);
let _ = post(&json!({ "sid": "raea", "ops": [{ "o": "quit" }] }));
*BRIDGE.lock().map_err(|e| e.to_string())? = None;
bridge.wait();
Ok(ran?.0)
}
/// A path as an entry's import specifier (Windows' verbatim prefix dropped, as raea-runtime-bundle does).
pub(crate) fn spec(p: &Path) -> String {
format!("{:?}", dunce::simplified(p).display().to_string())
}
pub fn run(args: &[String]) -> R<String> {
let ts = PathBuf::from(&args[2]).canonicalize().map_err(|e| format!("{}: {e}", args[2]))?;
let file = args.get(3).filter(|a| a.ends_with(".blend")).map(PathBuf::from);
// ARGS for Blender's sys.argv, without raea's own --timeout SECS
let mut rest = args[if file.is_some() { 4 } else { 3 }..].to_vec();
let secs = timeout(&mut rest);
let entry = format!("import * as M from {};\nconst call = (globalThis as any).__raea_call;\n{DEFAULT}{CLOSE}\n", spec(&ts));
let code = session(&entry, file.as_deref(), &rest, secs)?;
if code != 0 {
return Err(format!("{} ended with exit {code}", args[2]));
}
Ok(String::new())
}
+305
View File
@@ -0,0 +1,305 @@
//! `raea setup godot`, `raea godot types` and `raea godot open`; `raea godot run` is godot_run.rs. raea's Godot is
//! Godot 4.6.1 with GodotJS (github.com/godotjs/GodotJS, MIT): Godot's whole API from TypeScript, on Godot's own
//! JavaScript engine, JavaScriptCore on the Mac and QuickJS-ng on Windows and Linux (no V8). Godot without GodotJS
//! can't run a script, so raea uses an editor build with GodotJS in it (the editor, headless or not, runs scripts and
//! projects): raea's own (GD9, sdk/godot/build), from raea's release, else GodotJS's, from its GitHub release, into
//! ~/.raea/tools/godot and checked against the sha256 pinned here.
use std::path::{Path, PathBuf};
use std::process::Command;
use raea_app_tools::blender::own_dir;
type R<T> = Result<T, String>;
pub const USAGE: &str = "raea setup godot [--check] (download Godot 4.6.1 with GodotJS, its TypeScript bindings (MIT), into ~/.raea/tools/godot: JavaScriptCore on the Mac, QuickJS on Windows and Linux; raea's own build (the Mac's notarized), else GodotJS's, each checked against its pinned sha256)\n raea godot run [SCRIPT.ts] [--project DIR] [--window] [--movie FILE [--fps N] [--frames N]] [--scene res://X.tscn] [--size WxH] [--timeout S] [ARGS...] (a TypeScript script against Godot's whole API through raea/godot: its default export gets the SceneTree and ARGS, headless unless --window; --movie writes every frame Godot draws (NAME.png numbered, or .avi) at a fixed --fps, 30 unless given; the project is DIR, else the nearest project.godot above the script, else an empty one; Godot quits when it returns, or after --frames N; --scene plays a scene of the project under it, with no script needed; a scene in --window plays until the window is closed)\n raea godot types [DIR] (the project's own TypeScript types from GodotJS: Godot's API with its scenes, resources and input actions, into DIR/typings)\n raea godot open [DIR] (the Godot editor on the project, GodotJS's, to edit its scenes)";
/// The GodotJS release raea downloads (github.com/godotjs/GodotJS/releases); sdk/godot/tools/gen.sh writes
/// raea/godot's types from it, so the two move together.
pub const RELEASE: &str = "v1.1.0.beta1-4.6.1";
/// raea's own builds of the same editors (GD9: sdk/godot/build's macos.sh, linux.py and windows.py, zipped by
/// package.sh; the Mac's signed with raea's Developer ID and notarized), files of raea's release of this tag.
pub const RAEA_RELEASE: &str = "v0.1.1";
/// Where raea's builds are downloaded from; RAEA_GODOT_FROM points elsewhere (a folder as file:///..., to rehearse).
fn raea_base() -> String {
std::env::var("RAEA_GODOT_FROM").unwrap_or_else(|_| format!("https://github.com/shinyobjectz/raea/releases/download/{RAEA_RELEASE}"))
}
/// One platform's download: who built it, the asset, its sha256 and size, and the program inside its one top folder.
#[derive(Clone, Copy)]
struct Pin {
by: &'static str,
asset: &'static str,
sha256: &'static str,
size: u64,
program: &'static str,
}
impl Pin {
fn url(&self) -> String {
match self.by {
"raea" => format!("{}/{}", raea_base(), self.asset),
_ => format!("https://github.com/godotjs/GodotJS/releases/download/{RELEASE}/{}", self.asset),
}
}
}
// raea's Mac build is arm64 and notarized; GodotJS's a universal app, ad-hoc signed
const MAC_RAEA: Pin = Pin { by: "raea", asset: "godot-4.6.1-raea-macos-arm64.zip", sha256: "17e66b8f99134a67db29ce82b88ace7f4c2e4ae651c80a3876ac6bd5e68a8a75", size: 69_132_728, program: "Godot.app/Contents/MacOS/Godot" };
const MAC_GODOTJS: Pin = Pin { by: "GodotJS", asset: "macos-editor-app-4.6.1-jsc.zip", sha256: "8a3022cb07c9740b2acc4a0b6bba6be78fb2fe46ba172b13abd51e6829cdca95", size: 143_940_673, program: "Godot.app/Contents/MacOS/Godot" };
const LINUX_RAEA: Pin = Pin { by: "raea", asset: "godot-4.6.1-raea-linux-x86_64.zip", sha256: "9c86b3e6af0f8cc8a7158685103ccbe15d10aaf246067ec47509909647726b54", size: 78_737_822, program: "godot.linuxbsd.editor.x86_64" };
const LINUX_GODOTJS: Pin = Pin { by: "GodotJS", asset: "linux-editor-4.6.1-qjs-ng.zip", sha256: "daa91d6cff5862ed9e0b3776694fbe4ea0ebb474d244f46ffb3aa5af0318989d", size: 78_737_089, program: "godot.linuxbsd.editor.x86_64" };
const WINDOWS_RAEA: Pin = Pin { by: "raea", asset: "godot-4.6.1-raea-windows-x86_64.zip", sha256: "cf360e7a350f04a1cdb8d1ac475ebfc81518b5b49831ab2ed693f5d8127265e5", size: 73_171_472, program: "godot.windows.editor.x86_64.exe" };
const WINDOWS_GODOTJS: Pin = Pin { by: "GodotJS", asset: "windows-editor-4.6.1-qjs-ng.zip", sha256: "041b761a945b6a34d40f508dbd1accca462d943d2941c3a1a4568f84dd29c1d4", size: 83_915_786, program: "godot.windows.editor.x86_64.exe" };
fn pins() -> R<Vec<Pin>> {
pins_for(std::env::consts::OS, std::env::consts::ARCH)
}
/// This platform's downloads in the order they're tried: raea's build, then GodotJS's (a release made before raea's
/// builds are among its files still installs). Both hold the program at the same path. A platform GodotJS doesn't
/// build for is told how to bring its own build (GD2), never given a stock Godot.
fn pins_for(os: &str, arch: &str) -> R<Vec<Pin>> {
match (os, arch) {
("macos", "aarch64") => Ok(vec![MAC_RAEA, MAC_GODOTJS]),
("macos", _) => Ok(vec![MAC_GODOTJS]),
("linux", "x86_64") => Ok(vec![LINUX_RAEA, LINUX_GODOTJS]),
("windows", "x86_64") => Ok(vec![WINDOWS_RAEA, WINDOWS_GODOTJS]),
(os, arch) => Err(format!("GodotJS has no build for {os} {arch}: build it (github.com/godotjs/GodotJS) and `git config --global raea.godot PATH`")),
}
}
/// Whether the download in own_dir is one this raea pins (raea.json beside it names its sha256), so a moved pin
/// downloads again.
fn own_is_pinned() -> bool {
let Some(text) = own_dir("godot").ok().and_then(|d| std::fs::read_to_string(d.join("raea.json")).ok()) else { return false };
let Ok(had) = serde_json::from_str::<serde_json::Value>(&text) else { return false };
pins().is_ok_and(|ps| ps.iter().any(|p| had["sha256"] == p.sha256))
}
/// The Godot to use and where it came from: `git config --global raea.godot` (a GodotJS build of your own), else
/// raea's download. A Godot without GodotJS isn't looked for: it can't run raea/godot's scripts.
pub fn find() -> Option<(PathBuf, &'static str)> {
let configured = raea_app_tools::blender::run(Command::new("git").args(["config", "--global", "raea.godot"]), "git config").ok().map(|out| PathBuf::from(out.trim()));
if let Some(p) = configured.filter(|p| p.is_file()) {
return Some((p, "raea.godot in git config"));
}
let own = own_dir("godot").ok()?.join(pins().ok()?.first()?.program);
own.is_file().then_some((own, "raea's download"))
}
/// The binary, or what to run to get one.
pub fn binary() -> R<PathBuf> {
find().map(|(p, _)| p).ok_or_else(|| "no Godot with GodotJS: raea setup godot downloads it".to_string())
}
/// `godot --version`'s line ("4.6.1.stable.gh.14d19694e").
fn version(bin: &Path) -> R<String> {
let o = Command::new(bin).args(["--headless", "--version"]).output().map_err(|e| format!("{}: {e}", bin.display()))?;
let out = String::from_utf8_lossy(&o.stdout);
out.lines().map(str::trim).find(|l| l.chars().next().is_some_and(|c| c.is_ascii_digit())).map(str::to_string).ok_or_else(|| format!("{} --version printed no version", bin.display()))
}
/// Downloads the first pinned editor that comes and matches (raea's, then GodotJS's) into ~/.raea/tools/godot and
/// returns its program, and which it was.
fn download() -> R<(PathBuf, String)> {
let mut not = Vec::new();
for p in pins()? {
match download_one(&p) {
Ok(program) => return Ok((program, downloaded(&p, &not))),
Err(e) => not.push(format!("{}'s build: {e}", p.by)),
}
}
Err(format!("no Godot downloaded: {}", not.join("; ")))
}
/// What `raea setup godot` says it downloaded: whose build, and why any tried before it wasn't.
fn downloaded(p: &Pin, not: &[String]) -> String {
let by = if p.by == "raea" { format!("raea's build ({}, from raea's {RAEA_RELEASE} release)", p.asset) } else { format!("GodotJS's build ({}, from GodotJS {RELEASE})", p.asset) };
let before = if not.is_empty() { String::new() } else { format!("; {}", not.join("; ")) };
format!("downloaded Godot 4.6.1 with GodotJS, {by}{before}")
}
/// One pinned download, checked and unpacked into ~/.raea/tools/godot: its program.
fn download_one(p: &Pin) -> R<PathBuf> {
let dir = own_dir("godot")?;
let tmp = dir.with_file_name("godot.download");
let _ = std::fs::remove_dir_all(&tmp);
std::fs::create_dir_all(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?;
let file = tmp.join(p.asset);
let url = p.url();
if raea_app_tools::blender::run(Command::new("curl").args(["-fsSL", "--retry", "3", "-o"]).arg(&file).arg(&url), "downloading Godot with GodotJS").is_err() {
return Err(format!("{url} didn't download"));
}
let size = std::fs::metadata(&file).map_err(|e| e.to_string())?.len();
if size != p.size || raea_app_tools::blender::sha256(&file)? != p.sha256 {
return Err(format!("{} doesn't match the sha256 raea pins ({size} bytes); nothing installed (it's in {})", p.asset, tmp.display()));
}
let unpacked = tmp.join("unpacked");
unzip(&file, &unpacked)?;
let program = unpacked.join(p.program);
if !program.is_file() {
return Err(format!("{} holds no {}", p.asset, p.program));
}
// the zips keep no executable bits
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).map_err(|e| e.to_string())?;
}
let release = if p.by == "raea" { RAEA_RELEASE } else { RELEASE };
std::fs::write(unpacked.join("raea.json"), serde_json::json!({ "by": p.by, "release": release, "asset": p.asset, "sha256": p.sha256 }).to_string()).map_err(|e| e.to_string())?;
let _ = std::fs::remove_dir_all(&dir);
std::fs::rename(&unpacked, &dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let _ = std::fs::remove_dir_all(&tmp);
Ok(dir.join(p.program))
}
/// A zip's files into `to`, without its one top folder (every GodotJS zip has one).
fn unzip(file: &Path, to: &Path) -> R<()> {
let f = std::fs::File::open(file).map_err(|e| format!("{}: {e}", file.display()))?;
let mut z = zip::ZipArchive::new(f).map_err(|e| format!("{}: {e}", file.display()))?;
for i in 0..z.len() {
let mut e = z.by_index(i).map_err(|e| e.to_string())?;
let Some(path) = e.enclosed_name() else { return Err(format!("{} has an entry outside its folder: {}", file.display(), String::from_utf8_lossy(e.name_raw()))) };
let rel: PathBuf = path.components().skip(1).collect();
if rel.as_os_str().is_empty() {
continue;
}
let out = to.join(rel);
if e.is_dir() {
std::fs::create_dir_all(&out).map_err(|e| e.to_string())?;
continue;
}
if let Some(d) = out.parent() {
std::fs::create_dir_all(d).map_err(|e| e.to_string())?;
}
let mut w = std::fs::File::create(&out).map_err(|e| format!("{}: {e}", out.display()))?;
std::io::copy(&mut e, &mut w).map_err(|e| format!("{}: {e}", out.display()))?;
}
Ok(())
}
/// `raea setup godot [--check]`.
pub fn setup(args: &[String]) -> R<String> {
let check = args.iter().any(|a| a == "--check");
let current = own_is_pinned();
let (bin, from) = match find() {
Some((p, from)) if from != "raea's download" || current => (p, from.to_string()),
_ if check => return Err("no Godot with GodotJS that this raea pins: raea setup godot downloads it".into()),
_ => download()?,
};
let v = version(&bin)?;
Ok(format!("APPLIED Godot {v} with GodotJS at {} ({from}); raea godot run SCRIPT.ts runs a script against it", bin.display()))
}
/// The project folder: DIR, else the current folder; it needs its project.godot.
fn project(arg: Option<&String>) -> R<PathBuf> {
let dir = arg.map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."));
let dir = dir.canonicalize().map_err(|e| format!("{}: {e}", dir.display()))?;
if !dir.join("project.godot").is_file() {
return Err(format!("{} has no project.godot", dir.display()));
}
Ok(dir)
}
/// `raea godot types [DIR]`: GodotJS's codegen on the project, headless (--generate-types), into DIR/typings.
fn types(args: &[String]) -> R<String> {
let dir = project(args.get(2))?;
let o = Command::new(binary()?).args(["--headless", "--editor", "--path"]).arg(&dir).arg("--generate-types").output().map_err(|e| e.to_string())?;
let log = format!("{}{}", String::from_utf8_lossy(&o.stdout), String::from_utf8_lossy(&o.stderr));
if !o.status.success() || !log.contains("Type generation complete") {
let tail: Vec<&str> = log.lines().rev().take(12).collect::<Vec<_>>().into_iter().rev().collect();
return Err(format!("GodotJS's codegen failed on {}:\n{}", dir.display(), tail.join("\n")));
}
let mut n = 0;
for e in std::fs::read_dir(dir.join("typings")).into_iter().flatten().flatten() {
n += e.file_name().to_string_lossy().ends_with(".d.ts") as usize;
}
Ok(format!("APPLIED {n} typings files in {} (Godot's API with the project's scenes, resources and input actions); a tsconfig that includes them types `import ... from \"godot\"`", dir.join("typings").display()))
}
/// `raea godot open [DIR]`: the editor on the project, left running.
fn open(args: &[String]) -> R<String> {
let dir = project(args.get(2))?;
// its output isn't raea's: a caller reading raea's (the app) would otherwise wait until the editor is closed
let null = std::process::Stdio::null;
Command::new(binary()?).args(["--editor", "--path"]).arg(&dir).stdin(null()).stdout(null()).stderr(null()).spawn().map_err(|e| e.to_string())?;
Ok(format!("APPLIED the Godot editor (GodotJS) is opening {}", dir.display()))
}
/// `raea godot types|open ...` (run is godot_run::run).
pub fn godot(args: &[String]) -> R<String> {
match args.get(1).map(String::as_str) {
Some("types") => types(args),
Some("open") => open(args),
Some("run") => crate::godot_run::run(args),
_ => Err(format!("usage: {USAGE}")),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_pin_has_a_full_digest() {
for (os, arch) in [("macos", "aarch64"), ("macos", "x86_64"), ("linux", "x86_64"), ("windows", "x86_64")] {
for p in pins_for(os, arch).unwrap() {
assert_eq!(p.sha256.len(), 64);
assert!(p.sha256.chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()));
assert!(p.asset.ends_with(".zip") && p.size > 50_000_000);
}
}
}
#[test]
fn raeas_build_is_tried_first_and_godotjss_after() {
for (os, arch) in [("macos", "aarch64"), ("linux", "x86_64"), ("windows", "x86_64")] {
let ps = pins_for(os, arch).unwrap();
assert_eq!(ps.iter().map(|p| p.by).collect::<Vec<_>>(), ["raea", "GodotJS"], "{os}");
assert_eq!(ps[0].program, ps[1].program, "{os}: both hold the program at one path");
assert!(ps[1].url().starts_with("https://github.com/godotjs/GodotJS/releases/download/v1.1.0.beta1-4.6.1/"));
}
let mac = pins_for("macos", "aarch64").unwrap();
if std::env::var_os("RAEA_GODOT_FROM").is_none() {
assert_eq!(mac[0].url(), "https://github.com/shinyobjectz/raea/releases/download/v0.1.1/godot-4.6.1-raea-macos-arm64.zip");
}
// raea builds the Mac editor for arm64 only: an Intel Mac gets GodotJS's universal app
assert_eq!(pins_for("macos", "x86_64").unwrap().iter().map(|p| p.by).collect::<Vec<_>>(), ["GodotJS"]);
}
#[test]
fn setup_says_whose_build_and_why_not_the_one_before() {
let ps = pins_for("linux", "x86_64").unwrap();
assert_eq!(downloaded(&ps[0], &[]), "downloaded Godot 4.6.1 with GodotJS, raea's build (godot-4.6.1-raea-linux-x86_64.zip, from raea's v0.1.1 release)");
let not = ["raea's build: https://x/godot-4.6.1-raea-linux-x86_64.zip didn't download".to_string()];
assert_eq!(downloaded(&ps[1], &not), "downloaded Godot 4.6.1 with GodotJS, GodotJS's build (linux-editor-4.6.1-qjs-ng.zip, from GodotJS v1.1.0.beta1-4.6.1); raea's build: https://x/godot-4.6.1-raea-linux-x86_64.zip didn't download");
}
#[test]
fn a_platform_godotjs_doesnt_build_for_is_told_to_bring_its_own() {
for (os, arch) in [("linux", "aarch64"), ("windows", "aarch64"), ("freebsd", "x86_64")] {
let e = pins_for(os, arch).err().unwrap_or_default();
assert!(e.contains("github.com/godotjs/GodotJS") && e.contains("git config --global raea.godot PATH"), "{os} {arch}: {e}");
}
}
#[test]
fn unzip_drops_the_top_folder() {
let base = std::env::temp_dir().join(format!("raea-godot-unzip-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(&base).unwrap();
let zf = base.join("a.zip");
let mut w = zip::ZipWriter::new(std::fs::File::create(&zf).unwrap());
let o = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
w.add_directory("top/", o).unwrap();
w.start_file("top/Godot.app/Contents/MacOS/Godot", o).unwrap();
std::io::Write::write_all(&mut w, b"binary").unwrap();
w.finish().unwrap();
unzip(&zf, &base.join("out")).unwrap();
assert_eq!(std::fs::read(base.join("out/Godot.app/Contents/MacOS/Godot")).unwrap(), b"binary");
let _ = std::fs::remove_dir_all(&base);
}
}
+358
View File
@@ -0,0 +1,358 @@
//! `raea godot run SCRIPT.ts [--project DIR] [--window] [--movie FILE [--fps N] [--frames N]] [--scene res://X.tscn] [--size WxH]
//! [--timeout S] [ARGS...]`:
//! a TypeScript script against Godot's whole API (raea/godot, sdk/godot). raea's bundler makes one CommonJS file of the
//! script, with GodotJS's modules ("godot", "godot.annotations", ...) aliased to sdk/godot/src/shim's stand-ins, which
//! read GodotJS's own when the script runs. It goes into the project's .godot/raea/<pid>/ as run.js, beside
//! sdk/godot/src/host/main.js, which Godot loads as its main loop (--script): main.js calls the script's default export
//! with the SceneTree and ARGS, then quits. The script runs in Godot, on GodotJS's engine (JavaScriptCore on the Mac,
//! QuickJS elsewhere). --movie is Godot's Movie Maker: each frame drawn and written at a fixed rate, offline, in a window.
use std::io::{BufRead, BufReader, Read};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
type R<T> = Result<T, String>;
/// GodotJS's modules a script may import, each with its stand-in in sdk/godot/src/shim.
const MODULES: [(&str, &str); 5] = [("godot", "godot.js"), ("godot.annotations", "annotations.js"), ("godot-jsb", "jsb.js"), ("godot.lib.api", "lib-api.js"), ("godot.worker", "worker.js")];
struct Opts {
script: PathBuf,
project: Option<PathBuf>,
window: bool,
timeout: f64,
/// Godot's Movie Maker: every frame written to this file (NAME.png numbered, or .avi), at a fixed frame rate
movie: Option<PathBuf>,
fps: u32,
size: Option<String>,
/// Godot quits after this many frames (--quit-after), not when the script returns: a shot's length (GD11)
frames: Option<u32>,
/// a scene of the project added to the tree before the script runs, playing as it would in the game (GD11)
scene: Option<String>,
rest: Vec<String>,
}
fn opts(args: &[String]) -> R<Opts> {
let script = args.get(2).ok_or("raea godot run SCRIPT.ts [--project DIR] [--window] [--movie FILE [--fps N] [--frames N]] [--scene res://X.tscn] [--size WxH] [--timeout S] [ARGS...]")?;
// no script, only flags: the project's --scene plays with nothing of yours added (sdk/godot/src/host/none.ts)
let bare = script.starts_with("--");
let script = if bare { raea_io_home::home().join("sdk/godot/src/host/none.ts") } else { PathBuf::from(script).canonicalize().map_err(|e| format!("{script}: {e}"))? };
let mut o = Opts { script, project: None, window: false, timeout: 3600.0, movie: None, fps: 30, size: None, frames: None, scene: None, rest: Vec::new() };
let mut it = args[if bare { 2 } else { 3 }..].iter();
while let Some(a) = it.next() {
match a.as_str() {
"--project" => o.project = Some(PathBuf::from(it.next().ok_or("--project needs a folder")?)),
"--window" => o.window = true,
"--timeout" => o.timeout = it.next().and_then(|s| s.parse().ok()).ok_or("--timeout needs seconds")?,
"--movie" => o.movie = Some(std::path::absolute(it.next().ok_or("--movie needs a file (frames.png or film.avi)")?).map_err(|e| e.to_string())?),
"--fps" => o.fps = it.next().and_then(|s| s.parse().ok()).filter(|n| *n > 0).ok_or("--fps needs frames a second")?,
"--frames" => o.frames = Some(it.next().and_then(|s| s.parse().ok()).filter(|n| *n > 0).ok_or("--frames needs a number of frames")?),
"--scene" => o.scene = Some(it.next().filter(|s| s.starts_with("res://")).ok_or("--scene needs a scene of the project, res://PATH.tscn")?.clone()),
"--size" => {
let s = it.next().filter(|s| s.split_once('x').is_some_and(|(w, h)| w.parse::<u32>().is_ok() && h.parse::<u32>().is_ok()));
o.size = Some(s.ok_or("--size needs WxH")?.clone());
}
// everything after -- is the script's, flags too
"--" => o.rest.extend(it.by_ref().cloned()),
_ => o.rest.push(a.clone()),
}
}
if bare && o.scene.is_none() {
return Err("raea godot run without a script plays a scene: give --scene res://PATH.tscn (and --project DIR)".into());
}
Ok(o)
}
/// The nearest folder at or above `from` with a project.godot.
fn nearest_project(from: &Path) -> Option<PathBuf> {
from.ancestors().find(|d| d.join("project.godot").is_file()).map(Path::to_path_buf)
}
/// The script's bundle at `out`: its module as M on globalThis.__raea_godot_main, GodotJS's modules aliased.
fn bundle(script: &Path, out: &Path) -> R<()> {
let shim = raea_io_home::home().join("sdk/godot/src/shim");
let entry = format!("import * as M from {:?};\n(globalThis as any).__raea_godot_main = M;\n", dunce::simplified(script).display().to_string());
let aliases: Vec<String> = MODULES.iter().map(|(m, f)| format!("{m}={}", shim.join(f).display())).collect();
let mut extra: Vec<&str> = Vec::new();
for a in &aliases {
extra.extend(["--alias", a.as_str()]);
}
raea_runtime_bundle::bundle_entry(&entry, out, &extra)
}
/// One line of Godot's output as raea prints it: GodotJS's console prefix gone, and what every run prints dropped:
/// Godot's banner and the blank line after it, the JavaScriptCore build's note that it has no promise-rejection hook,
/// and the leaks reported at exit (GodotJS 1.1's values, Godot's RIDs and objects the script left: harmless once it
/// has quit; each with its "at:" line). It also notes when a callback of the script threw: GodotJS prints the
/// exception, its stack and an "at: _call" line, and Godot carries on, so the run is stopped (`threw`).
pub(crate) struct Clean {
skip_at: bool,
skip_blank: bool,
in_throw: bool,
pub(crate) threw: bool,
}
impl Clean {
pub(crate) fn new() -> Self {
Clean { skip_at: false, skip_blank: false, in_throw: false, threw: false }
}
pub(crate) fn line(&mut self, l: &str) -> Option<String> {
let t = l.trim_start();
if t.contains("[jsb][Error] exception thrown in function") {
self.in_throw = true;
} else if self.in_throw && t.starts_with("at: _call (modules/GodotJS/") {
self.in_throw = false;
self.threw = true;
}
let (at, blank) = (std::mem::take(&mut self.skip_at), std::mem::take(&mut self.skip_blank));
if (at && t.starts_with("at: ")) || (blank && t.is_empty()) {
return None;
}
let exit_leak = t.contains(" leaked") && (t.contains("RID") || t.contains("ObjectDB"));
if t.contains("variant pool leaked") || t.contains("Pages in use exist at exit in PagedAllocator") || exit_leak {
self.skip_at = true;
return None;
}
if t.starts_with("Godot Engine v") && t.contains("godotengine.org") {
self.skip_blank = true;
return None;
}
if t.contains("SetPromiseRejectCallback is not supported") {
return None;
}
Some(l.strip_prefix("[JS] ").unwrap_or(l).to_string())
}
}
fn forward(from: impl Read + Send + 'static, err: bool, threw: Arc<AtomicBool>) -> std::thread::JoinHandle<()> {
std::thread::spawn(move || {
let mut c = Clean::new();
for l in BufReader::new(from).lines().map_while(Result::ok) {
if let Some(l) = c.line(&l) {
if err { eprintln!("{l}") } else { println!("{l}") }
}
if c.threw {
threw.store(true, Ordering::SeqCst);
}
}
})
}
/// The window size Godot's Movie Maker records: the project's display/window/size/viewport_width and _height
/// (Godot's own --resolution sizes the window, not the movie), 1152x648 when it sets none.
fn project_size(project_godot: &str) -> (u32, u32) {
let mut size = (1152, 648);
let mut display = false;
for l in project_godot.lines().map(str::trim) {
if l.starts_with('[') {
display = l == "[display]";
} else if display {
let Some((key, v)) = l.split_once('=') else { continue };
match (key.trim(), v.trim().parse::<u32>()) {
("window/size/viewport_width", Ok(w)) => size.0 = w,
("window/size/viewport_height", Ok(h)) => size.1 = h,
_ => {}
}
}
}
size
}
fn parse_size(s: &str) -> Option<(u32, u32)> {
let (w, h) = s.split_once('x')?;
Some((w.parse().ok()?, h.parse().ok()?))
}
/// `raea godot run ...`.
pub fn run(args: &[String]) -> R<String> {
let o = opts(args)?;
let bin = crate::godot::binary()?;
let home = raea_io_home::home();
let host = home.join("sdk/godot/src/host/main.js");
if !host.is_file() {
return Err(format!("{} is missing: this raea's install has no sdk/godot", host.display()));
}
// the project: --project, the nearest project.godot above the script, else an empty one for this run
let found = match &o.project {
Some(p) => Some(p.canonicalize().map_err(|e| format!("{}: {e}", p.display()))?),
None => nearest_project(o.script.parent().unwrap_or(Path::new("."))),
};
let temp = std::env::temp_dir().join(format!("raea-godot-{}", std::process::id()));
let project = match found {
Some(p) if p.join("project.godot").is_file() => p,
Some(p) => return Err(format!("{} has no project.godot", p.display())),
None => {
std::fs::create_dir_all(&temp).map_err(|e| e.to_string())?;
// --size is the window's size, which is what Movie Maker records
let display = match o.size.as_deref().and_then(parse_size) {
Some((w, h)) => format!("\n[display]\nwindow/size/viewport_width={w}\nwindow/size/viewport_height={h}\n"),
None => String::new(),
};
let text = format!("config_version=5\n\n[application]\nconfig/name=\"raea godot run\"\n{display}");
std::fs::write(temp.join("project.godot"), text).map_err(|e| e.to_string())?;
temp.clone()
}
};
// a project's own movie is its window's size: say so rather than record another one
if let (Some(_), Some(want), true) = (&o.movie, o.size.as_deref().and_then(parse_size), project != temp) {
let has = project_size(&std::fs::read_to_string(project.join("project.godot")).unwrap_or_default());
if has != want {
return Err(format!(
"Godot's Movie Maker records {}'s window, {}x{}, not --size {}x{}: set display/window/size/viewport_width and _height in its project.godot",
project.display(), has.0, has.1, want.0, want.1
));
}
}
// a project Godot never opened has its assets unimported, so its scenes wouldn't load: import them first
if project != temp && !project.join(".godot").is_dir() {
let s = Command::new(&bin).args(["--headless", "--path"]).arg(&project).arg("--import").stdout(Stdio::null()).stderr(Stdio::null()).status().map_err(|e| e.to_string())?;
if !s.success() {
return Err(format!("Godot couldn't import {}'s assets (godot --headless --import)", project.display()));
}
}
let pid = std::process::id();
let work = project.join(format!(".godot/raea/{pid}"));
std::fs::create_dir_all(&work).map_err(|e| format!("{}: {e}", work.display()))?;
let ran = (|| {
std::fs::copy(&host, work.join("main.js")).map_err(|e| format!("{}: {e}", host.display()))?;
bundle(&o.script, &work.join("run.js"))?;
let mut cmd = Command::new(&bin);
// a movie is drawn, so it needs the window; headless Godot draws nothing
if let Some(m) = &o.movie {
if let Some(d) = m.parent() {
std::fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?;
}
// on top: macOS stops drawing a window other windows cover, and Movie Maker then writes its last frame again
cmd.arg("--write-movie").arg(m).arg("--fixed-fps").arg(o.fps.to_string()).arg("--always-on-top");
} else if !o.window {
cmd.arg("--headless");
}
if let Some(s) = &o.size {
cmd.arg("--resolution").arg(s);
}
// a set length: Godot stops after it, and main.js doesn't quit when the script returns
if let Some(n) = o.frames {
cmd.arg("--quit-after").arg(n.to_string()).env("RAEA_GODOT_HOLD", "1");
}
if let Some(sc) = &o.scene {
cmd.env("RAEA_GODOT_SCENE", sc);
}
cmd.arg("--path").arg(&project).arg("--script").arg(format!("res://.godot/raea/{pid}/main.js")).arg("--").args(&o.rest);
cmd.env("RAEA_GODOT_LOADED", work.join("loaded"));
// Godot runs in the project's folder: raea/godot's cwd() and resolve() read where raea was run from
if let Ok(here) = std::env::current_dir() {
cmd.env("RAEA_CWD", here);
}
let mut child = cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().map_err(|e| format!("{}: {e}", bin.display()))?;
let threw = Arc::new(AtomicBool::new(false));
let outs = [forward(child.stdout.take().unwrap(), false, threw.clone()), forward(child.stderr.take().unwrap(), true, threw.clone())];
let deadline = Instant::now() + Duration::from_secs_f64(o.timeout);
let status = loop {
if let Some(s) = child.try_wait().map_err(|e| e.to_string())? {
break Ok(s);
}
// a callback that threw leaves Godot running on a broken script: stop it, as main.js does when main() throws
if threw.load(Ordering::SeqCst) {
let _ = child.kill();
let _ = child.wait();
break Err(format!("{} threw (above); Godot was stopped", o.script.display()));
}
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
break Err(format!("{} didn't finish in {} s (--timeout); Godot was stopped", o.script.display(), o.timeout));
}
std::thread::sleep(Duration::from_millis(20));
};
for t in outs {
let _ = t.join();
}
status
})();
// main.js writes it once the script has loaded: Godot exits 0 when it couldn't load the script at all
let loaded = work.join("loaded").is_file();
let _ = std::fs::remove_dir_all(&work);
if project == temp {
let _ = std::fs::remove_dir_all(&temp);
}
let status = ran?;
if !loaded {
return Err(format!("Godot couldn't load {} (GodotJS's errors above)", o.script.display()));
}
match status.code() {
Some(0) => Ok(String::new()),
Some(c) => Err(format!("{} ended with exit {c}", o.script.display())),
None => Err(format!("Godot stopped running {} ({status})", o.script.display())),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn clean_keeps_the_script_and_drops_the_exit_noise() {
let mut c = Clean::new();
let lines = [
"Godot Engine v4.6.1.stable.gh.14d19694e - https://godotengine.org",
"",
"[jsc][Log] SetPromiseRejectCallback is not supported",
"[JS] PASS 3",
"",
"WARNING: [jsb][Warning] variant pool leaked",
" at: ~VariantAllocator (modules/GodotJS/bridge/../impl/jsc/../../internal/jsb_variant_allocator.h:43)",
"ERROR: Pages in use exist at exit in PagedAllocator: 7Variant",
" at: ~PagedAllocator (./core/templates/paged_allocator.h:169)",
"ERROR: a real error",
" at: somewhere (file.cpp:1)",
];
let kept: Vec<String> = lines.iter().filter_map(|l| c.line(l)).collect();
assert_eq!(kept, ["PASS 3", "", "ERROR: a real error", " at: somewhere (file.cpp:1)"]);
for l in [
"WARNING: 3 RIDs of type \"CanvasItem\" were leaked.",
" at: _free_rids (servers/rendering/renderer_canvas_cull.cpp:2678)",
"WARNING: ObjectDB instances leaked at exit (run with --verbose for details).",
" at: cleanup (core/object/object.cpp:2378)",
] {
assert_eq!(c.line(l), None, "{l}");
}
assert!(!c.threw);
}
#[test]
fn a_callback_that_threw_is_noted_once_its_stack_is_out() {
let mut c = Clean::new();
let lines = [
"ERROR: [jsb][Error] exception thrown in function:",
"undefined is not an object (evaluating 'this.logo.position')",
"_process@/tmp/p/.godot/raea/1/run.js:1575:14",
];
for l in lines {
assert!(c.line(l).is_some());
assert!(!c.threw);
}
assert!(c.line(" at: _call (modules/GodotJS/bridge/jsb_environment.cpp:1737)").is_some());
assert!(c.threw);
}
#[test]
fn movie_size_is_the_projects_window() {
assert_eq!(project_size("config_version=5\n"), (1152, 648));
let p = "[application]\nconfig/name=\"x\"\n\n[display]\nwindow/size/viewport_width=1920\nwindow/size/viewport_height=1080\n";
assert_eq!(project_size(p), (1920, 1080));
assert_eq!(project_size("[rendering]\nwindow/size/viewport_width=10\n"), (1152, 648));
assert_eq!(parse_size("960x540"), Some((960, 540)));
assert_eq!(parse_size("960"), None);
}
#[test]
fn the_nearest_project_is_above_the_script() {
let base = std::env::temp_dir().join(format!("raea-godot-near-{}", std::process::id()));
std::fs::create_dir_all(base.join("scripts/deep")).unwrap();
std::fs::write(base.join("project.godot"), "").unwrap();
assert_eq!(nearest_project(&base.join("scripts/deep")), Some(base.clone()));
let _ = std::fs::remove_dir_all(&base);
}
}
+58
View File
@@ -0,0 +1,58 @@
//! The verbs that script other engines from TypeScript: Blender (`raea setup blender`, `raea blender run SCRIPT.py|.ts`;
//! finding and setting Blender up is apps/tools/src/blender.rs) and Godot with GodotJS (`raea setup godot`,
//! `raea godot run|types|open`; sdk/blender and sdk/godot are their TypeScript sides).
/// the Blender a TypeScript script drives (`raea blender run SCRIPT.ts`, sdk/blender)
pub mod blender_bridge;
/// `raea blender run SCRIPT.ts`: the script on raea's engine, its batches posted to the bridge's Blender
pub mod blender_ts;
/// `raea setup godot`, `raea godot types` and `raea godot open`: Godot with GodotJS (sdk/godot)
pub mod godot;
/// `raea godot run SCRIPT.ts`: a TypeScript script in Godot through GodotJS
pub mod godot_run;
/// `raea blender shot`, `raea godot shot`: a shot's frames drawn by Blender or Godot (<BlenderShot>, <GodotShot>)
pub mod shot;
/// `raea scene export`, `raea godot export|back`, `raea blender open|back`: a raea scene sent to Blender or Godot and back
pub mod round;
use raea_app_tools::blender;
type R<T> = Result<T, String>;
/// The CLI's verbs here, or None for any other: `setup blender|godot`, `blender ...` and `godot ...`.
pub fn cli(args: &[String]) -> Option<R<String>> {
let second = args.get(1).map(String::as_str);
Some(match (args.first()?.as_str(), second) {
("setup", Some("blender")) => blender::setup(&args[2..]),
("setup", Some("godot")) => godot::setup(&args[2..]),
("blender", Some("run")) if args.get(2).is_some_and(|s| blender_bridge::is_ts(s)) => blender_ts::run(args),
("blender", Some("shot")) => shot::blender(args),
("godot", Some("shot")) => shot::godot(args),
("scene", Some("export")) => round::scene_export(args),
("godot", Some("export")) => round::godot_export(args),
("godot", Some("back")) => round::godot_back(args),
("blender", Some("open")) => round::blender_open(args),
("blender", Some("back")) => round::blender_back(args),
("blender", _) => blender::blender(args),
("godot", _) => godot::godot(args),
_ => return None,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn args(s: &str) -> Vec<String> {
s.split_whitespace().map(str::to_string).collect()
}
// other verbs pass through untouched, and a bare `godot` or `blender` gets its usage, not a run
#[test]
fn takes_only_its_verbs() {
assert!(cli(&args("setup audio")).is_none());
assert!(cli(&args("render edit.tsx")).is_none());
assert!(cli(&[]).is_none());
assert!(cli(&args("godot")).unwrap().unwrap_err().contains(godot::USAGE));
}
}
+146
View File
@@ -0,0 +1,146 @@
//! A raea scene sent to Blender or Godot and its changes read back (docs/blender.feature BL37-BL39, docs/godot.feature
//! GD12-GD13): the verbs, running Blender (sdk/blender/src/scene.ts) and Godot (sdk/godot/src/host/back.ts) on what
//! raea-app-interchange writes and compares.
//! raea scene export EDIT.tsx -o DIR [--composition ID] [--frame N | --at A-B]
//! raea godot export EDIT.tsx -o DIR [--composition ID] [--frame N | --at A-B]
//! raea godot back DIR [--json]
//! raea blender open EDIT.tsx [--frame N | --at A-B] [-o DIR] [--no-window] | FILE.blend|.glb|.gltf|.obj|.fbx
//! raea blender back FILE.blend [--json]
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use raea_app_interchange::{back, export, godot};
use serde_json::Value;
use crate::{R, blender_ts};
pub const USAGE: &str = "raea scene export EDIT.tsx -o DIR [--composition ID] [--frame N | --at A-B] (the composition's 3D as data other tools build: DIR/scene.json, each part placed (y up, metres) with its shape, material or light, and the camera; meshes/ and models/ beside it)\n raea godot export EDIT.tsx -o DIR [--frame N | --at A-B] (the composition's 3D as a Godot project that runs: project.godot and main.tscn, each part Godot's own node, --at's frames an AnimationPlayer)\n raea godot back DIR (what changed in Godot's main.tscn since the export, as edits to the TSX at their lines; nodes added there written as media/NAME.glb; --json)\n raea blender open EDIT.tsx [--frame N | --at A-B] [-o DIR] [--no-window] | FILE.blend|.glb (the composition's 3D built in Blender, saved as DIR/NAME.blend (out/blender/NAME/ unless -o) and opened in a Blender window; a model or .blend opened as it is)\n raea blender back FILE.blend (what changed in Blender since raea blender open, as edits to the TSX at their lines; meshes made there written as media/NAME.glb; --json)";
fn flag<'a>(args: &'a [String], k: &str) -> Option<&'a String> {
args.iter().position(|a| a == k).and_then(|i| args.get(i + 1))
}
fn read_json(p: &Path) -> R<Value> {
serde_json::from_slice(&std::fs::read(p).map_err(|e| format!("{}: {e}", p.display()))?).map_err(|e| format!("{}: {e}", p.display()))
}
/// The scene export's folder for an edit: -o DIR, else out/blender/NAME/ beside it.
fn export_to(args: &[String], default_sub: &str) -> R<(PathBuf, Value)> {
let mut a = args.to_vec();
if flag(args, "-o").is_none() {
let edit = PathBuf::from(args.get(2).ok_or(USAGE)?);
let stem = edit.file_stem().and_then(|s| s.to_str()).unwrap_or("scene").to_string();
let dir = edit.parent().unwrap_or(Path::new(".")).join("out").join(default_sub).join(&stem);
a.extend(["-o".into(), dir.to_string_lossy().into_owned()]);
}
export::export(&a)
}
/// The edits from scene.json in `dir` to what `now` holds, said (or as JSON).
fn compared(dir: &Path, now: &Path, json: bool) -> R<String> {
let sent = read_json(&dir.join("scene.json"))?;
let held = read_json(now)?;
let _ = std::fs::remove_file(now);
let edits = back::compare(&sent, &held);
let tsx = PathBuf::from(sent["from"].as_str().unwrap_or(""));
Ok(if json { serde_json::to_string_pretty(&edits).unwrap_or_default() } else { back::said(&edits, &tsx) })
}
/// The project's media folder for models made in Blender or Godot: beside the edit the scene came from.
fn media_of(dir: &Path) -> R<PathBuf> {
let sent = read_json(&dir.join("scene.json"))?;
let tsx = PathBuf::from(sent["from"].as_str().ok_or("scene.json names no edit")?);
Ok(tsx.parent().unwrap_or(Path::new(".")).join("media"))
}
pub fn scene_export(args: &[String]) -> R<String> {
let (out, v) = export::export(args)?;
Ok(export::said(&out, &v))
}
pub fn godot_export(args: &[String]) -> R<String> {
let (out, v) = export_to(args, "godot")?;
let name = Path::new(&args[2]).file_stem().and_then(|s| s.to_str()).unwrap_or("raea").to_string();
let said = godot::project(&out, &v, &name)?;
let left = export::said(&out, &v);
let left = left.split_once("; ").map(|(_, l)| format!("; {l}")).unwrap_or_default();
Ok(format!("a Godot project in {}: {said}{left}\nrun it: raea godot run SCRIPT.ts --project {0} (or --movie); edit it: raea godot open {0}; then raea godot back {0}", out.display()))
}
pub fn godot_back(args: &[String]) -> R<String> {
let dir = PathBuf::from(args.get(2).ok_or(USAGE)?).canonicalize().map_err(|e| format!("{}: {e}", args[2]))?;
let media = media_of(&dir)?;
let now = dir.join(".raea-now.json");
let script = raea_io_home::home().join("sdk/godot/src/host/back.ts");
let run: Vec<String> = ["godot", "run"].iter().map(|s| s.to_string())
.chain([script.to_string_lossy().into_owned(), "--project".into(), dir.to_string_lossy().into_owned(), "--".into(), now.to_string_lossy().into_owned(), media.to_string_lossy().into_owned()])
.collect();
crate::godot_run::run(&run)?;
compared(&dir, &now, args.iter().any(|a| a == "--json"))
}
/// A Blender window on `file`, left running as the person's.
fn window(file: &Path, python: Option<String>) -> R<()> {
let (bin, _) = raea_app_tools::blender::find().ok_or("no Blender: raea setup blender finds or downloads one")?;
let mut cmd = Command::new(&bin);
match python {
Some(code) => cmd.arg("--python-expr").arg(code),
None => cmd.arg(file),
};
cmd.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn().map_err(|e| format!("{}: {e}", bin.display()))?;
Ok(())
}
pub fn blender_open(args: &[String]) -> R<String> {
let src = args.get(2).ok_or(USAGE)?;
let path = std::path::absolute(src).map_err(|e| e.to_string())?;
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();
match ext.as_str() {
"blend" => {
window(&path, None)?;
return Ok(format!("APPLIED Blender is opening {}", path.display()));
}
"glb" | "gltf" | "obj" | "fbx" => {
let op = match ext.as_str() {
"obj" => "bpy.ops.wm.obj_import",
"fbx" => "bpy.ops.import_scene.fbx",
_ => "bpy.ops.import_scene.gltf",
};
let code = format!("import bpy\nbpy.ops.wm.read_homefile(use_empty=True)\n{op}(filepath={:?})", path.to_string_lossy());
window(&path, Some(code))?;
return Ok(format!("APPLIED Blender is opening {}", path.display()));
}
_ => {}
}
let (dir, v) = export_to(args, "blender")?;
let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("scene");
let blend = dir.join(format!("{stem}.blend"));
let call = format!("build({:?}, {:?})", dir.to_string_lossy(), blend.to_string_lossy());
let entry = format!("import {{ build }} from \"@raea/blender/scene\";\nconst call = (globalThis as any).__raea_call;\nPromise.resolve().then(() => {call}){}\n", blender_ts::CLOSE);
let code = blender_ts::session(&entry, None, &[], 900.0)?;
if code != 0 || !blend.is_file() {
return Err(format!("Blender couldn't build {} (above)", dir.join("scene.json").display()));
}
if !args.iter().any(|a| a == "--no-window") {
window(&blend, None)?;
}
Ok(format!("{}\nbuilt in Blender: {}; after changing it there, save and run: raea blender back {}", export::said(&dir, &v), blend.display(), blend.display()))
}
pub fn blender_back(args: &[String]) -> R<String> {
let blend = PathBuf::from(args.get(2).filter(|a| a.ends_with(".blend")).ok_or(USAGE)?).canonicalize().map_err(|e| format!("{}: {e}", args[2]))?;
let dir = blend.parent().ok_or("the .blend's folder")?.to_path_buf();
if !dir.join("scene.json").is_file() {
return Err(format!("{} has no scene.json beside it: raea blender back reads a .blend raea blender open made", blend.display()));
}
let media = media_of(&dir)?;
let now = dir.join(".raea-now.json");
let call = format!("readBack({:?}, {:?})", now.to_string_lossy(), media.to_string_lossy());
let entry = format!("import {{ readBack }} from \"@raea/blender/scene\";\nconst call = (globalThis as any).__raea_call;\nPromise.resolve().then(() => {call}){}\n", blender_ts::CLOSE);
let code = blender_ts::session(&entry, Some(&blend), &[], 900.0)?;
if code != 0 {
return Err(format!("Blender couldn't read {} (above)", blend.display()));
}
compared(&dir, &now, args.iter().any(|a| a == "--json"))
}
+231
View File
@@ -0,0 +1,231 @@
//! A shot's frames made by another engine, numbered from DIR/0000.png (docs/blender.feature BL36, docs/godot.feature
//! GD11): what <BlenderShot> and <GodotShot> show, made through their native calls (runtime/react's scene/shots.rs).
//! raea blender shot SCRIPT.ts|FILE.blend -o DIR --frames N [--fps F] [--size WxH] [--file FILE.blend]
//! [--engine eevee|cycles|workbench] [--samples S] [--transparent] [--timeout S] [-- ARGS]
//! raea godot shot SCRIPT.ts|res://SCENE.tscn [--project DIR] -o DIR --frames N [--fps F] [--size WxH] [--scene res://X]
//! [--timeout S] [-- ARGS]
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use serde_json::json;
use crate::{R, blender_ts};
pub const BLENDER_USAGE: &str = "raea blender shot SCRIPT.ts|FILE.blend -o DIR --frames N [--fps F] [--size WxH] [--file FILE.blend] [--engine eevee|cycles|workbench] [--samples S] [--transparent] [--timeout S] [-- ARGS]";
/// Both, as raea's help says them.
pub const USAGE: &str = "raea blender shot SCRIPT.ts|FILE.blend -o DIR --frames N [--fps F] [--size WxH] [--engine eevee|cycles|workbench] [--samples S] [--transparent] (a shot's frames rendered by Blender, DIR/0000.png on: a raea/blender script's scene or a .blend's animation; what <BlenderShot> shows, from raea/blender/shot)\n raea godot shot SCRIPT.ts|res://SCENE.tscn [--project DIR] -o DIR --frames N [--fps F] [--size WxH] (a shot's frames recorded by Godot's Movie Maker, DIR/0000.png on, its sound as sound.wav; what <GodotShot> shows, from raea/godot/shot)";
pub const GODOT_USAGE: &str = "raea godot shot SCRIPT.ts|res://SCENE.tscn [--project DIR] -o DIR --frames N [--fps F] [--size WxH] [--scene res://X.tscn] [--timeout S] [-- ARGS]";
#[derive(Debug)]
struct Shot {
src: String,
out: PathBuf,
frames: u32,
fps: f64,
size: (u32, u32),
transparent: bool,
/// the flags that take a value, by name
flags: BTreeMap<String, String>,
rest: Vec<String>,
}
/// args[2] the source, then the flags (each taking a value but --transparent), then -- and the script's own.
fn parse(args: &[String], usage: &str) -> R<Shot> {
let src = args.get(2).filter(|a| !a.starts_with('-')).ok_or(usage)?.clone();
let (mut flags, mut rest, mut transparent) = (BTreeMap::new(), Vec::new(), false);
let mut it = args[3..].iter();
while let Some(a) = it.next() {
match a.as_str() {
"--" => rest.extend(it.by_ref().cloned()),
"--transparent" => transparent = true,
f if f.starts_with('-') => _ = flags.insert(a.clone(), it.next().ok_or_else(|| format!("{a} needs a value: {usage}"))?.clone()),
_ => return Err(format!("{a}: not a flag of this verb: {usage}")),
}
}
let out = std::path::absolute(flags.get("-o").ok_or(usage)?).map_err(|e| e.to_string())?;
let frames = flags.get("--frames").and_then(|n| n.parse().ok()).filter(|n| *n > 0).ok_or("--frames needs a number of frames over 0")?;
let fps: f64 = match flags.get("--fps") {
Some(f) => f.parse().ok().filter(|f: &f64| *f > 0.0).ok_or("--fps needs frames a second")?,
None => 30.0,
};
let size = match flags.get("--size") {
Some(s) => s.split_once('x').and_then(|(w, h)| Some((w.parse().ok()?, h.parse().ok()?))).ok_or("--size needs WxH")?,
None => (1920, 1080),
};
Ok(Shot { src, out, frames, fps, size, transparent, flags, rest })
}
/// The frames a run wrote in `dir` (Blender's 0001.png on, Godot's f00000000.png on), by their number: the first
/// `n` renamed 0000.png on, any past them removed. Too few is the run's failure.
pub(crate) fn renumber(dir: &Path, n: u32) -> R<()> {
let number = |p: &Path| p.file_stem()?.to_str()?.trim_start_matches(|c: char| !c.is_ascii_digit()).parse::<u64>().ok();
let mut made: Vec<(u64, PathBuf)> = std::fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|e| e == "png"))
.filter_map(|p| Some((number(&p)?, p)))
.collect();
made.sort();
if made.len() < n as usize {
return Err(format!("{} frames were made of the {n} asked for ({})", made.len(), dir.display()));
}
// through a name of their own first, so 0001.png -> 0000.png never meets a frame not yet moved
let mut moved = Vec::new();
for (i, (_, p)) in made.iter().enumerate() {
if i < n as usize {
let tmp = dir.join(format!("raea-{i:06}.tmp"));
std::fs::rename(p, &tmp).map_err(|e| format!("{}: {e}", p.display()))?;
moved.push((i, tmp));
} else {
let _ = std::fs::remove_file(p);
}
}
for (i, tmp) in moved {
std::fs::rename(&tmp, dir.join(format!("{i:04}.png"))).map_err(|e| e.to_string())?;
}
Ok(())
}
fn fresh(out: &Path) -> R<()> {
let _ = std::fs::remove_dir_all(out);
std::fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))
}
/// `raea blender shot ...`: the script's default export run (or the .blend opened), then sdk/blender's shoot().
pub fn blender(args: &[String]) -> R<String> {
let s = parse(args, BLENDER_USAGE)?;
let src = std::path::absolute(&s.src).map_err(|e| e.to_string())?;
let is_blend = s.src.ends_with(".blend");
let file = if is_blend { Some(src.clone()) } else { s.flags.get("--file").map(PathBuf::from) };
if let Some(f) = file.as_ref().filter(|f| !f.is_file()) {
return Err(format!("{}: no such .blend", f.display()));
}
fresh(&s.out)?;
let mut opts = json!({ "out": s.out.to_string_lossy(), "frames": s.frames, "fps": s.fps, "width": s.size.0, "height": s.size.1, "transparent": s.transparent });
if let Some(e) = s.flags.get("--engine").map(String::as_str) {
opts["engine"] = json!(e);
}
if let Some(n) = s.flags.get("--samples").map(String::as_str) {
opts["samples"] = json!(n.parse::<u32>().map_err(|_| "--samples needs a whole number")?);
}
let shoot = "import { shoot } from \"@raea/blender/shoot\";\nconst call = (globalThis as any).__raea_call;\n";
let entry = if is_blend {
format!("{shoot}Promise.resolve().then(() => shoot({opts})){}\n", blender_ts::CLOSE)
} else {
let ts = src.canonicalize().map_err(|e| format!("{}: {e}", s.src))?;
format!("import * as M from {};\n{shoot}{}.then(() => shoot({opts})){}\n", blender_ts::spec(&ts), blender_ts::DEFAULT, blender_ts::CLOSE)
};
let mut rest = s.rest.clone();
let secs = s.flags.get("--timeout").map(String::as_str).and_then(|t| t.parse().ok()).unwrap_or_else(|| blender_ts::timeout(&mut rest));
let code = blender_ts::session(&entry, file.as_deref(), &rest, secs)?;
if code != 0 {
return Err(format!("{} ended with exit {code}", s.src));
}
renumber(&s.out, s.frames)?;
Ok(format!("{} frames by Blender in {}", s.frames, s.out.display()))
}
/// Godot's window size for the shot: an override.cfg in the project (Godot reads it over project.godot) for the
/// length of the run, since Movie Maker records the window the project opens; put back as it was after.
struct Override {
path: PathBuf,
before: Option<Vec<u8>>,
}
impl Override {
fn set(project: &Path, (w, h): (u32, u32)) -> R<Override> {
let path = project.join("override.cfg");
let before = std::fs::read(&path).ok();
let mut text = before.as_deref().map(String::from_utf8_lossy).unwrap_or_default().into_owned();
text.push_str(&format!("\n[display]\nwindow/size/viewport_width={w}\nwindow/size/viewport_height={h}\n"));
std::fs::write(&path, text).map_err(|e| format!("{}: {e}", path.display()))?;
Ok(Override { path, before })
}
}
impl Drop for Override {
fn drop(&mut self) {
let _ = match &self.before {
Some(b) => std::fs::write(&self.path, b),
None => std::fs::remove_file(&self.path),
};
}
}
/// `raea godot shot ...`: `raea godot run` with --movie, --frames and --scene, its frames renumbered; the sound Movie
/// Maker writes beside them kept as sound.wav.
pub fn godot(args: &[String]) -> R<String> {
let s = parse(args, GODOT_USAGE)?;
let none = raea_io_home::home().join("sdk/godot/src/host/none.ts");
let (script, scene) = match s.src.strip_prefix("res://") {
Some(_) => (none.to_string_lossy().into_owned(), Some(s.src.clone())),
None => (s.src.clone(), s.flags.get("--scene").cloned()),
};
fresh(&s.out)?;
let mut run = vec!["godot".to_string(), "run".into(), script, "--movie".into(), s.out.join("f.png").to_string_lossy().into_owned()];
run.extend(["--fps".into(), s.fps.round().to_string(), "--frames".into(), s.frames.to_string()]);
let _over = match s.flags.get("--project").map(String::as_str) {
Some(p) => {
run.extend(["--project".into(), p.to_string()]);
Some(Override::set(Path::new(p), s.size)?)
}
None => {
run.extend(["--size".into(), format!("{}x{}", s.size.0, s.size.1)]);
None
}
};
if let Some(sc) = scene {
run.extend(["--scene".into(), sc]);
}
if let Some(t) = s.flags.get("--timeout").map(String::as_str) {
run.extend(["--timeout".into(), t.to_string()]);
}
if !s.rest.is_empty() {
run.push("--".into());
run.extend(s.rest.iter().cloned());
}
crate::godot_run::run(&run)?;
let wav = s.out.join("f.wav");
if wav.is_file() {
let _ = std::fs::rename(&wav, s.out.join("sound.wav"));
}
renumber(&s.out, s.frames)?;
Ok(format!("{} frames by Godot in {}", s.frames, s.out.display()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn frames_are_numbered_from_zero_by_their_own_numbers() {
let d = std::env::temp_dir().join(format!("raea-shot-renumber-{}", std::process::id()));
fresh(&d).unwrap();
for f in ["0001.png", "0002.png", "0003.png", "10000.png", "notes.txt"] {
std::fs::write(d.join(f), f).unwrap();
}
renumber(&d, 3).unwrap();
assert_eq!(std::fs::read_to_string(d.join("0000.png")).unwrap(), "0001.png");
assert_eq!(std::fs::read_to_string(d.join("0002.png")).unwrap(), "0003.png");
assert!(!d.join("10000.png").exists() && !d.join("0003.png").exists() && d.join("notes.txt").exists());
// Godot's names, and too few
fresh(&d).unwrap();
for f in ["f00000000.png", "f00000001.png"] {
std::fs::write(d.join(f), f).unwrap();
}
assert!(renumber(&d, 3).unwrap_err().contains("2 frames were made of the 3"));
renumber(&d, 2).unwrap();
assert_eq!(std::fs::read_to_string(d.join("0001.png")).unwrap(), "f00000001.png");
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn a_shot_needs_its_out_and_length() {
let a = |s: &str| s.split_whitespace().map(String::from).collect::<Vec<_>>();
assert!(parse(&a("blender shot x.ts --frames 3"), BLENDER_USAGE).is_err());
assert!(parse(&a("blender shot x.ts -o d"), BLENDER_USAGE).unwrap_err().contains("--frames"));
let s = parse(&a("godot shot res://m.tscn -o d --frames 4 --size 640x360 --project p -- go"), GODOT_USAGE).unwrap();
assert_eq!((s.frames, s.size, s.flags.get("--project").map(String::as_str), s.rest.clone()), (4, (640, 360), Some("p"), vec!["go".to_string()]));
}
}
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "raea-app-fingerprint"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "`raea fingerprint` (docs/fingerprint.feature FP3a): new, bootstrap, teach, score and report, run by a resident service on localhost that keeps the encoders loaded"
[dependencies]
# the taxonomy, evidence and heads
raea-sys-fingerprint = { path = "../../systems/fingerprint" }
# scoring and the sheet, which one judges a piece, diff and profiles
raea-sys-fingerprint-use = { path = "../../systems/fingerprint-use" }
raea-sys-fingerprint-things = { path = "../../systems/fingerprint-things" }
# the encoders and the columns they make
raea-sys-columns = { path = "../../systems/columns" }
# raea check's floor on the file: its findings go in the summary, and a check wins over a head (FP4c)
raea-app-check = { path = "../check" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
anyhow = "1"
# the draws of FP0b's few-shot curves, seeded (bootstrap.rs)
fastrand = "2"
+87
View File
@@ -0,0 +1,87 @@
//! Approvals are positives (docs/fingerprint.feature FP6a): an approved cut, a picture lock, a publish or a golden
//! reference says every moment of it is clean on every axis, except where the person left a note. `raea fingerprint
//! approve FILE... [--project P]` adds a clean row on every axis ("*") for each 2 s window of each file, skipping the
//! windows within 2 s of a pinned note on that file in its project's feed (.raea/feed/*.json), since a note there may
//! name a defect. Notes aren't read into labels here; that is FP5a.
use crate::bootstrap::WIN;
use crate::flag;
use anyhow::{Result, anyhow};
use raea_sys_columns::Encoders;
use raea_sys_fingerprint::evidence::{Row, features};
use raea_sys_fingerprint::folder::Folder;
use raea_sys_fingerprint::taxonomy::Fingerprint;
use std::path::Path;
/// The seconds a note was pinned at on `file`, from every post in its project's feed that shows a file of that name
pub(crate) fn noted(file: &Path) -> Vec<f64> {
let Some(name) = file.file_name().and_then(|n| n.to_str()) else { return Vec::new() };
let Some(feed) = file.ancestors().map(|d| d.join(".raea/feed")).find(|d| d.is_dir()) else { return Vec::new() };
let mut at = Vec::new();
for e in std::fs::read_dir(feed).into_iter().flatten().flatten() {
let Ok(text) = std::fs::read_to_string(e.path()) else { continue };
let Ok(post) = serde_json::from_str::<serde_json::Value>(&text) else { continue };
let shows = post["media"].as_array().into_iter().flatten().any(|m| m["path"].as_str().is_some_and(|p| p.ends_with(name)));
if shows {
at.extend(post["notes"].as_array().into_iter().flatten().filter_map(|n| n["pin"]["t"].as_f64()));
}
}
at
}
/// The windows an approval labels clean: every WIN seconds of the piece, away from its notes
pub(crate) fn windows(dur: f64, notes: &[f64]) -> Vec<(f64, f64)> {
let n = (dur / WIN).floor() as usize;
(0..n).map(|i| (i as f64 * WIN, (i + 1) as f64 * WIN)).filter(|(a, b)| !notes.iter().any(|t| *t > a - WIN && *t < b + WIN)).collect()
}
pub(crate) fn approve(enc: &mut Encoders, dir: &Folder, fp: &Fingerprint, args: &[String], cwd: &Path, project: impl Fn(&Path) -> String) -> Result<(String, usize)> {
let files = crate::named(args, cwd)?;
if files.is_empty() {
return Err(anyhow!("which approved work? raea fingerprint approve FILE..."));
}
let mut l = dir.ledger()?;
let mut out = String::new();
let mut added = 0;
for file in &files {
let c = enc.columns(file)?;
// an approval given again replaces the last one for that media
l.retain(|r| !(r.source == "approval" && r.media == c.media));
let notes = noted(file);
let w = windows(c.dur, &notes);
for (a, b) in &w {
let row = Row {
media: c.media.clone(),
a: *a,
b: *b,
axis: "*".into(),
bad: false,
weight: 1.0,
who: fp.who.clone().unwrap_or_else(|| "me".into()),
source: "approval".into(),
project: flag(args, "--project").map_or_else(|| project(file), str::to_string),
kind: None,
region: None,
words: None,
at: 0,
pin: None,
band: None,
};
l.push(row, &features(&c, *a, *b));
}
added += w.len();
out += &format!("approved {}: {} clean windows on every axis{}\n", file.display(), w.len(), if notes.is_empty() { String::new() } else { format!(", {} noted moments left out", notes.len()) });
}
dir.write_ledger(&l)?;
Ok((out, added))
}
#[cfg(test)]
mod tests {
#[test]
fn an_approval_leaves_out_the_windows_near_a_note() {
assert_eq!(super::windows(9.0, &[]), vec![(0.0, 2.0), (2.0, 4.0), (4.0, 6.0), (6.0, 8.0)]);
// a note at 5 s: the windows within 2 s of it go
assert_eq!(super::windows(12.0, &[5.0]), vec![(0.0, 2.0), (8.0, 10.0), (10.0, 12.0)]);
}
}
+281
View File
@@ -0,0 +1,281 @@
//! The bootstrap (FP4a, FP4b): known defects put into windows of the person's own real work, so the mechanical axes
//! learn from labels by construction, and the cheats each must still catch. Each source gives `per` 2 s windows
//! from 0.5 s to its end less 2.5 s (FP0b's protocol); each window gives a clean row ("*"), a row per picture and
//! sound defect, and a row per cheat. Only what the damage changed is embedded again: a freeze reuses the first
//! frame's vector, a flash re-embeds one frame, a sound defect leaves the picture alone.
//!
//! Then it measures what FP0b measured, in Rust: each axis's AUC from k = 4, 16 and 32 labelled windows a class, held
//! out by source (5 folds x 5 draws, the scaler fit on every plain row of the training sources), on its own
//! modality and on the one FP0b used; and each word head's AUC and catch rate with no labels (FP0g).
use raea_sys_fingerprint::evidence::{Ledger, Row, features, slice};
use raea_sys_fingerprint::head::{Logistic, Scaler, auc, quantile, share_over};
use raea_sys_fingerprint::taxonomy::Fingerprint;
use raea_sys_fingerprint::train::{C, folds};
use raea_sys_fingerprint::words::Words;
use anyhow::Result;
use raea_sys_columns::damage::{self, CHEATS, Noise, PICTURE, SOUND};
use raea_sys_columns::media::{self, Rgb};
use raea_sys_columns::window::Modality;
use raea_sys_columns::{Columns, Encoders, FPS};
use serde::Serialize;
use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
/// The window, seconds
pub const WIN: f64 = 2.0;
/// Sources shorter than this are skipped (FP0b's)
pub const SHORTEST: f64 = 6.0;
pub const KS: [usize; 3] = [4, 16, 32];
/// FP0b's AUC at k = 32 for each axis, on the modality it was measured on (docs/fingerprint.md FP0b, FP0g)
pub const FP0B: [(&str, Modality, f64); 11] = [
("blur", Modality::Picture, 1.00),
("dark", Modality::Picture, 0.95),
("glow", Modality::Picture, 0.80),
("flash", Modality::Change, 0.97),
("freeze", Modality::Change, 1.00),
("noise", Modality::Events, 1.00),
("dropout", Modality::Events, 0.97),
("clip", Modality::Events, 0.98),
("noise", Modality::Sound, 1.00),
("dropout", Modality::Sound, 0.99),
("clip", Modality::Sound, 1.00),
];
#[derive(Debug, Default, Serialize)]
pub struct Made {
pub sources: usize,
pub windows: usize,
pub rows: usize,
/// windows too quiet for a gap or clipping to change them, which get only the noise damage
pub quiet: usize,
pub skipped: Vec<String>,
}
/// The rows a bootstrap makes, which the next bootstrap replaces
fn made_here(r: &Row) -> bool {
matches!(r.source.as_str(), "damage" | "cheat")
}
/// A plain damage row on `axis` ("*" for the clean windows)
fn damage_on(r: &Row, axis: &str) -> bool {
r.source == "damage" && r.axis == axis
}
/// The plain damage rows on `axis`
fn damage_rows(l: &Ledger, axis: &str) -> Vec<usize> {
(0..l.rows.len()).filter(|&i| damage_on(&l.rows[i], axis)).collect()
}
/// Each defect of a sense as (kind, axis, source): the plain ones, then their disguises
fn damages(sense: &[&'static str]) -> Vec<(&'static str, &'static str, &'static str)> {
sense.iter().map(|k| (*k, *k, "damage")).chain(CHEATS.iter().filter(|c| sense.contains(&c.1)).map(|c| (c.0, c.1, "cheat"))).collect()
}
/// Below this a window is near silence: a gap or clipping changes nothing, and a row saying it does teaches noise
const QUIET_DB: f32 = -45.0;
/// The window's loudness in dB over all of it
fn loudness(pcm: &[f32]) -> f32 {
if pcm.is_empty() {
return -100.0;
}
(10.0 * (pcm.iter().map(|x| x * x).sum::<f32>() / pcm.len() as f32).max(1e-10).log10()).max(-100.0)
}
fn zeros_to(mut v: Vec<f32>, n: usize) -> Vec<f32> {
v.resize(n, 0.0);
v
}
/// The picture columns of damaged frames, embedding only frames the damage changed
fn picture_of(enc: &mut Encoders, clean: &[Rgb], sig: &[f32], look: &[f32], d: &[Rgb]) -> Result<(Vec<f32>, Vec<f32>)> {
let (sd, ld) = (sig.len() / clean.len().max(1), look.len() / clean.len().max(1));
let mut fresh: Vec<Rgb> = Vec::new();
let mut from: Vec<Result<usize, usize>> = Vec::new();
for f in d {
match clean.iter().position(|c| c == f) {
Some(j) => from.push(Ok(j)),
None => {
fresh.push(f.clone());
from.push(Err(fresh.len() - 1));
}
}
}
let (fs, fl) = if fresh.is_empty() { (Vec::new(), Vec::new()) } else { enc.picture(&fresh)? };
let (mut s, mut l) = (Vec::with_capacity(sig.len()), Vec::with_capacity(look.len()));
for f in from {
let (ss, ll, j) = match f {
Ok(j) => (sig, look, j),
Err(k) => (&fs[..], &fl[..], k),
};
s.extend_from_slice(&ss[j * sd..(j + 1) * sd]);
l.extend_from_slice(&ll[j * ld..(j + 1) * ld]);
}
Ok((s, l))
}
/// The bootstrap's rows for `files` into the ledger, replacing any it made before. `say` hears each source's progress.
pub fn rows(enc: &mut Encoders, who: &str, files: &[PathBuf], per: usize, l: &mut Ledger, say: &mut dyn FnMut(String)) -> Result<Made> {
l.retain(|r| !made_here(r));
let mut made = Made::default();
let mut noise = Noise::new(0);
for (n, file) in files.iter().enumerate() {
let dur = media::duration(file).unwrap_or(0.0);
if dur < SHORTEST {
made.skipped.push(format!("{} ({dur:.1} s, under {SHORTEST} s)", file.display()));
continue;
}
let sha = media::sha256(file)?;
let frames = media::frames(file, FPS, 0.0, dur)?;
let (p16, p48) = (media::sound(file, 16_000)?, media::sound(file, 48_000)?);
made.sources += 1;
for w in 0..per {
let t = 0.5 + (dur - 3.0) * w as f64 / (per - 1).max(1) as f64;
let i0 = (t * FPS).round() as usize;
let Some(fr) = frames.get(i0..i0 + (WIN * FPS) as usize) else { continue };
let cut = |p: &[f32], rate: f64| zeros_to(p.get((t * rate) as usize..).unwrap_or(&[]).iter().take((WIN * rate) as usize).copied().collect(), (WIN * rate) as usize);
let (w16, w48) = (cut(&p16, 16_000.0), cut(&p48, 48_000.0));
let (sig, look) = enc.picture(fr)?;
let (clap, yam) = enc.sound(&w16, &w48)?;
let clean = Columns { media: sha.clone(), dur: WIN, sig, look, clap, yam, level: media::levels(&w16, 16_000), text: Vec::new() };
let push = |l: &mut Ledger, c: &Columns, axis: &str, kind: &str, source: &str| {
let r = Row {
media: sha.clone(),
a: t,
b: t + WIN,
axis: axis.into(),
bad: axis != "*",
weight: 1.0,
who: who.into(),
source: source.into(),
project: sha[..12].to_string(),
kind: Some(kind.into()),
region: None,
words: None,
at: 0,
pin: None,
band: None,
};
l.push(r, &features(c, 0.0, WIN));
};
push(l, &clean, "*", "clean", "damage");
for (kind, axis, source) in damages(&PICTURE) {
let (sig, look) = picture_of(enc, fr, &clean.sig, &clean.look, &damage::picture(fr, kind))?;
push(l, &Columns { sig, look, ..clean.clone() }, axis, kind, source);
}
let quiet = loudness(&w16) < QUIET_DB;
made.quiet += quiet as usize;
for (kind, axis, source) in damages(&SOUND).into_iter().filter(|s| !quiet || s.1 == "noise") {
let (d16, d48) = (damage::sound(&w16, kind, 16_000, &mut noise), damage::sound(&w48, kind, 48_000, &mut noise));
let (clap, yam) = enc.sound(&d16, &d48)?;
push(l, &Columns { clap, yam, level: media::levels(&d16, 16_000), ..clean.clone() }, axis, kind, source);
}
made.windows += 1;
}
say(format!("source {}/{} {}: {} windows so far", n + 1, files.len(), file.display(), made.windows));
}
made.rows = l.rows.iter().filter(|r| made_here(r)).count();
Ok(made)
}
#[derive(Debug, Serialize)]
pub struct Curve {
pub axis: String,
pub modality: Modality,
/// AUC at each k
pub k: BTreeMap<usize, f64>,
/// FP0b's at k = 32 on this modality, and whether this run came within 0.03 of it or beat it
pub fp0b: Option<f64>,
pub holds: Option<bool>,
}
fn sample(rng: &mut fastrand::Rng, from: &[usize], k: usize) -> Vec<usize> {
let mut v = from.to_vec();
rng.shuffle(&mut v);
v.truncate(k);
v
}
/// FP0b's few-shot curve for one axis on one modality, from the bootstrap's rows
pub fn curve(l: &Ledger, axis: &str, m: Modality, rng: &mut fastrand::Rng) -> Curve {
let s = slice(m);
let row = |i: usize| &l.features(i)[s.clone()];
let plain = |i: &usize| l.rows[*i].source == "damage";
let (clean, bad) = (damage_rows(l, "*"), damage_rows(l, axis));
let projects = l.projects(&clean);
let mut k_auc = BTreeMap::new();
for k in KS {
let mut aucs = Vec::new();
for fold in folds(&projects) {
let held = |i: &usize| fold.contains(&l.rows[*i].project);
let base: Vec<&[f32]> = (0..l.rows.len()).filter(|i| plain(i) && !held(i)).map(row).collect();
let sc = Scaler::fit(&base);
let (tc, tb): (Vec<usize>, Vec<usize>) = (clean.iter().copied().filter(|i| !held(i)).collect(), bad.iter().copied().filter(|i| !held(i)).collect());
if tc.len() < k || tb.len() < k {
continue;
}
for _ in 0..5 {
let (a, b) = (sample(rng, &tc, k), sample(rng, &tb, k));
let x: Vec<&[f32]> = a.iter().chain(&b).map(|&i| row(i)).collect();
let y: Vec<bool> = (0..2 * k).map(|i| i >= k).collect();
let f = Logistic::fit(sc.clone(), &x, &y, None, C, true);
let score = |v: &Vec<usize>| -> Vec<f32> { v.iter().filter(|i| held(i)).map(|&i| f.score(row(i))).collect() };
aucs.push(auc(&score(&bad), &score(&clean)));
}
}
let ok: Vec<f64> = aucs.into_iter().filter(|a| a.is_finite()).collect();
if !ok.is_empty() {
k_auc.insert(k, ok.iter().sum::<f64>() / ok.len() as f64);
}
}
let fp0b = FP0B.iter().find(|(a, mm, _)| *a == axis && *mm == m).map(|x| x.2);
let holds = fp0b.zip(k_auc.get(&32)).map(|(want, got)| *got >= want - 0.03);
Curve { axis: axis.into(), modality: m, k: k_auc, fp0b, holds }
}
/// Every mechanical axis's curve on its own modality and on FP0b's
pub fn curves(fp: &Fingerprint, l: &Ledger) -> Vec<Curve> {
let mut rng = fastrand::Rng::with_seed(1);
let mut out = Vec::new();
for axis in PICTURE.iter().chain(&SOUND) {
let own = fp.axis(axis).map(|a| a.modality);
let mut ms: Vec<Modality> = own.into_iter().chain(FP0B.iter().filter(|x| x.0 == *axis).map(|x| x.1)).collect();
ms.dedup();
for m in ms.into_iter().collect::<BTreeSet<_>>() {
out.push(curve(l, axis, m, &mut rng));
}
}
out
}
#[derive(Debug, Serialize)]
pub struct WordScore {
pub axis: String,
/// AUC, damaged against clean windows, with no labels
pub auc: f64,
/// the share of damaged windows over the score that flags 10% of clean ones
pub caught: f64,
/// each cheat's share over that same score
pub cheats: BTreeMap<String, f64>,
}
/// Each word head on the bootstrap's windows (FP0g)
pub fn word_scores(l: &Ledger, words: &Words) -> Vec<WordScore> {
let z = |i: usize, axis: &str| words.z(axis, l.features(i));
let of = |axis: &str, pick: &dyn Fn(&Row) -> bool| -> Vec<f32> { l.rows.iter().enumerate().filter(|(_, r)| pick(r)).filter_map(|(i, _)| z(i, axis)).collect() };
let mut out = Vec::new();
for axis in PICTURE.iter().chain(&SOUND) {
if !words.axes.iter().any(|w| w.0 == *axis) {
continue;
}
let clean = of(axis, &|r| damage_on(r, "*"));
let bad = of(axis, &|r| damage_on(r, axis));
let thr = quantile(&clean, 0.9);
let share = |v: &[f32]| share_over(v, thr);
let cheats = CHEATS.iter().filter(|c| c.1 == *axis).map(|c| (c.0.to_string(), share(&of(axis, &|r| r.source == "cheat" && r.kind.as_deref() == Some(c.0))))).collect();
out.push(WordScore { axis: axis.to_string(), auc: auc(&bad, &clean), caught: share(&bad), cheats });
}
out
}
+160
View File
@@ -0,0 +1,160 @@
//! `raea fingerprint` (docs/fingerprint.feature FP3a): a person's fingerprint made, bootstrapped, taught and used to
//! score a piece. The encoders take seconds to load, so the verbs run in a resident service (`raea fingerprint
//! serve`, serve.rs) that keeps them loaded: the first verb starts it, on localhost, and later verbs reach it in
//! milliseconds (earshot's CLI reloads its models on every call, 20-40 s). It leaves after 30 idle minutes, or on
//! `raea fingerprint stop`. RAEA_FINGERPRINT_HERE=1 runs a verb in this process instead.
mod approve;
mod bootstrap;
mod moving;
mod notes;
mod pairing;
mod pick;
mod postmortem;
mod profiles;
mod reembed;
mod serve;
mod things;
mod verbs;
use std::path::Path;
pub use serve::serve;
pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT [--by kimi|claude] | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh kimi or claude session read a project's pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)";
/// Evaluates a .ts file's default export to its JSON (the CLI's spec host)
pub type Eval = fn(&Path) -> Result<String, String>;
/// The flags each verb takes, and whether each takes a value
pub(crate) const FLAGS: [(&str, bool); 31] = [
("--fp", true),
("--was", true),
("--to", true),
("--source", true),
("--kinds", true),
("--tags", true),
("--who", true),
("--about", true),
("--extends", true),
("--from", true),
("--per", true),
("--axis", true),
("--at", true),
("--then", true),
("--span", true),
("--box", true),
("--words", true),
("--project", true),
("--sheet", true),
("--in", true),
("--as", true),
("--against", true),
("--profile", true),
("--by", true),
("--ask", true),
("--tally", false),
("--bad", false),
("--good", false),
("--json", false),
("--timeline", false),
("--here", false),
];
/// A flag's value
pub(crate) 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)
}
pub(crate) fn has(args: &[String], name: &str) -> bool {
args.iter().any(|a| a == name)
}
/// A path as given, against the folder the verb ran in (an absolute one stays itself)
pub(crate) fn at(cwd: &Path, p: &str) -> std::path::PathBuf {
cwd.join(p)
}
/// The files a verb names, against the folder it ran in
pub(crate) fn named(args: &[String], cwd: &Path) -> anyhow::Result<Vec<std::path::PathBuf>> {
Ok(words(args).map_err(anyhow::Error::msg)?.iter().map(|f| at(cwd, f)).collect())
}
/// The files a list names, one a line against the list's own folder; blank lines and # lines are skipped
pub(crate) fn listed(cwd: &Path, list: &str) -> anyhow::Result<Vec<std::path::PathBuf>> {
use anyhow::Context;
let list = at(cwd, list);
let text = std::fs::read_to_string(&list).with_context(|| list.display().to_string())?;
let base = list.parent().unwrap_or(cwd);
Ok(text.lines().map(str::trim).filter(|l| !(l.is_empty() || l.starts_with('#'))).map(|l| at(base, l)).collect())
}
/// The words that aren't flags or their values; an unknown flag is an error
pub(crate) fn words(args: &[String]) -> Result<Vec<&str>, String> {
let mut out = Vec::new();
let mut it = args.iter();
while let Some(a) = it.next() {
match FLAGS.iter().find(|(f, _)| f == a) {
Some((_, true)) => {
it.next().ok_or_else(|| format!("{a} takes a value"))?;
}
Some(_) => {}
None if a.starts_with("--") => return Err(format!("no flag {a}")),
None => out.push(a.as_str()),
}
}
Ok(out)
}
/// `raea fingerprint VERB ...`, printed; its exit code (1: the verb failed, 2: the command was wrong)
pub fn cli(args: &[String], eval: Eval) -> i32 {
let verb = match args.first().map(String::as_str) {
None | Some("--help" | "-h" | "help") => {
println!("{USAGE}");
return 0;
}
Some(v) => v,
};
if let Err(e) = words(&args[1..]) {
eprintln!("raea fingerprint: {e}\n{USAGE}");
return 2;
}
match verb {
"serve" => match serve(eval) {
Ok(()) => 0,
Err(e) => {
eprintln!("raea fingerprint serve: {e:#}");
1
}
},
"report" => verbs::report_here(args),
"which" => pick::which_here(&args[1..], &std::env::current_dir().unwrap_or_default()),
"diff" => pick::diff_here(&args[1..]),
"read" => notes::read_here(&args[1..], &std::env::current_dir().unwrap_or_default()),
"readings" => notes::readings_here(&args[1..], &std::env::current_dir().unwrap_or_default()),
"share" => pick::share_here(&args[1..], &std::env::current_dir().unwrap_or_default()),
"use" => pick::use_here(&args[1..], &std::env::current_dir().unwrap_or_default()),
"new" | "bootstrap" | "teach" | "approve" | "pair" | "versions" | "learn-notes" | "move" | "postmortem" | "things" | "reembed" | "profile" | "score" | "stop" => {
let cwd = std::env::current_dir().unwrap_or_default();
let here = has(args, "--here") || std::env::var_os("RAEA_FINGERPRINT_HERE").is_some();
let (out, code) = if here { serve::here(args, &cwd, eval) } else { serve::call(args, &cwd) };
if !out.is_empty() {
println!("{}", out.trim_end());
}
code
}
v => {
eprintln!("raea fingerprint: no verb {v}\n{USAGE}");
2
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn the_usage_names_every_flag() {
let missing: Vec<_> = super::FLAGS.iter().filter(|(f, _)| *f != "--here" && !super::USAGE.contains(f)).collect();
assert!(missing.is_empty(), "raea fingerprint takes flags its usage doesn't name: {missing:?}");
}
}
+86
View File
@@ -0,0 +1,86 @@
//! `raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P]` (docs/fingerprint.feature
//! FP14d). A note or mark teaches the fingerprint that judged the piece, and a parent never reads a child's evidence
//! (inherit.rs), so one client's taste doesn't move the person's own. Moving labels up is the person's call: the
//! child's own rows that match leave its ledger for a fingerprint it extends (its nearest unless --to names one). A
//! row on an axis the parent hasn't, or on one the child says otherwise, stays: in the parent it would mean something
//! else.
use crate::{Eval, flag};
use anyhow::{Result, anyhow, bail};
use raea_sys_fingerprint::evidence::{Ledger, Row};
use raea_sys_fingerprint::folder::Folder;
use raea_sys_fingerprint::inherit;
use raea_sys_fingerprint::taxonomy::Fingerprint;
use std::collections::BTreeSet;
/// The rows `pick` takes from `child` into `parent`; returns how many moved
pub fn rows(child: &mut Ledger, parent: &mut Ledger, pick: &dyn Fn(&Row) -> bool) -> usize {
let mut n = 0;
for i in 0..child.rows.len() {
if pick(&child.rows[i]) {
parent.push(child.rows[i].clone(), child.features(i));
n += 1;
}
}
child.retain(|r| !pick(r));
n
}
/// The axes a row may carry into `parent`: the parent's own and inherited ones, less those the child overrides
pub fn carried(parent: &Fingerprint, eval: Eval, over: &BTreeSet<String>) -> BTreeSet<String> {
let full = inherit::axes(parent, &inherit::parents(parent, Some(eval)));
full.axes.iter().map(|a| a.name.clone()).filter(|a| !over.contains(a)).chain(["*".to_string()]).collect()
}
/// Moves the child's matching rows up and writes both ledgers; returns the parent's name and what it did
pub(crate) fn up(dir: &Folder, child: &Fingerprint, args: &[String], eval: Eval) -> Result<(String, String)> {
let (axis, source, project) = (flag(args, "--axis"), flag(args, "--source"), flag(args, "--project"));
if axis.is_none() && source.is_none() && project.is_none() {
bail!("say which labels: --axis A, --source S (note, teach, approval, pair, damage) or --project P");
}
let parents = inherit::parents(child, Some(eval));
let (pdir, parent) = match flag(args, "--to") {
Some(n) => parents.iter().find(|(_, p)| p.name == n).ok_or_else(|| anyhow!("{} doesn't extend {n}: labels only move up", child.name))?,
None => parents.first().ok_or_else(|| anyhow!("{} extends nothing, so its labels have nowhere to move up to", child.name))?,
};
let keep = carried(parent, eval, &inherit::overrides(child, &parents));
let wanted = |r: &Row| axis.is_none_or(|a| r.axis == a) && source.is_none_or(|s| r.source == s) && project.is_none_or(|p| r.project == p);
let (mut lc, mut lp) = (dir.ledger()?, pdir.ledger()?);
let stay = lc.rows.iter().filter(|r| wanted(r) && !keep.contains(&r.axis)).count();
let n = rows(&mut lc, &mut lp, &|r| wanted(r) && keep.contains(&r.axis));
if n == 0 && stay == 0 {
bail!("none of {}'s own labels match", child.name);
}
pdir.write_ledger(&lp)?;
dir.write_ledger(&lc)?;
let mut out = format!("{n} labels moved from {} up to {}\n", child.name, parent.name);
if stay > 0 {
out += &format!("{stay} stay: their axes are {}'s own, and would mean something else in {}\n", child.name, parent.name);
}
Ok((parent.name.clone(), out))
}
#[cfg(test)]
mod tests {
use super::*;
fn row(axis: &str, source: &str) -> Row {
Row { media: "m".into(), a: 0.0, b: 2.0, axis: axis.into(), bad: true, weight: 1.0, who: "me".into(), source: source.into(), project: "p".into(), kind: None, region: None, words: None, at: 0, pin: None, band: None }
}
#[test]
fn only_picked_rows_move_and_keep_their_features() {
let w = raea_sys_fingerprint::evidence::width();
let (mut c, mut p) = (Ledger::default(), Ledger::default());
c.push(row("blur", "note"), &vec![1.0; w]);
c.push(row("glow", "note"), &vec![2.0; w]);
c.push(row("blur", "damage"), &vec![3.0; w]);
p.push(row("hiss", "teach"), &vec![4.0; w]);
let n = rows(&mut c, &mut p, &|r| r.source == "note" && r.axis == "blur");
assert_eq!(n, 1);
assert_eq!(c.rows.iter().map(|r| r.axis.as_str()).collect::<Vec<_>>(), ["glow", "blur"]);
assert_eq!((c.features(0)[0], c.features(1)[0]), (2.0, 3.0), "the child's rows keep their own features");
assert_eq!(p.rows.len(), 2);
assert_eq!(p.features(1)[0], 1.0, "a moved row carries its features");
}
}
+308
View File
@@ -0,0 +1,308 @@
//! Notes become evidence (docs/fingerprint.feature FP5a, FP5b). `raea fingerprint read PROJECT [--by kimi|claude]`
//! has a fresh agent session read each pinned note on the project's videos into a kind (defect, direction, praise or
//! both) and an axis from the fingerprint's own axes, kept in the fingerprint's readings.jsonl. Nothing trains on them
//! yet: `raea fingerprint readings --ask N` puts N readings to the person as questions in the app (`raea show
//! --question`, answers to the "fingerprint" inbox), `readings --tally` counts how often the person agreed, and only
//! once the kind is right 45 times in 50 and the axis 40 (FP5b) does `raea fingerprint learn-notes` make each defect
//! or praise an evidence row over its span (1.5 s before the pin to 0.5 s after). A direction goes to the brief and the
//! agent, never into a head. A note's marks (FP11b) make its row a region label: the box around its marks, boxes and
//! lassos; a span pin sets the row's time. On a render with a layer pass, a reading keeps the layers under its pin,
//! and the reader is told them.
use crate::{flag, has, words};
use raea_sys_fingerprint::folder::Folder;
use raea_sys_fingerprint::taxonomy::Fingerprint;
pub use raea_sys_fingerprint_use::reading::{Reading, agreement, earned};
use raea_sys_fingerprint_use::reading::span;
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
pub const INBOX: &str = "fingerprint";
/// A post's video on this machine: the renders library, else the project's own folder
fn media(project: &Path, m: &Value) -> Option<PathBuf> {
let p = m["path"].as_str()?;
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
[home.join(".raea/feed/media").join(p), project.join(p)].into_iter().find(|f| f.is_file())
}
/// Every video in the project's feed, each version's, found on this machine (FP7a's postmortem looks back on them)
pub fn videos(project: &Path) -> Vec<PathBuf> {
let mut out: Vec<PathBuf> = Vec::new();
for e in std::fs::read_dir(project.join(".raea/feed")).into_iter().flatten().flatten() {
let Some(post) = std::fs::read_to_string(e.path()).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()) else { continue };
for m in post["media"].as_array().into_iter().flatten().filter(|m| m["kind"] == "video") {
if let Some(v) = media(project, m).filter(|v| !out.contains(v)) {
out.push(v);
}
}
}
out.sort();
out
}
/// Every person's pinned note on a video in the project's feed
pub fn pinned(project: &Path) -> Vec<Reading> {
let name = project.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let mut out = Vec::new();
for e in std::fs::read_dir(project.join(".raea/feed")).into_iter().flatten().flatten() {
let Ok(post) = std::fs::read_to_string(e.path()).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()).ok_or(()) else { continue };
let Some(video) = post["media"].as_array().into_iter().flatten().find(|m| m["kind"] == "video").and_then(|m| media(project, m)) else { continue };
for n in post["notes"].as_array().into_iter().flatten() {
let (Some(t), Some(text)) = (n["pin"]["t"].as_f64(), n["text"].as_str()) else { continue };
if n["author"]["kind"] != "person" {
continue;
}
let to = n["pin"]["to"].as_f64().filter(|&to| to > t);
let at = n["pin"]["x"].as_f64().zip(n["pin"]["y"].as_f64()).map(|(x, y)| [x - 0.01, y - 0.01, x + 0.01, y + 0.01].map(|v| v.clamp(0.0, 1.0)));
let layers = at.map(|b| raea_sys_fingerprint_things::located::layers(&video, t, b)).unwrap_or_default();
out.push(Reading { note: n["id"].as_str().unwrap_or("").into(), text: text.into(), who: n["author"]["name"].as_str().unwrap_or("me").into(), media: video.clone(), t, project: name.clone(), to, region: raea_sys_fingerprint_use::grow::marked(&n["pin"]), layers, band: raea_sys_fingerprint_use::grow::sound_band(&n["pin"]), ..Default::default() });
}
}
out
}
/// The reading prompt: the axes with their words, then the notes, and the JSON to answer
pub fn prompt(fp: &Fingerprint, notes: &[Reading]) -> String {
let axes = fp.axes.iter().map(|a| format!("- {}: {}", a.name, a.words.join("; "))).collect::<Vec<_>>().join("\n");
let on = |n: &Reading| if n.layers.is_empty() { String::new() } else { format!(" (pinned on {})", n.layers.join(", ")) };
let list = notes.iter().map(|n| format!("{}: {}{}", n.note, n.text.replace('\n', " "), on(n))).collect::<Vec<_>>().join("\n");
format!(
"You read a person's review notes on their videos. Read each note only; open no file and change nothing.\n\
For each note say its kind: \"defect\" (it names something wrong at that moment), \"direction\" (it asks for a creative change, \
not a fault), \"praise\" (it says something is good) or \"both\" (a defect and a direction). Then the axis it is about, from \
these and only these, or null when none fits:\n{axes}\n\nThe notes, one a line, id first:\n{list}\n\n\
End with only this JSON, nothing after it: [{{\"id\": \"\", \"kind\": \"defect|direction|praise|both\", \"axis\": \"name or null\"}}]"
)
}
/// The JSON array an answer ends with
pub fn answer(text: &str) -> Option<Vec<Value>> {
let end = text.rfind(']')?;
let start = text[..end].rfind("[{").or_else(|| text[..end].rfind('['))?;
serde_json::from_str(&text[start..=end]).ok()
}
/// Fold an answer into the notes: a kind it doesn't know or an axis not in the fingerprint is dropped
pub fn fold(notes: &mut [Reading], fp: &Fingerprint, ans: &[Value], by: &str) {
for a in ans {
let Some(id) = a["id"].as_str() else { continue };
let Some(n) = notes.iter_mut().find(|n| n.note == id) else { continue };
let kind = a["kind"].as_str().unwrap_or("");
if !matches!(kind, "defect" | "direction" | "praise" | "both") {
continue;
}
n.kind = kind.into();
n.axis = a["axis"].as_str().filter(|x| fp.axis(x).is_some()).map(str::to_string);
n.by = by.into();
}
}
/// One fresh session's words: kimi's or claude's stream, the assistant's text joined
fn ask(by: &str, p: &str) -> Result<String, String> {
let mut c = std::process::Command::new(by);
match by {
"kimi" => c.args(["-p", p, "--output-format", "stream-json"]),
"claude" => c.args(["-p", p, "--output-format", "stream-json", "--verbose", "--allowedTools", ""]),
o => return Err(format!("--by {o}: kimi or claude")),
};
let out = c.output().map_err(|e| format!("couldn't run {by}: {e}"))?;
let mut text = String::new();
for line in String::from_utf8_lossy(&out.stdout).lines() {
let Ok(v) = serde_json::from_str::<Value>(line) else { continue };
let content = if v["role"] == "assistant" { &v["content"] } else if v["type"] == "assistant" { &v["message"]["content"] } else if v["type"] == "result" { &v["result"] } else { continue };
match content {
Value::String(s) => text += s,
Value::Array(a) => a.iter().filter_map(|p| p["text"].as_str()).for_each(|s| text += s),
_ => {}
}
text.push('\n');
}
if text.trim().is_empty() {
return Err(format!("{by} said nothing: {}", String::from_utf8_lossy(&out.stderr).lines().last().unwrap_or("")));
}
Ok(text)
}
pub fn readings_of(dir: &Folder) -> Vec<Reading> {
std::fs::read_to_string(dir.dir.join("readings.jsonl")).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect()
}
pub fn write_readings(dir: &Folder, r: &[Reading]) -> std::io::Result<()> {
std::fs::write(dir.dir.join("readings.jsonl"), r.iter().filter_map(|x| serde_json::to_string(x).ok()).map(|l| l + "\n").collect::<String>())
}
/// `raea fingerprint read PROJECT [--by kimi|claude]`
pub(crate) fn read_here(args: &[String], cwd: &Path) -> i32 {
let run = || -> Result<String, String> {
let w = words(args)?;
let project = w.first().map_or(cwd.to_path_buf(), |p| cwd.join(p));
let by = flag(args, "--by").unwrap_or("kimi");
let dir = crate::pick::chosen(args, Some(&crate::pick::piece_in(args, cwd))).0;
let fp = dir.read(None).map_err(|e| e.to_string())?;
let mut notes = pinned(&project);
let mut kept = readings_of(&dir);
notes.retain(|n| !kept.iter().any(|k| k.note == n.note && k.media == n.media));
if notes.is_empty() {
return Ok(format!("no new pinned notes in {}", project.display()));
}
for chunk in notes.chunks_mut(40) {
let text = ask(by, &prompt(&fp, chunk))?;
let ans = answer(&text).ok_or_else(|| format!("{by} answered no readings JSON"))?;
fold(chunk, &fp, &ans, by);
eprintln!("read {} notes", chunk.len());
}
let read = notes.iter().filter(|n| !n.kind.is_empty()).count();
kept.extend(notes.into_iter().filter(|n| !n.kind.is_empty()));
write_readings(&dir, &kept).map_err(|e| e.to_string())?;
Ok(format!("{read} notes read into labels by {by}, kept in {}; none trains a head until you've checked them: raea fingerprint readings --ask 50", dir.dir.join("readings.jsonl").display()))
};
match run() {
Ok(o) => {
println!("{o}");
0
}
Err(e) => {
eprintln!("raea fingerprint read: {e}");
1
}
}
}
/// The choices a reading is checked with, and what each says about kind and axis
pub const CHOICES: [(&str, bool, bool); 4] = [("Right", true, true), ("Right kind, wrong axis", true, false), ("Wrong kind", false, false), ("Right axis, wrong kind", false, true)];
/// `raea fingerprint readings [PROJECT] [--ask N] [--tally]`: the readings kept in the fingerprint that judges PROJECT
pub(crate) fn readings_here(args: &[String], cwd: &Path) -> i32 {
let dir = crate::pick::chosen(args, Some(&crate::pick::piece_in(args, cwd))).0;
let mut r = readings_of(&dir);
if let Some(n) = flag(args, "--ask").and_then(|n| n.parse::<usize>().ok()) {
let todo: Vec<usize> = r.iter().enumerate().filter(|(_, x)| x.kind_ok.is_none()).map(|(i, _)| i).take(n).collect();
let mut cmd = std::process::Command::new(std::env::current_exe().unwrap_or_else(|_| "raea".into()));
cmd.args(["show", "--title", "Check how raea read your notes", "--inbox", INBOX]);
for &i in &todo {
let x = &r[i];
let q = format!("[{}] \"{}\" read as {} on {}", x.note, x.text.replace('\n', " "), x.kind, x.axis.as_deref().unwrap_or("no axis"));
cmd.args(["--question", &q, "--preview", &x.media.display().to_string()]);
for (c, _, _) in CHOICES {
cmd.args(["--choice", c]);
}
}
if todo.is_empty() {
println!("every reading is checked");
return 0;
}
let Ok(out) = cmd.output() else { return 1 };
let said = String::from_utf8_lossy(&out.stdout).into_owned();
// the item raea show made, so the answers can be matched to the notes asked, in order
let Some(item) = said.split(|c: char| c.is_whitespace() || c == '(' || c == ')' || c == ',').find(|w| w.starts_with("i-show-")) else {
eprintln!("raea fingerprint readings: raea show didn't say its item: {said}{}", String::from_utf8_lossy(&out.stderr));
return 1;
};
let mut asked: serde_json::Map<String, Value> = std::fs::read(dir.dir.join("asked.json")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
asked.insert(item.to_string(), json!(todo.iter().map(|&i| [r[i].note.clone(), r[i].media.display().to_string()]).collect::<Vec<_>>()));
let _ = std::fs::write(dir.dir.join("asked.json"), serde_json::to_vec_pretty(&asked).unwrap_or_default());
println!("{} readings put to you in the app ({item}); `raea fingerprint readings --tally` counts your answers", todo.len());
return 0;
}
if has(args, "--tally") {
let asked: serde_json::Map<String, Value> = std::fs::read(dir.dir.join("asked.json")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
let inbox = PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(format!(".raea/inbox/{INBOX}.jsonl"));
for line in std::fs::read_to_string(inbox).unwrap_or_default().lines() {
let Ok(v) = serde_json::from_str::<Value>(line) else { continue };
let Some(batch) = v["item"].as_str().and_then(|i| asked.get(i)).and_then(Value::as_array) else { continue };
for (k, who) in batch.iter().enumerate() {
let Some(a) = v["answers"][format!("q{}", k + 1)].as_str() else { continue };
let Some((_, ok_kind, ok_axis)) = CHOICES.iter().find(|c| c.0 == a) else { continue };
if let Some(x) = r.iter_mut().find(|x| who[0].as_str() == Some(x.note.as_str()) && who[1].as_str() == Some(&x.media.display().to_string())) {
(x.kind_ok, x.axis_ok) = (Some(*ok_kind), Some(*ok_axis));
}
}
}
let _ = write_readings(&dir, &r);
}
let (k, a, n) = agreement(&r);
let f = |x: Option<f64>| x.map_or("-".into(), |v| format!("{:.0}%", v * 100.0));
println!("{} readings, {n} checked: kind right {}, axis right {} (FP5b needs 50 checked, 90% and 80%): {}", r.len(), f(k), f(a), if earned(&r) { "notes may train" } else { "notes don't train yet" });
println!("{}", json!({"readings": r.len(), "checked": n, "kind": k, "axis": a, "earned": earned(&r)}));
0
}
/// `learn-notes`: each checked-off reading's defect or praise as an evidence row over its span, once the readings
/// have earned it; a reading already learned is replaced, so learning again is safe
pub(crate) fn learn(enc: &mut raea_sys_columns::Encoders, dir: &Folder, l: &mut raea_sys_fingerprint::evidence::Ledger) -> anyhow::Result<String> {
let r = readings_of(dir);
if !earned(&r) {
let (k, a, n) = agreement(&r);
anyhow::bail!("notes don't train yet: {n} readings checked, kind right {:?}, axis right {:?} (FP5b needs 50 checked, 90% and 80%: raea fingerprint readings --ask 50)", k, a);
}
// only these readings' rows are remade: notes another fingerprint's person moved up here (FP14d) stay
let ids: std::collections::BTreeSet<&str> = r.iter().map(|x| x.note.as_str()).collect();
l.retain(|x| x.source != "note" || !x.kind.as_deref().is_some_and(|k| ids.contains(k)));
let mut made = 0;
for x in r.iter().filter(|x| x.kind_ok != Some(false) && x.axis_ok != Some(false)) {
let bad = match x.kind.as_str() {
"defect" | "both" => true,
"praise" => false,
_ => continue,
};
let axis = match (&x.axis, bad) {
(Some(a), _) => a.clone(),
(None, false) => "*".into(),
(None, true) => continue,
};
let c = enc.columns(&x.media)?;
// a span is the label's time (a scene's, a box's on the sound: FP11c), half a second at least; a moment, 1.5 s
// before the pin to 0.5 s after (FP11b)
let (a, b) = x.to.map_or(((x.t - 1.5).max(0.0), (x.t + 0.5).min(c.dur)), |to| span(x.t, to, c.dur));
if b - a < 0.5 {
continue;
}
// a defect's marks, grown into the thing by EdgeTAM and followed through its shot: a row for each 2 s it stays
// in, with its box there (grow.rs through); else the mark's own box over the label
let seed = x.region.filter(|_| bad);
let shot = seed.and_then(|s| raea_sys_fingerprint_use::grow::through(&x.media, x.t, c.dur, s, 2.0).ok().flatten()).filter(|w| !w.is_empty());
for (a, b, region) in shot.map_or_else(|| vec![(a, b, seed)], |w| w.into_iter().map(|(a, b, r)| (a, b, Some(r))).collect()) {
let (media, axis, who, project, kind, words) = (c.media.clone(), axis.clone(), x.who.clone(), x.project.clone(), Some(x.note.clone()), Some(x.text.clone()));
// a defect's box on the sound keeps its pitch band (FP11c)
let band = x.band.filter(|_| bad);
let row = raea_sys_fingerprint::evidence::Row { media, a, b, axis, bad, weight: 1.0, who, source: "note".into(), project, kind, region, words, at: 0, pin: None, band };
l.push(row, &raea_sys_fingerprint::evidence::features(&c, a, b));
}
made += 1;
}
Ok(format!("{made} notes are evidence now (defects and praise; directions stay with the brief)\n"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_reading_keeps_only_kinds_and_axes_it_knows() {
let fp = raea_sys_fingerprint::taxonomy::base("me");
let mut n = vec![Reading { note: "n1".into(), ..Default::default() }, Reading { note: "n2".into(), ..Default::default() }, Reading { note: "n3".into(), ..Default::default() }];
let ans = answer("I read them.\n[{\"id\": \"n1\", \"kind\": \"defect\", \"axis\": \"glitch\"}, {\"id\": \"n2\", \"kind\": \"direction\", \"axis\": \"made up\"}, {\"id\": \"n3\", \"kind\": \"rant\", \"axis\": null}]").unwrap();
fold(&mut n, &fp, &ans, "kimi");
assert_eq!((n[0].kind.as_str(), n[0].axis.as_deref()), ("defect", Some("glitch")));
assert_eq!((n[1].kind.as_str(), n[1].axis.as_deref()), ("direction", None), "an axis the fingerprint hasn't is dropped");
assert_eq!(n[2].kind, "", "a kind it doesn't know is no reading");
n[0].layers = vec!["Floor".into()];
assert!(prompt(&fp, &n).contains("n1: ") && prompt(&fp, &n).contains("(pinned on Floor)"), "the reader is told the layer");
}
#[test]
fn a_box_on_the_sound_is_a_reading_s_span_and_band_not_a_region() {
let dir = std::env::temp_dir().join(format!("fp11c-{}", std::process::id()));
std::fs::create_dir_all(dir.join(".raea/feed")).unwrap();
std::fs::write(dir.join("a.mp4"), b"").unwrap();
let note = json!({"id": "n1", "text": "that hiss", "author": {"kind": "person", "name": "me"}, "pin": {"kind": "time", "t": 2.0, "to": 4.0, "marks": [{"kind": "box", "on": "sound", "points": [[0.2, 0.9], [0.4, 0.6]]}]}});
std::fs::write(dir.join(".raea/feed/p.json"), json!({"media": [{"kind": "video", "path": "a.mp4"}], "notes": [note]}).to_string()).unwrap();
let r = pinned(&dir);
std::fs::remove_dir_all(&dir).ok();
assert_eq!(r.len(), 1);
assert_eq!((r[0].t, r[0].to, r[0].band, r[0].region), (2.0, Some(4.0), Some([0.6, 0.9]), None));
}
}
+91
View File
@@ -0,0 +1,91 @@
//! Pairs from what the person already does (docs/fingerprint.feature FP6b, FP6c). `raea fingerprint pair WORSE BETTER
//! --axis A [--at T] [--then T2]` records a pick between real options or a hand edit's before and after: the better
//! window against the worse on that axis. `raea fingerprint versions V1 V2...` (the files in version order) makes a
//! weak pair (weight 0.5, every axis) of each noted moment whose picture or sound changed in the next version (cosine
//! distance 0.01 or more) and wasn't noted again within 1 s there.
use crate::approve::noted;
use crate::flag;
use anyhow::{Context, Result, anyhow, bail};
use raea_sys_columns::Encoders;
use raea_sys_columns::window::Modality;
use raea_sys_fingerprint::evidence::{Ledger, Row, features, slice};
use raea_sys_fingerprint::pairs::difference;
use std::path::Path;
fn row(media: &str, a: f64, b: f64, axis: &str, weight: f32, who: &str, project: String, words: Option<String>) -> Row {
Row { media: media.into(), a, b, axis: axis.into(), bad: true, weight, who: who.into(), source: "pair".into(), project, kind: None, region: None, words, at: 0, pin: None, band: None }
}
/// `pair`: one row, the worse window's features minus the better one's
pub(crate) fn pair(enc: &mut Encoders, l: &mut Ledger, who: &str, args: &[String], cwd: &Path, project: impl Fn(&Path) -> String) -> Result<String> {
let f = crate::named(args, cwd)?;
let [worse, better] = f.as_slice() else { bail!("raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2]") };
let axis = flag(args, "--axis").ok_or_else(|| anyhow!("--axis A: the axis the better one is better on"))?;
let span: f64 = flag(args, "--span").map_or(Ok(2.0), str::parse).context("--span takes seconds")?;
let t: f64 = flag(args, "--at").map_or(Ok(span / 2.0), str::parse).context("--at takes seconds")?;
let t2: f64 = flag(args, "--then").map_or(Ok(t), str::parse).context("--then takes seconds")?;
let (cw, cb) = (enc.columns(worse)?, enc.columns(better)?);
let win = |dur: f64, t: f64| {
let a = (t - span / 2.0).clamp(0.0, (dur - span).max(0.0));
(a, (a + span).min(dur))
};
let ((a, b), (a2, b2)) = (win(cw.dur, t), win(cb.dur, t2));
let d = difference(&features(&cw, a, b), &features(&cb, a2, b2));
l.push(row(&cw.media, a, b, axis, 1.0, who, flag(args, "--project").map_or_else(|| project(worse), str::to_string), flag(args, "--words").map(str::to_string)), &d);
Ok(format!("paired on {axis}: {} at {a:.1} s is worse than {} at {a2:.1} s\n", worse.display(), better.display()))
}
fn distance(x: &[f32], y: &[f32]) -> f32 {
let d: f32 = x.iter().zip(y).map(|(a, b)| a * b).sum();
1.0 - d / (x.iter().map(|a| a * a).sum::<f32>().sqrt() * y.iter().map(|b| b * b).sum::<f32>().sqrt()).max(1e-9)
}
/// Whether a noted moment changed in the next version and wasn't noted there again
pub(crate) fn weak(before: &[f32], after: &[f32], t: f64, next_notes: &[f64]) -> bool {
let changed = [Modality::Picture, Modality::Sound].iter().any(|&m| distance(&before[slice(m)], &after[slice(m)]) >= 0.01);
changed && !next_notes.iter().any(|n| (n - t).abs() <= 1.0)
}
/// `versions`: weak pairs along a chain of versions
pub(crate) fn versions(enc: &mut Encoders, l: &mut Ledger, who: &str, args: &[String], cwd: &Path, project: impl Fn(&Path) -> String) -> Result<String> {
let f = crate::named(args, cwd)?;
if f.len() < 2 {
bail!("raea fingerprint versions V1 V2... takes the versions in order");
}
let mut made = 0;
for w in f.windows(2) {
let (now, next) = (&w[0], &w[1]);
let (cn, cx) = (enc.columns(now)?, enc.columns(next)?);
let next_notes = noted(next);
for t in noted(now) {
let (a, b) = ((t - 1.5).max(0.0), (t + 0.5).min(cn.dur.min(cx.dur)));
if b - a < 1.0 {
continue;
}
let (fb, fa) = (features(&cn, a, b), features(&cx, a, b));
if weak(&fb, &fa, t, &next_notes) {
l.push(row(&cn.media, a, b, "*", 0.5, who, flag(args, "--project").map_or_else(|| project(now), str::to_string), None), &difference(&fb, &fa));
made += 1;
}
}
}
Ok(format!("{made} weak pairs from {} versions: noted moments the next version changed and nobody noted again\n", f.len()))
}
#[cfg(test)]
mod tests {
use raea_sys_fingerprint::evidence::width;
#[test]
fn a_changed_moment_not_noted_again_is_a_weak_pair() {
let a = vec![1.0; width()];
let mut b = a.clone();
assert!(!super::weak(&a, &b, 5.0, &[]), "unchanged: no pair");
b.iter_mut().enumerate().for_each(|(i, x)| *x = if i % 2 == 0 { 1.0 } else { -1.0 });
assert!(super::weak(&a, &b, 5.0, &[]));
assert!(!super::weak(&a, &b, 5.0, &[5.6]), "noted again within 1 s: no pair");
assert!(super::weak(&a, &b, 5.0, &[7.0]));
}
}
+151
View File
@@ -0,0 +1,151 @@
//! Which fingerprint judges a piece (docs/fingerprint.feature FP14c): `raea fingerprint which PATH` says the one
//! chosen, what it's for and why; `raea fingerprint use NAME [--in project|workspace] [PATH]` pins one by writing that
//! level's `default`. score and teach use the chosen one unless --fp names another. No encoders are needed.
use crate::{flag, has, words};
use raea_sys_fingerprint::folder::{Folder, root};
use raea_sys_fingerprint_use::which::{Choice, default_file, levels, piece, which};
use std::path::{Path, PathBuf};
/// The fingerprint a verb uses: --fp, else the one that judges `file`, else the account's default, else "me"
pub(crate) fn chosen(args: &[String], file: Option<&Path>) -> (Folder, Option<Choice>) {
if let Some(n) = flag(args, "--fp") {
return (Folder::named(n), None);
}
if let Some(c) = file.and_then(which) {
return (Folder { dir: c.dir.clone() }, Some(c));
}
let n = std::fs::read_to_string(root().join("default")).ok().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).unwrap_or_else(|| "me".into());
(Folder::named(&n), None)
}
/// A piece in the project a verb names (its first word, else the current folder), so `read`, `readings` and
/// `learn-notes` keep a project's notes in the fingerprint that judges it (FP14d)
pub(crate) fn piece_in(args: &[String], cwd: &Path) -> PathBuf {
here(cwd, args, 0).join("piece.mp4")
}
fn here(cwd: &Path, args: &[String], at: usize) -> PathBuf {
let w = words(args).unwrap_or_default();
w.get(at).map_or_else(|| cwd.to_path_buf(), |p| cwd.join(p))
}
pub(crate) fn which_here(args: &[String], cwd: &Path) -> i32 {
let path = here(cwd, args, 0);
let Some(c) = which(&path) else {
eprintln!("raea fingerprint which: you have no fingerprint yet (`raea fingerprint new me` makes one)");
return 1;
};
if has(args, "--json") {
let p = piece(&path);
println!("{}", serde_json::json!({"chosen": c, "piece": p, "looked_in": levels(&p).iter().map(|(l, d)| serde_json::json!({"level": l, "dir": d})).collect::<Vec<_>>()}));
} else {
println!("{} {}", c.name, c.about.as_deref().unwrap_or(""));
println!(" why: {}", c.why);
println!(" at: {}", c.dir.display());
}
0
}
pub(crate) fn use_here(args: &[String], cwd: &Path) -> i32 {
let Some(name) = words(args).ok().and_then(|w| w.first().map(|s| s.to_string())) else {
eprintln!("raea fingerprint use: which one? raea fingerprint use NAME [--in project|workspace] [PATH]");
return 2;
};
let level = flag(args, "--in").unwrap_or("account");
if !matches!(level, "project" | "workspace" | "account") {
eprintln!("raea fingerprint use: --in takes project or workspace, not {level}");
return 2;
}
let path = here(cwd, args, 1);
let Some(file) = default_file(&path, level) else {
eprintln!("raea fingerprint use: {} isn't in a {level} (no .raea/{level} above it)", path.display());
return 1;
};
let p = piece(&path);
let all = levels(&p);
let from = all.iter().position(|(l, _)| *l == level).unwrap_or(0);
if !all[from..].iter().any(|(_, d)| Folder { dir: d.join(&name) }.exists()) {
eprintln!("raea fingerprint use: no fingerprint {name} at the {level} or above it");
return 1;
}
let wrote = std::fs::create_dir_all(file.parent().unwrap_or(cwd)).and(std::fs::write(&file, &name));
if let Err(e) = wrote {
eprintln!("raea fingerprint use: {}: {e}", file.display());
return 1;
}
println!("{name} judges this {level}'s pieces now ({})", file.display());
0
}
/// `raea fingerprint diff A B [--json]` (FP8b): the axes two fingerprints rank the same evidence most differently on
pub(crate) fn diff_here(args: &[String]) -> i32 {
let w = words(args).unwrap_or_default();
let [a, b] = w.as_slice() else {
eprintln!("raea fingerprint diff: which two? raea fingerprint diff A B");
return 2;
};
match raea_sys_fingerprint_use::diff::diff(&Folder::named(a), &Folder::named(b), 3) {
Ok(d) if has(args, "--json") => {
println!("{}", serde_json::to_string_pretty(&d).unwrap_or_default());
0
}
Ok(d) => {
println!("where {a} and {b} differ, most apart first (0 agree, 1 unrelated, 2 opposed):");
for x in &d {
println!(" {:16} {:.2} over {} windows", x.axis, x.apart, x.windows);
for m in &x.moments {
println!(" {} {:.1}-{:.1}s: {a} ranks it {:.0}%, {b} {:.0}%", &m.media[..m.media.len().min(12)], m.a, m.b, m.rank_a * 100.0, m.rank_b * 100.0);
}
}
0
}
Err(e) => {
eprintln!("raea fingerprint diff: {e:#}");
1
}
}
}
/// `raea fingerprint share NAME --in project|workspace [PATH]` (FP8a): the fingerprint's taxonomy, words and evidence
/// copied into that level's .raea/fingerprints, to travel with its repo; never its heads (each machine retrains them)
/// and never media (the rows hold embeddings, spans and labels)
pub(crate) fn share_here(args: &[String], cwd: &Path) -> i32 {
let Some(name) = words(args).ok().and_then(|w| w.first().map(|s| s.to_string())) else {
eprintln!("raea fingerprint share: which one? raea fingerprint share NAME --in project|workspace [PATH]");
return 2;
};
let level = flag(args, "--in").unwrap_or("project");
let path = here(cwd, args, 1);
let Some(to) = default_file(&path, level).and_then(|f| f.parent().map(|d| d.join(&name))) else {
eprintln!("raea fingerprint share: {} isn't in a {level} (no .raea/{level} above it)", path.display());
return 1;
};
let from = Folder::named(&name);
let run = || -> anyhow::Result<usize> {
from.read(None)?;
let dest = Folder { dir: to.clone() };
if dest.exists() {
anyhow::bail!("{} has a fingerprint {name} already", to.display());
}
std::fs::create_dir_all(&to)?;
for f in ["fingerprint.ts", "fingerprint.json", "words.json", "words.f16"] {
if from.dir.join(f).is_file() {
std::fs::copy(from.dir.join(f), to.join(f))?;
}
}
let l = from.ledger()?;
dest.write_ledger(&l)?;
Ok(l.rows.len())
};
match run() {
Ok(n) => {
println!("shared {name} into {} with {n} evidence rows, no heads and no media; commit it with the {level}", to.display());
0
}
Err(e) => {
eprintln!("raea fingerprint share: {e:#}");
1
}
}
}
+58
View File
@@ -0,0 +1,58 @@
//! `raea fingerprint postmortem [PROJECT] [--ask N] [--tally]` (docs/fingerprint.feature FP7a; the picking, the clips
//! and the questions are raea-sys-fingerprint-use's postmortem.rs). It scores every version of the project's pieces with
//! the fingerprint that judges the project and asks at most ten yes/no questions in the app; `--tally` makes each answer
//! an evidence row, retrains, and says how each head's held-out score moved.
use crate::{Eval, flag, has};
use anyhow::{Result, anyhow, bail};
use raea_sys_columns::Encoders;
use raea_sys_fingerprint::evidence::{Row, features};
use raea_sys_fingerprint::retrain;
use raea_sys_fingerprint_use::postmortem::{self as pm, MOST};
use raea_sys_fingerprint_use::score::{Scored, score};
use std::path::{Path, PathBuf};
pub(crate) fn run(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
let project = crate::pick::piece_in(args, cwd).parent().map(Path::to_path_buf).unwrap_or_else(|| cwd.to_path_buf());
let name = project.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let (dir, fp, w) = crate::verbs::open(enc, args, eval, Some(&crate::pick::piece_in(args, cwd)))?;
let before = dir.trained()?.map(|t| t.0).ok_or_else(|| anyhow!("{} has no trained heads yet: `raea fingerprint bootstrap` or teach it first", fp.name))?;
if has(args, "--tally") {
let inbox = std::fs::read_to_string(PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(format!(".raea/inbox/{}.jsonl", pm::INBOX))).unwrap_or_default();
let answers = pm::answered(&dir.dir, &inbox);
let mut l = dir.ledger()?;
// every tally adds every answer again, so tallying twice is safe
l.retain(|r| r.source != "postmortem");
for (x, yes) in &answers {
let c = enc.columns(&x.file)?;
let (a, b) = (x.a.min(c.dur), x.b.min(c.dur));
if b - a < 0.5 {
continue;
}
let who = fp.who.clone().unwrap_or_else(|| "me".into());
let row = Row { media: c.media.clone(), a, b, axis: x.axis.clone(), bad: *yes, weight: 1.0, who, source: "postmortem".into(), project: name.clone(), kind: None, region: None, words: Some(x.words.clone()), at: 0, pin: None, band: None };
l.push(row, &features(&c, a, b));
}
dir.write_ledger(&l)?;
let after = retrain(&dir, &fp, &w, &l, None)?;
let f = |v: Option<f64>| v.map_or("-".into(), |v| format!("{v:.2}"));
let mut out = format!("{} answers are evidence now\n", answers.len());
for (axis, was, now) in pm::moved(&before, &after) {
out += &format!(" {axis}: held out {} -> {}\n", f(was), f(now));
}
return Ok((out, 0));
}
let n = flag(args, "--ask").map_or(Ok(MOST), str::parse).map_err(|_| anyhow!("--ask takes a count"))?.min(MOST);
let files = crate::notes::videos(&project);
if files.is_empty() {
bail!("{} has no videos in its feed to look back on", project.display());
}
let scored = files.iter().map(|f| -> Result<Scored> { Ok(score(&fp, Some(&w), Some(&before), &enc.columns(f)?, &f.display().to_string())) }).collect::<Result<Vec<_>>>()?;
let asks = pm::picks(&scored, &before, &fp, &dir.ledger()?, n);
if asks.is_empty() {
return Ok((format!("nothing to ask: on {} versions, no head disagrees with you or sits near its flag\n", files.len()), 0));
}
let item = pm::ask(&std::env::current_exe()?, &dir.dir, &name, &asks)?;
let against = asks.iter().filter(|x| x.why == "disagrees with you").count();
Ok((format!("{} questions on {} versions put to you in the app ({item}): {against} where it disagrees with you, the rest where it's least sure; `raea fingerprint postmortem --tally` adds your answers\n", asks.len(), files.len()), 0))
}
+80
View File
@@ -0,0 +1,80 @@
//! `raea fingerprint profile REFS... --as NAME [--against LIST]` and `score FILE --profile NAME` (docs/fingerprint.feature
//! FP6e): a profile's measures taken from work the person admires, kept in the fingerprint's profiles/NAME.json, and a
//! piece critiqued against it, measure by measure, with where and which way to move.
use crate::{flag, listed, named};
use anyhow::{Context, Result, anyhow, bail};
use raea_sys_columns::{Encoders, media};
use raea_sys_fingerprint::folder::Folder;
use raea_sys_fingerprint_use::profile::{Measures, NAMES, Out, Profile, critique, measures, profile};
use raea_sys_fingerprint_use::score::clock;
use std::path::{Path, PathBuf};
const BINS: usize = 12;
/// The windows the critique says "where" with, seconds
const WIN: f64 = 4.0;
/// A piece's measures, whole and in windows
pub(crate) fn measured(enc: &mut Encoders, file: &Path) -> Result<(Measures, Vec<((f64, f64), Measures)>)> {
let c = enc.columns(file)?;
let pcm = media::sound(file, 16_000).unwrap_or_default();
let cols = ((c.dur * 10.0) as usize).max(1);
let spec = media::spectrogram(&pcm, 16_000, cols, BINS);
let whole = measures(&c, &spec, BINS, 0.0, c.dur);
let n = (c.dur / WIN).ceil() as usize;
let windows = (0..n).map(|i| {
let (a, b) = (i as f64 * WIN, ((i + 1) as f64 * WIN).min(c.dur));
((a, b), measures(&c, &spec, BINS, a, b))
}).collect();
Ok((whole, windows))
}
fn path(dir: &Folder, name: &str) -> PathBuf {
dir.dir.join("profiles").join(format!("{name}.json"))
}
pub(crate) fn make(enc: &mut Encoders, dir: &Folder, args: &[String], cwd: &Path) -> Result<String> {
let name = flag(args, "--as").ok_or_else(|| anyhow!("name it: raea fingerprint profile REFS... --as NAME"))?;
let refs = named(args, cwd)?;
if refs.len() < 2 {
bail!("a profile needs two references or more (three for its leave-one-out check)");
}
let mut r = Vec::new();
for f in &refs {
r.push((f.display().to_string(), measured(enc, f)?.0));
}
let mut other = Vec::new();
if let Some(list) = flag(args, "--against") {
for f in listed(cwd, list)? {
other.push(measured(enc, &f)?.0);
}
}
let p = profile(name, r, &other);
std::fs::create_dir_all(dir.dir.join("profiles"))?;
std::fs::write(path(dir, name), serde_json::to_vec_pretty(&p)?)?;
let mut out = format!("profile {name} from {} references:\n", p.refs.len());
for (k, words) in NAMES {
if let Some((lo, hi)) = p.ranges.get(k) {
out += &format!(" {words:40} {lo:.2} to {hi:.2}\n");
}
}
out += &match (p.inside_own, p.inside_other) {
(Some(o), Some(x)) => format!("leave-one-out: a reference falls in the others' ranges {:.0}% of the time, unrelated work {:.0}%: {}\n", o * 100.0, x * 100.0, if p.tells == Some(true) { "it tells this taste apart" } else { "it does NOT tell this taste apart" }),
(Some(o), None) => format!("leave-one-out: a reference falls in the others' ranges {:.0}% of the time (give --against LIST to compare with unrelated work)\n", o * 100.0),
_ => "leave-one-out needs three references\n".into(),
};
Ok(out)
}
/// The critique of a piece against a saved profile, as lines
pub(crate) fn against(enc: &mut Encoders, dir: &Folder, name: &str, file: &Path) -> Result<(String, Vec<Out>)> {
let p: Profile = serde_json::from_slice(&std::fs::read(path(dir, name)).with_context(|| format!("no profile {name} (raea fingerprint profile REFS... --as {name})"))?)?;
let (whole, windows) = measured(enc, file)?;
let out = critique(&p, &whole, &windows);
let words = |k: &str| NAMES.iter().find(|n| n.0 == k).map_or(k.to_string(), |n| n.1.to_string());
let mut t = format!("against the {name} profile: {}\n", if out.is_empty() { "every measure in range".to_string() } else { format!("{} out of range", out.len()) });
for o in &out {
t += &format!(" {} {:.2} is outside {:.2} to {:.2}: {} it{}\n", words(&o.measure), o.value, o.range.0, o.range.1, o.move_, o.at.map_or(String::new(), |(a, _)| format!(", most at {}", clock(a))));
}
Ok((t, out))
}
+90
View File
@@ -0,0 +1,90 @@
//! Encoder upgrades keep the evidence (docs/fingerprint.feature FP8c). When this machine's encoders aren't the ones a
//! fingerprint was trained on, `raea fingerprint reembed PLACE...` re-embeds every row whose media it finds under
//! those files and folders (matched by content hash), moves the fingerprint to the new encoders and retrains. A row
//! whose media isn't found keeps its old pin and trains no head until it's re-embedded or labelled again; a bootstrap's
//! damaged rows are remade by running the bootstrap again.
use crate::words;
use anyhow::{Result, anyhow};
use raea_sys_columns::{Encoders, media};
use raea_sys_fingerprint::evidence::features;
use raea_sys_fingerprint::folder::Folder;
use raea_sys_fingerprint::taxonomy::Fingerprint;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
const MEDIA: [&str; 9] = ["mp4", "mov", "m4v", "webm", "mkv", "wav", "mp3", "m4a", "flac"];
/// An encoder set's short name, as a row's pin
pub(crate) fn pin_of(p: &BTreeMap<String, String>) -> String {
p.iter().map(|(k, v)| format!("{k}:{}", &v[..v.len().min(8)])).collect::<Vec<_>>().join(",")
}
/// The media files under each place, two folders deep
fn files(places: &[PathBuf]) -> Vec<PathBuf> {
fn walk(d: &Path, depth: usize, out: &mut Vec<PathBuf>) {
for e in std::fs::read_dir(d).into_iter().flatten().flatten() {
let p = e.path();
if p.is_dir() && depth > 0 {
walk(&p, depth - 1, out);
} else if MEDIA.iter().any(|m| p.extension().is_some_and(|x| x.eq_ignore_ascii_case(m))) {
out.push(p);
}
}
}
let mut out = Vec::new();
for p in places {
if p.is_dir() { walk(p, 2, &mut out) } else { out.push(p.clone()) }
}
out
}
/// Rows moved to `here`'s encoders where their media is found; returns the fingerprint as it is now and what happened
pub(crate) fn reembed(enc: &mut Encoders, dir: &Folder, mut fp: Fingerprint, here: BTreeMap<String, String>, args: &[String], cwd: &Path) -> Result<(Fingerprint, String)> {
let places: Vec<PathBuf> = words(args).map_err(|e| anyhow!(e))?.iter().map(|f| cwd.join(f)).collect();
let mut l = dir.ledger()?;
if fp.encoders != here {
let old = pin_of(&fp.encoders);
l.rows.iter_mut().filter(|r| r.pin.is_none()).for_each(|r| r.pin = Some(old.clone()));
fp.encoders = here;
dir.rewrite(&fp)?;
}
let waiting: std::collections::BTreeSet<String> = l.rows.iter().filter(|r| r.pin.is_some() && !matches!(r.source.as_str(), "damage" | "cheat")).map(|r| r.media.clone()).collect();
let mut done = 0;
for f in files(&places) {
if waiting.is_empty() {
break;
}
let Ok(sha) = media::sha256(&f) else { continue };
if !waiting.contains(&sha) {
continue;
}
let c = enc.columns(&f)?;
for i in 0..l.rows.len() {
let r = &l.rows[i];
if r.media == sha && r.pin.is_some() && !matches!(r.source.as_str(), "damage" | "cheat") {
let x = features(&c, r.a, r.b);
l.set_features(i, &x);
l.rows[i].pin = None;
done += 1;
}
}
}
dir.write_ledger(&l)?;
let left = l.rows.iter().filter(|r| r.pin.is_some()).count();
let damage = l.rows.iter().filter(|r| r.pin.is_some() && matches!(r.source.as_str(), "damage" | "cheat")).count();
let mut out = format!("re-embedded {done} rows on this machine's encoders; {left} wait on their old ones");
if damage > 0 {
out += &format!(" ({damage} from a bootstrap: run raea fingerprint bootstrap again to remake them)");
}
Ok((fp, out + "\n"))
}
#[cfg(test)]
mod tests {
#[test]
fn a_pin_names_each_encoder_and_its_hash() {
let p = std::collections::BTreeMap::from([("clap".to_string(), "0123456789abcdef".to_string()), ("siglip".to_string(), "fedcba".to_string())]);
assert_eq!(super::pin_of(&p), "clap:01234567,siglip:fedcba");
}
}
+141
View File
@@ -0,0 +1,141 @@
//! The resident service: the encoders loaded once, on 127.0.0.1 at a port the host file names
//! (~/.raea/fingerprints/.serve.json). A request is one JSON line, {"args": [...], "cwd": "..."}; the answer is
//! progress lines, {"say": "..."}, then {"out": "...", "code": N}. One request at a time, in order.
use crate::{Eval, verbs};
use anyhow::{Context, Result};
use raea_sys_columns::Encoders;
use raea_sys_fingerprint::folder::root;
use serde_json::{Value, json};
use std::io::{BufRead, BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
/// The service leaves after this long with no request
const IDLE: Duration = Duration::from_secs(30 * 60);
/// How long a verb waits for a service it started to come up (the first run fetches the models)
const UP: Duration = Duration::from_secs(900);
fn host() -> PathBuf {
root().join(".serve.json")
}
fn now() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}
/// `raea fingerprint serve`: load the encoders, listen, answer until idle or stopped
pub fn serve(eval: Eval) -> Result<()> {
let started = Instant::now();
let mut enc = Encoders::load().context("loading the encoders")?;
let listener = TcpListener::bind("127.0.0.1:0")?;
let port = listener.local_addr()?.port();
std::fs::create_dir_all(root())?;
std::fs::write(host(), json!({"port": port, "pid": std::process::id()}).to_string())?;
eprintln!("raea fingerprint serve: encoders loaded in {:.1} s, on 127.0.0.1:{port}", started.elapsed().as_secs_f64());
let last = Arc::new(AtomicU64::new(now()));
let seen = last.clone();
std::thread::spawn(move || {
loop {
std::thread::sleep(Duration::from_secs(60));
if now().saturating_sub(seen.load(Ordering::Relaxed)) > IDLE.as_secs() {
let _ = std::fs::remove_file(host());
eprintln!("raea fingerprint serve: idle for {} min, leaving", IDLE.as_secs() / 60);
std::process::exit(0);
}
}
});
for stream in listener.incoming() {
let Ok(mut s) = stream else { continue };
last.store(now(), Ordering::Relaxed);
let mut line = String::new();
if BufReader::new(&s).read_line(&mut line).is_err() {
continue;
}
let req: Value = serde_json::from_str(&line).unwrap_or_default();
let args: Vec<String> = serde_json::from_value(req["args"].clone()).unwrap_or_default();
let cwd = PathBuf::from(req["cwd"].as_str().unwrap_or("."));
if args.first().is_some_and(|v| v == "stop") {
let _ = writeln!(s, "{}", json!({"out": "raea fingerprint serve: stopped", "code": 0}));
let _ = std::fs::remove_file(host());
return Ok(());
}
let mut say = |m: String| {
let _ = writeln!(s, "{}", json!({ "say": m }));
};
let (out, code) = verbs::run(&mut enc, &args, &cwd, eval, &mut say);
let _ = writeln!(s, "{}", json!({"out": out, "code": code}));
last.store(now(), Ordering::Relaxed);
}
Ok(())
}
/// A verb run in this process, with the encoders loaded for it
pub(crate) fn here(args: &[String], cwd: &Path, eval: Eval) -> (String, i32) {
match Encoders::load() {
Ok(mut enc) => verbs::run(&mut enc, args, cwd, eval, &mut |m| eprintln!("{m}")),
Err(e) => (format!("raea fingerprint: loading the encoders: {e:#}"), 1),
}
}
fn reach() -> Option<TcpStream> {
let h: Value = serde_json::from_slice(&std::fs::read(host()).ok()?).ok()?;
TcpStream::connect(("127.0.0.1", h["port"].as_u64()? as u16)).ok()
}
/// The service started in the background, its output in ~/.raea/fingerprints/.serve.log; its stream once it's up
fn start() -> Result<TcpStream, String> {
let _ = std::fs::remove_file(host());
std::fs::create_dir_all(root()).map_err(|e| e.to_string())?;
let log = root().join(".serve.log");
let file = std::fs::File::create(&log).map_err(|e| e.to_string())?;
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let mut cmd = std::process::Command::new(exe);
cmd.args(["fingerprint", "serve"]).stdin(std::process::Stdio::null()).stdout(file.try_clone().map_err(|e| e.to_string())?).stderr(file);
#[cfg(unix)]
std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
let mut child = cmd.spawn().map_err(|e| format!("starting the service: {e}"))?;
eprintln!("raea fingerprint: starting the service (loading the encoders once; its log is {})", log.display());
let t = Instant::now();
while t.elapsed() < UP {
if let Some(s) = reach() {
return Ok(s);
}
if let Ok(Some(status)) = child.try_wait() {
let tail = std::fs::read_to_string(&log).unwrap_or_default();
return Err(format!("the service stopped ({status}):\n{}", tail.lines().rev().take(12).collect::<Vec<_>>().into_iter().rev().collect::<Vec<_>>().join("\n")));
}
std::thread::sleep(Duration::from_millis(200));
}
let _ = child.kill();
Err(format!("the service didn't come up in {} s (see {})", UP.as_secs(), log.display()))
}
/// A verb sent to the service, started if it isn't running; its progress printed as it comes
pub(crate) fn call(args: &[String], cwd: &Path) -> (String, i32) {
let stream = match reach() {
Some(s) => Ok(s),
None if args.first().is_some_and(|v| v == "stop") => return ("raea fingerprint: no service running".into(), 0),
None => start(),
};
let mut s = match stream {
Ok(s) => s,
Err(e) => return (format!("raea fingerprint: {e}"), 1),
};
if writeln!(s, "{}", json!({"args": args, "cwd": cwd})).is_err() {
return ("raea fingerprint: the service closed the connection".into(), 1);
}
for line in BufReader::new(s).lines() {
let Ok(line) = line else { break };
let v: Value = serde_json::from_str(&line).unwrap_or_default();
if let Some(m) = v["say"].as_str() {
eprintln!("{m}");
} else if v.get("code").is_some() {
return (v["out"].as_str().unwrap_or("").to_string(), v["code"].as_i64().unwrap_or(1) as i32);
}
}
("raea fingerprint: the service ended without an answer (see ~/.raea/fingerprints/.serve.log)".into(), 1)
}
+31
View File
@@ -0,0 +1,31 @@
//! `raea fingerprint things FILE [--project P] [--json]` (docs/fingerprint.feature FP13a, FP13c): a piece's shots,
//! their things (a render's layers, and every mark a person drew on a note of it in P's feed, P the folder it runs in
//! by default) and the camera's path, with what floats, passes through, lurches or is empty
//! (raea-sys-fingerprint-things). `--json` prints it all for `raea check --things`.
use crate::{flag, has};
use anyhow::Result;
use raea_sys_columns::Encoders;
use raea_sys_fingerprint_things::things::{Mark, things};
use std::path::{Path, PathBuf};
pub(crate) fn run(enc: &mut Encoders, args: &[String], cwd: &Path) -> Result<(String, i32)> {
let file = cwd.join(args.first().filter(|a| !a.starts_with("--")).ok_or_else(|| anyhow::anyhow!("things FILE"))?);
let project = flag(args, "--project").map_or_else(|| cwd.to_path_buf(), |p| cwd.join(p));
let me = file.canonicalize().ok();
let marks: Vec<Mark> = crate::notes::pinned(&project)
.into_iter()
.filter(|r| r.media.canonicalize().ok() == me)
.filter_map(|r| Some(Mark { name: r.text.chars().take(40).collect(), t: r.t, a: (r.t - 1.0).max(0.0), b: r.to.unwrap_or(r.t + 1.0), region: r.region? }))
.collect();
let t = things(enc, &file, &marks)?;
if has(args, "--json") {
return Ok((serde_json::to_string_pretty(&t)?, 0));
}
let n: usize = t.shots.iter().map(|s| s.things.len()).sum();
let mut out = format!("{}: {} shots, {n} things seen ({} marked), {} findings\n", PathBuf::from(&t.file).display(), t.shots.len(), marks.len(), t.issues.len());
for i in &t.issues {
out += &format!(" {:>6.1} s {} {}\n", i.at, i.rule, i.says);
}
Ok((out, 0))
}
+398
View File
@@ -0,0 +1,398 @@
//! The verbs, run with the encoders loaded: new, bootstrap, teach and score; and report, which needs no encoders.
use crate::{Eval, at, flag, has, listed, named, words};
use anyhow::{Context, Result, anyhow, bail};
use raea_sys_columns::{Encoders, FPS, media};
use raea_sys_fingerprint::evidence::{Ledger, Row, features};
use raea_sys_fingerprint::folder::{Folder, root};
use raea_sys_fingerprint::inherit;
use raea_sys_fingerprint_use::score::{Scored, clock, score, summary, timeline};
use raea_sys_fingerprint_use::sheet::{Tick, sheet};
use raea_sys_fingerprint::taxonomy::{Applies, Fingerprint, base, words_of};
use raea_sys_fingerprint::words::Words;
use crate::bootstrap;
use raea_sys_fingerprint::{report_text, retrain};
use serde_json::json;
use std::path::Path;
/// The fingerprint a verb is about: --fp, else the one `new` made first, else "me"
/// A verb's answer and exit code
pub(crate) fn run(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval, say: &mut dyn FnMut(String)) -> (String, i32) {
let rest = &args[1..];
let ran = match args[0].as_str() {
"new" => new(enc, rest),
"bootstrap" => boot(enc, rest, cwd, eval, say),
"teach" => teach(enc, rest, cwd, eval),
"approve" => approved(enc, rest, cwd, eval),
"reembed" => reembedded(enc, rest, cwd, eval),
"pair" | "versions" => paired(enc, args[0].as_str(), rest, cwd, eval),
"learn-notes" => learned(enc, rest, cwd, eval),
"move" => moved(enc, rest, eval),
"postmortem" => crate::postmortem::run(enc, rest, cwd, eval),
"things" => crate::things::run(enc, rest, cwd),
"profile" => {
let dir = crate::pick::chosen(rest, None).0;
crate::profiles::make(enc, &dir, rest, cwd).map(|o| (o, 0))
}
"score" => scored(enc, rest, cwd, eval),
v => Err(anyhow!("no verb {v}")),
};
ran.unwrap_or_else(|e| (format!("raea fingerprint {}: {e:#}", args[0]), 1))
}
/// A new fingerprint as `new` makes it: raea's base axes, or the axes of the one it --extends, with --who and --about,
/// and the kinds of piece and project tags it judges (--kinds, --tags, each comma-separated)
pub(crate) fn shaped(short: &str, args: &[String], parent: Option<Fingerprint>) -> Fingerprint {
let mut fp = base(short);
if let Some(p) = parent {
fp.axes = p.axes;
fp.extends = Some(p.name);
}
fp.who = flag(args, "--who").map(str::to_string).or_else(|| std::env::var("USER").ok());
fp.about = flag(args, "--about").map(str::trim).filter(|a| !a.is_empty()).map(str::to_string);
let (kinds, tags) = (flag(args, "--kinds").map(words_of).unwrap_or_default(), flag(args, "--tags").map(words_of).unwrap_or_default());
if !kinds.is_empty() || !tags.is_empty() {
fp.applies = Some(Applies { kinds, tags });
}
fp
}
fn new(enc: &mut Encoders, args: &[String]) -> Result<(String, i32)> {
let n = *words(args).map_err(|e| anyhow!(e))?.first().ok_or_else(|| anyhow!("name it: raea fingerprint new NAME"))?;
let dir = Folder::named(n);
let short = dir.dir.file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| n.into());
let parent = match flag(args, "--extends") {
Some(p) => Some(Folder::named(p).read(None).with_context(|| format!("--extends {p}"))?),
None => None,
};
let from = parent.as_ref().map(|p| format!("{}'s axes", p.name)).unwrap_or_else(|| "raea's base taxonomy".into());
let mut fp = shaped(&short, args, parent);
fp.encoders = enc.pins();
dir.create(&fp)?;
let w = Words::build(enc, &fp)?;
dir.write_words(&w)?;
retrain(&dir, &fp, &w, &Ledger::default(), None)?;
if !root().join("default").exists() && dir.dir.parent() == Some(root().as_path()) {
std::fs::write(root().join("default"), &short)?;
}
Ok((
format!(
"made {}: {} axes from {from}, {} scoring from their words today (advice until they earn a gate)\n edit {} to add, remove or reword axes\n next: raea fingerprint bootstrap FILE... with your own finished work trains the mechanical axes",
dir.dir.display(),
fp.axes.len(),
w.axes.len(),
dir.ts().display()
),
0,
))
}
/// The fingerprint, its encoders checked against this machine's, and its words, made again when they changed
/// The fingerprint a verb uses (pick.rs: --fp, else the one that judges the file), its axes with its parents', and its
/// words
pub(crate) fn open(enc: &mut Encoders, args: &[String], eval: Eval, file: Option<&Path>) -> Result<(Folder, Fingerprint, Words)> {
let dir = crate::pick::chosen(args, file).0;
let mut raw = dir.read(Some(eval))?;
let here = enc.pins();
if raw.encoders.is_empty() {
raw.encoders = here;
dir.rewrite(&raw)?;
} else if here.iter().filter(|(k, v)| raw.encoders.get(*k) == Some(*v)).count() == raw.encoders.len() && raw.encoders != here {
// an encoder added since (EmbeddingGemma 2, FP1b) doesn't change the ones it was trained on
raw.encoders = here;
dir.rewrite(&raw)?;
} else if raw.encoders != here {
bail!(
"{} was trained on other encoders ({:?}) than this machine has ({:?}); its heads refuse these columns. `raea fingerprint reembed FOLDER...` moves its evidence to these, re-embedding the rows whose media it finds",
dir.ts().display(),
raw.encoders,
here
);
}
// a fingerprint that extends another judges with its parents' axes too (FP14b)
let fp = inherit::axes(&raw, &inherit::parents(&raw, Some(eval)));
let w = match dir.words().filter(|w| !w.stale(&fp)) {
Some(w) => w,
None => {
let w = Words::build(enc, &fp)?;
dir.write_words(&w)?;
w
}
};
// a shared fingerprint arrives with evidence and no heads: this machine trains its own (FP8a)
if !dir.dir.join("heads.safetensors").is_file() {
let l = dir.ledger()?;
if !l.rows.is_empty() {
retrain(&dir, &fp, &w, &l, None)?;
}
}
Ok((dir, fp, w))
}
fn boot(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval, say: &mut dyn FnMut(String)) -> Result<(String, i32)> {
let (dir, fp, w) = open(enc, args, eval, None)?;
let mut files = named(args, cwd)?;
if let Some(list) = flag(args, "--from") {
files.extend(listed(cwd, list)?);
}
if files.is_empty() {
bail!("give it real finished work: raea fingerprint bootstrap FILE... or --from LIST (no placeholder footage)");
}
let per: usize = flag(args, "--per").map_or(Ok(10), str::parse).context("--per takes a count")?;
let mut l = dir.ledger()?;
let who = fp.who.clone().unwrap_or_else(|| "me".into());
let made = bootstrap::rows(enc, &who, &files, per, &mut l, say)?;
dir.write_ledger(&l)?;
say(format!("{} windows from {} sources; measuring held out by source", made.windows, made.sources));
let curves = bootstrap::curves(&fp, &l);
let ws = bootstrap::word_scores(&l, &w);
let patches = raea_sys_fingerprint_things::located::bootstrap(enc, &dir.dir, &files, per, say)?;
let b = json!({"made": made, "per": per, "sources": files, "curves": curves, "words": ws, "patches": patches});
retrain(&dir, &fp, &w, &l, Some(b))?;
Ok((report_text(&dir.report().unwrap_or_default()), 0))
}
/// The project a file belongs to: the folder holding .raea/project above it, else the folder it's in
fn project_of(file: &Path) -> String {
let mut d = file.parent();
while let Some(p) = d {
if p.join(".raea/project").exists() {
return p.file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
}
d = p.parent();
}
file.parent().and_then(|p| p.file_name()).map(|s| s.to_string_lossy().into_owned()).unwrap_or_default()
}
/// `approve`: approved work as clean rows on every axis (approve.rs, FP6a), then the heads retrained
fn approved(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
let first = words(args).map_err(|e| anyhow!(e))?.first().map(|f| at(cwd, f));
let (dir, fp, w) = open(enc, args, eval, first.as_deref())?;
let (mut out, _) = crate::approve::approve(enc, &dir, &fp, args, cwd, project_of)?;
let tr = retrain(&dir, &fp, &w, &dir.ledger()?, None)?;
out += &format!("{} axes gating\n", tr.heads.iter().filter(|h| h.state == "gating").count());
Ok((out, 0))
}
/// `reembed`: the evidence moved to this machine's encoders (reembed.rs, FP8c), the words remade and the heads retrained
fn reembedded(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
let dir = crate::pick::chosen(args, None).0;
let raw = dir.read(Some(eval))?;
let (fp, out) = crate::reembed::reembed(enc, &dir, raw, enc.pins(), args, cwd)?;
let fp = inherit::axes(&fp, &inherit::parents(&fp, Some(eval)));
let w = Words::build(enc, &fp)?;
dir.write_words(&w)?;
retrain(&dir, &fp, &w, &dir.ledger()?, None)?;
Ok((out, 0))
}
/// `pair` and `versions` (pairing.rs, FP6b, FP6c), then the heads retrained
fn paired(enc: &mut Encoders, verb: &str, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
let first = words(args).map_err(|e| anyhow!(e))?.first().map(|f| at(cwd, f));
let (dir, fp, w) = open(enc, args, eval, first.as_deref())?;
let who = fp.who.clone().unwrap_or_else(|| "me".into());
let mut l = dir.ledger()?;
let out = if verb == "pair" { crate::pairing::pair(enc, &mut l, &who, args, cwd, project_of)? } else { crate::pairing::versions(enc, &mut l, &who, args, cwd, project_of)? };
dir.write_ledger(&l)?;
retrain(&dir, &fp, &w, &l, None)?;
Ok((out, 0))
}
/// `learn-notes [PROJECT]` (notes.rs, FP5a): checked readings as evidence in the fingerprint that judges the project
/// (FP14d), then its heads retrained
fn learned(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
let (dir, fp, w) = open(enc, args, eval, Some(&crate::pick::piece_in(args, cwd)))?;
let mut l = dir.ledger()?;
let out = crate::notes::learn(enc, &dir, &mut l)?;
dir.write_ledger(&l)?;
retrain(&dir, &fp, &w, &l, None)?;
Ok((out, 0))
}
/// `move` (moving.rs, FP14d): a child's own labels up into a fingerprint it extends, then both retrained
fn moved(enc: &mut Encoders, args: &[String], eval: Eval) -> Result<(String, i32)> {
let (dir, fp, w) = open(enc, args, eval, None)?;
let (to, out) = crate::moving::up(&dir, &dir.read(Some(eval))?, args, eval)?;
retrain(&dir, &fp, &w, &dir.ledger()?, None)?;
let (pd, pfp, pw) = open(enc, &["--fp".into(), to], eval, None)?;
retrain(&pd, &pfp, &pw, &pd.ledger()?, None)?;
Ok((out, 0))
}
fn teach(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
let file = at(cwd, words(args).map_err(|e| anyhow!(e))?.first().ok_or_else(|| anyhow!("which file?"))?);
let (dir, fp, w) = open(enc, args, eval, Some(&file))?;
let axis = flag(args, "--axis").ok_or_else(|| anyhow!("--axis A (or \"*\" for every axis)"))?;
if axis != "*" && fp.axis(axis).is_none() {
bail!("no axis {axis:?} in {}: its axes are {}", dir.ts().display(), fp.axes.iter().map(|a| a.name.as_str()).collect::<Vec<_>>().join(", "));
}
let t: f64 = flag(args, "--at").ok_or_else(|| anyhow!("--at SECONDS"))?.parse().context("--at takes seconds")?;
let span: f64 = flag(args, "--span").map_or(Ok(2.0), str::parse).context("--span takes seconds")?;
let region = flag(args, "--box").map(|b| -> Result<[f32; 4]> {
let v: Vec<f32> = b.split(',').map(str::parse).collect::<Result<_, _>>().context("--box takes x0,y0,x1,y1 in 0-1")?;
v.try_into().map_err(|_| anyhow!("--box takes four numbers"))
});
let c = enc.columns(&file)?;
let a = (t - span / 2.0).clamp(0.0, (c.dur - span).max(0.0));
let b = (a + span).min(c.dur);
let bad = !has(args, "--good");
let row = Row {
media: c.media.clone(),
a,
b,
axis: axis.into(),
bad,
weight: 1.0,
who: fp.who.clone().unwrap_or_else(|| "me".into()),
source: "teach".into(),
project: flag(args, "--project").map_or_else(|| project_of(&file), str::to_string),
kind: None,
region: region.transpose()?,
words: flag(args, "--words").map(str::to_string),
at: 0,
pin: None,
band: None,
};
let mut l = dir.ledger()?;
l.push(row, &features(&c, a, b));
dir.write_ledger(&l)?;
let tr = retrain(&dir, &fp, &w, &l, None)?;
let h = tr.heads.iter().find(|h| h.axis == axis);
let (p, n) = l.for_axis(axis).iter().fold((0, 0), |(p, n), &i| if l.rows[i].bad { (p + 1, n) } else { (p, n + 1) });
Ok((
format!(
"taught {axis}: {} at {} in {}\n {axis} has {p} defect and {n} clean labels; its head: {}",
if bad { "the defect" } else { "clean" },
clock(t),
file.display(),
h.map_or("every axis's clean labels grew".to_string(), |h| format!("{} ({})", h.state, h.why))
),
0,
))
}
/// raea check's findings on the file, in seconds: (rule, from, to, what)
fn checks(file: &Path) -> Vec<(String, f64, f64, String)> {
let Ok(found) = raea_app_check::floor(&[file.display().to_string()], &[], &[]) else { return Vec::new() };
found.into_iter().map(|f| {
let (a, b) = f.frames.map_or((0.0, 0.0), |[a, b]| (a as f64 / 30.0, b as f64 / 30.0));
(f.check, a, b, f.says)
}).collect()
}
/// A check wins over a head (FP4c): a moment on an axis a check measures is no gate unless the check found it too
fn arbitrate(s: &mut Scored, fp: &Fingerprint, found: &[(String, f64, f64, String)]) {
for m in &mut s.moments {
let Some(rule) = fp.axis(&m.axis).and_then(|a| a.check.as_deref()) else { continue };
let agrees = found.iter().any(|(r, a, b, _)| r == rule && *a <= m.b + 1.0 && *b >= m.a - 1.0);
if !agrees {
m.gating = false;
m.state = format!("{}; the {rule} check found none", m.state);
}
}
}
fn scored(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
let file = at(cwd, words(args).map_err(|e| anyhow!(e))?.first().ok_or_else(|| anyhow!("which file?"))?);
let (dir, fp, w) = open(enc, args, eval, Some(&file))?;
let why = crate::pick::chosen(args, Some(&file)).1.map_or_else(|| "named with --fp, or the account's default".to_string(), |c| c.why);
let c = enc.columns(&file)?;
let trained = dir.trained()?.map(|(t, _)| t);
let mut s = score(&fp, Some(&w), trained.as_ref(), &c, &file.display().to_string());
let found = checks(&file);
arbitrate(&mut s, &fp, &found);
raea_sys_fingerprint_things::located::locate(enc, &file, &raea_sys_fingerprint_use::patch::load(&dir.dir), &mut s)?;
// FP9a: each gating flag on the cut before, judged on this one, and its axis's disguises rerun on the fix
let fixes = match flag(args, "--was") {
Some(old) => {
let was = at(cwd, old);
let mut ws = score(&fp, Some(&w), trained.as_ref(), &enc.columns(&was)?, &was.display().to_string());
arbitrate(&mut ws, &fp, &checks(&was));
Some(raea_sys_fingerprint_use::fixed::fixes(&ws, &s, &fp, &dir.ledger()?, &c))
}
None => None,
};
let mut out = if has(args, "--json") {
serde_json::to_string_pretty(&json!({"fingerprint": {"name": fp.name, "about": fp.about, "why": why}, "scored": s, "checks": found.iter().map(|(r, a, b, says)| json!({"check": r, "a": a, "b": b, "says": says})).collect::<Vec<_>>(), "fixes": fixes}))?
} else if let Some(f) = &fixes {
let mut t = format!("judged by {}: {why}\n", fp.name);
t += &raea_sys_fingerprint_use::fixed::said(f);
t += &summary(&s);
t
} else {
let mut t = format!("judged by {}: {why}\n", fp.name);
t += &summary(&s);
t += &format!("checks: {}\n", if found.is_empty() { "no findings".to_string() } else { format!("{} findings", found.len()) });
for (r, a, _, says) in &found {
t += &format!(" {} {r}: {says}\n", clock(*a));
}
t
};
if has(args, "--timeline") {
out += &timeline(&s);
}
if let Some(p) = flag(args, "--profile") {
out += &crate::profiles::against(enc, &dir, p, &file)?.0;
}
if let Some(png) = flag(args, "--sheet") {
let png = at(cwd, png);
let frames: Vec<media::Rgb> = (0..12).filter_map(|i| media::frames(&file, FPS, c.dur * (i as f64 + 0.5) / 12.0, 0.25).ok()?.into_iter().next()).collect();
let pcm = media::sound(&file, 16_000)?;
let ticks: Vec<Tick> = found.iter().map(|(r, a, b, _)| Tick { a: *a, b: *b, what: r.clone() }).collect();
sheet(&s, &frames, &pcm, &ticks, &|axis| fp.axis(axis).map(|a| a.modality), &png)?;
out += &format!("sheet: {}\n", png.display());
}
let unfixed = fixes.iter().flatten().any(|f| f.verdict != "fixed");
Ok((out, i32::from(unfixed || s.moments.iter().any(|m| m.gating))))
}
/// `raea fingerprint report`: report.json, read; no encoders needed
pub(crate) fn report_here(args: &[String]) -> i32 {
let dir = crate::pick::chosen(args, None).0;
match dir.report() {
Some(r) if has(args, "--json") => {
println!("{}", serde_json::to_string_pretty(&r).unwrap_or_default());
0
}
Some(r) => {
println!("{}", report_text(&r).trim_end());
0
}
None => {
eprintln!("raea fingerprint report: no report at {} (`raea fingerprint new NAME` makes one)", dir.dir.display());
1
}
}
}
#[cfg(test)]
mod tests {
use super::shaped;
use raea_sys_fingerprint::taxonomy::{Applies, base};
fn args(xs: &[&str]) -> Vec<String> {
xs.iter().map(|x| x.to_string()).collect()
}
/// FP14a: a new fingerprint says what it's for, and one that extends another starts from its axes
#[test]
fn a_new_fingerprint_says_what_its_for_and_what_it_builds_on() {
let own = shaped("me", &args(&["me", "--who", "w"]), None);
assert_eq!((own.about.as_deref(), own.extends.as_deref(), own.who.as_deref()), (None, None, Some("w")));
assert_eq!(own.axes, base("me").axes);
let mut parent = base("me");
parent.axes.truncate(2);
parent.axes[0].words = vec!["a soft picture".into()];
let ads = shaped("ads", &args(&["ads", "--about", " Short ads for one brand ", "--extends", "me"]), Some(parent.clone()));
assert_eq!(ads.name, "ads");
assert_eq!(ads.about.as_deref(), Some("Short ads for one brand"));
assert_eq!(ads.extends.as_deref(), Some("me"));
assert_eq!(ads.axes, parent.axes);
assert_eq!(shaped("x", &args(&["x", "--about", " "]), None).about, None);
assert_eq!(own.applies, None);
let judged = shaped("ads", &args(&["ads", "--kinds", "ad, Playable", "--tags", "brand,"]), None);
assert_eq!(judged.applies, Some(Applies { kinds: vec!["ad".into(), "playable".into()], tags: vec!["brand".into()] }));
}
}
+2
View File
@@ -23,6 +23,8 @@ raea-runtime-react = { path = "../../runtime/react", default-features = false }
raea-runtime-page = { path = "../../runtime/page" }
raea-runtime-export = { path = "../../runtime/export" }
raea-runtime-live = { path = "../../runtime/live" }
# its switches (env_on)
raea-io-home = { path = "../../io/home" }
serde_json = "1"
winit = "=0.30.13"
raea-gpu-device = { path = "../../gpu/device" }
+1 -1
View File
@@ -212,7 +212,7 @@ impl ApplicationHandler for Player {
}
pub(crate) fn probing() -> bool {
std::env::var("RAEA_PLAYER_PROBE").as_deref() == Ok("1")
raea_io_home::env_on("RAEA_PLAYER_PROBE")
}
pub(crate) fn windowed(game: Game) -> R<String> {
+17
View File
@@ -0,0 +1,17 @@
[package]
name = "raea-app-interchange"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "A composition's 3D as data another tool builds (`raea scene export`: scene.json, its meshes and models), a Godot project written from it, and what changed in Blender or Godot read back as edits to the TSX (docs/blender.feature BL37-BL39, docs/godot.feature GD12-GD13)"
[dependencies]
# the composition bundled and stepped to its frames' 3D (raea-runtime-export's scene_frames), walked into parts
raea-runtime-bundle = { path = "../../runtime/bundle" }
raea-runtime-export = { path = "../../runtime/export" }
raea-runtime-scene = { path = "../../runtime/scene" }
raea-core-scene = { path = "../../core/scene" }
# a mesh that isn't a primitive written as a .glb (Manifold's)
raea-core-shape = { path = "../../core/shape" }
serde_json = "1"
+209
View File
@@ -0,0 +1,209 @@
//! What changed in Blender or Godot, as edits to the TSX at their lines (docs/blender.feature BL39, docs/godot.feature
//! GD13). The scene went out as scene.json; Blender's or Godot's reader (sdk/blender/src/scene.ts's readBack,
//! sdk/godot/src/host/back.ts) writes what it holds now in the same terms (raea's axes, each object's raea_id), and this
//! compares the two at the first frame sent. Nothing in the TSX is changed here: the agent makes the edits.
use std::path::Path;
use serde_json::{Value, json};
/// A placement's numbers (x y z, qx qy qz qw, sx sy sz), or None.
fn nums(a: &Value) -> Option<Vec<f64>> {
let v: Vec<f64> = a.as_array()?.iter().filter_map(Value::as_f64).collect();
(v.len() >= 10).then_some(v)
}
fn r4(x: f64) -> f64 {
(x * 1e4).round() / 1e4
}
/// A quaternion (x y z w) as Euler angles X, Y, Z in radians, applied X then Y then Z (three.js' and raea's default
/// order for `rotation={[x, y, z]}`).
pub fn euler_xyz(q: &[f64]) -> [f64; 3] {
let (x, y, z, w) = (q[0], q[1], q[2], q[3]);
let m02 = 2.0 * (x * z + y * w);
let (m12, m22) = (2.0 * (y * z - x * w), 1.0 - 2.0 * (x * x + y * y));
let (m01, m00) = (2.0 * (x * y - z * w), 1.0 - 2.0 * (y * y + z * z));
let ey = m02.clamp(-1.0, 1.0).asin();
let (ex, ez) = if m02.abs() < 0.999_999 { ((-m12).atan2(m22), (-m01).atan2(m00)) } else { ((2.0 * (y * z + x * w)).atan2(1.0 - 2.0 * (x * x + z * z)), 0.0) };
[r4(ex), r4(ey), r4(ez)]
}
/// The angle between two rotations, in degrees.
fn turned(a: &[f64], b: &[f64]) -> f64 {
let d = (a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]).abs().min(1.0);
2.0 * d.acos().to_degrees()
}
/// One edit onto the list: the part, what changed, the prop with its old and new values, and the line said for it.
fn edit(out: &mut Vec<Value>, part: &Value, what: &str, prop: &str, from: Value, to: Value, said: String) {
out.push(json!({ "id": part["id"], "name": part["source"]["name"], "loc": part["source"]["loc"], "change": what, "prop": prop, "from": from, "to": to, "says": said }));
}
fn surface(p: &Value, sent: &Value, now: &Value, out: &mut Vec<Value>) {
if !now.is_object() {
return;
}
if let (Some(a), Some(b)) = (sent["color"].as_str(), now["color"].as_str())
&& !a.eq_ignore_ascii_case(b)
{
edit(out, p, "recoloured", "color", json!(a), json!(b), format!("color {a} -> {b}"));
}
for (k, prop) in [("roughness", "roughness"), ("metallic", "metalness"), ("intensity", "intensity")] {
if let (Some(a), Some(b)) = (sent[k].as_f64(), now[k].as_f64())
&& (a - b).abs() > 0.005 * a.abs().max(1.0)
{
edit(out, p, if k == "intensity" { "relit" } else { "resurfaced" }, prop, json!(r4(a)), json!(r4(b)), format!("{prop} {} -> {}", r4(a), r4(b)));
}
}
if now["emissive"].as_str().is_some() && sent["emissive"].as_str() != now["emissive"].as_str() {
edit(out, p, "glows", "emissive", sent["emissive"].clone(), now["emissive"].clone(), format!("emissive {} -> {}", sent["emissive"].as_str().unwrap_or("none"), now["emissive"].as_str().unwrap_or("none")));
}
}
fn placement(p: &Value, a: &[f64], b: &[f64], out: &mut Vec<Value>) {
let d = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
if d.iter().any(|x| x.abs() > 1e-3) {
let to = [r4(b[0]), r4(b[1]), r4(b[2])];
edit(out, p, "moved", "position", json!([r4(a[0]), r4(a[1]), r4(a[2])]), json!(to), format!("moved by [{}, {}, {}] to {to:?} (world)", r4(d[0]), r4(d[1]), r4(d[2])));
}
if turned(&a[3..7], &b[3..7]) > 0.05 {
let e = euler_xyz(&b[3..7]);
edit(out, p, "turned", "rotation", json!(euler_xyz(&a[3..7])), json!(e), format!("turned {:.1} degrees: rotation {e:?} (radians, X Y Z; world), quaternion [{}, {}, {}, {}]", turned(&a[3..7], &b[3..7]), r4(b[3]), r4(b[4]), r4(b[5]), r4(b[6])));
}
if (0..3).any(|k| (a[7 + k] - b[7 + k]).abs() > 1e-3 * a[7 + k].abs().max(1.0)) {
let to = [r4(b[7]), r4(b[8]), r4(b[9])];
edit(out, p, "scaled", "scale", json!([r4(a[7]), r4(a[8]), r4(a[9])]), json!(to), format!("scale {to:?}"));
}
}
/// The edits from `sent` (scene.json) to `now` (what Blender or Godot holds), at the first frame sent.
pub fn compare(sent: &Value, now: &Value) -> Vec<Value> {
let mut out = Vec::new();
let held: Vec<&Value> = now["parts"].as_array().into_iter().flatten().collect();
for p in sent["parts"].as_array().into_iter().flatten() {
let Some(n) = held.iter().find(|n| n["id"] == p["id"]) else {
edit(&mut out, p, "deleted", "", Value::Null, Value::Null, "deleted".into());
continue;
};
let first = p["at"].as_array().into_iter().flatten().find(|a| !a.is_null()).and_then(nums);
if let (Some(a), Some(b)) = (first, nums(&n["at"])) {
placement(p, &a, &b, &mut out);
}
surface(p, &p["material"], &n["material"], &mut out);
surface(p, &p["light"], &n["light"], &mut out);
}
let cam = sent["camera"].as_array().into_iter().flatten().find(|c| c.is_object());
if let (Some(c), Some(n)) = (cam, now["camera"].as_object()) {
let me = json!({ "id": "camera", "source": { "name": "camera" } });
if let (Some(a), Some(b)) = (nums(&c["at"]), n.get("at").and_then(nums)) {
placement(&me, &a, &b, &mut out);
}
if let (Some(a), Some(b)) = (c["fov"].as_f64(), n.get("fov").and_then(Value::as_f64))
&& (a - b).abs() > 0.05
{
edit(&mut out, &me, "lens", "fov", json!(r4(a)), json!(r4(b)), format!("fov {} -> {} (degrees, vertical)", r4(a), r4(b)));
}
}
for n in now["new"].as_array().into_iter().flatten() {
let file = n["file"].as_str().unwrap_or("");
let at = nums(&n["at"]).map(|v| format!(" at [{}, {}, {}]", r4(v[0]), r4(v[1]), r4(v[2]))).unwrap_or_default();
out.push(json!({ "id": Value::Null, "name": n["name"], "loc": Value::Null, "change": "added", "prop": "", "from": Value::Null, "to": n["at"],
"says": format!("added: <Model src={{staticFile(\"{}\")}} />{at}, written as {file} with its sidecar", file.trim_start_matches("media/")) }));
}
out
}
/// Where a part is written in the TSX: its stamp, else the line naming it (`name="crate"`), else for the camera and
/// a light that has no name the Nth line writing its element (the id's `#N`: `<DirectionalLight`), else None.
pub fn line_of(tsx: &Path, e: &Value) -> Option<String> {
if let Some(loc) = e["loc"].as_str() {
return Some(loc.to_string());
}
let text = std::fs::read_to_string(tsx).ok()?;
let file = tsx.file_name()?.to_string_lossy();
let at = |i: usize| format!("{file}:{}", i + 1);
if let Some(name) = e["name"].as_str().filter(|&n| n != "camera" || e["id"] != "camera") {
return text.lines().position(|l| l.contains(&format!("name=\"{name}\"")) || l.contains(&format!("name: \"{name}\""))).map(at);
}
let id = e["id"].as_str()?;
let (tag, n) = match id.split_once('|') {
None if id == "camera" => ("<Camera3d", 0),
Some((kind, rest)) => {
let tag = match kind {
"directional" => "<DirectionalLight",
"point" => "<PointLight",
"spot" => "<SpotLight",
"rect" => "<RectLight",
_ => return None,
};
(tag, rest.rsplit_once('#').and_then(|(_, n)| n.parse().ok()).unwrap_or(0))
}
None => return None,
};
text.lines().enumerate().filter(|(_, l)| l.contains(tag) && !l.contains(&format!("{tag}s"))).nth(n).map(|(i, _)| at(i))
}
/// The edits as lines, each with where it goes in the TSX.
pub fn said(edits: &[Value], tsx: &Path) -> String {
if edits.is_empty() {
return "nothing changed".into();
}
edits.iter().map(|e| {
// the part by its name in the TSX, else by its id
let who = match (e["name"].as_str(), e["id"].as_str()) {
(Some(n), _) => format!("\"{n}\""),
(None, id) => id.unwrap_or("").to_string(),
};
let at = line_of(tsx, e).map(|l| format!(" ({l})")).unwrap_or_default();
format!("{who}{at}: {}", e["says"].as_str().unwrap_or(""))
}).collect::<Vec<_>>().join("\n")
}
#[cfg(test)]
mod tests {
use super::*;
fn sent() -> Value {
json!({ "parts": [
{ "id": "mesh|a#0", "kind": "mesh", "source": { "name": "crate" }, "at": [[0, 0.5, 0, 0, 0, 0, 1, 1, 1, 1]], "material": { "color": "#ff0000", "roughness": 0.5, "metallic": 0 } },
{ "id": "point|#0", "kind": "light", "source": {}, "at": [[0, 3, 0, 0, 0, 0, 1, 1, 1, 1]], "light": { "color": "#ffffff", "intensity": 1 } }
], "camera": [{ "at": [0, 1, 5, 0, 0, 0, 1, 1, 1, 1], "fov": 40 }] })
}
#[test]
fn nothing_changed_says_so() {
let s = sent();
let now = json!({ "parts": [
{ "id": "mesh|a#0", "at": [0, 0.5, 0, 0, 0, 0, 1, 1, 1, 1], "material": { "color": "#FF0000", "roughness": 0.5, "metallic": 0 } },
{ "id": "point|#0", "at": [0, 3, 0, 0, 0, 0, 1, 1, 1, 1], "light": { "color": "#ffffff", "intensity": 1.0001 } }
], "camera": { "at": [0, 1, 5, 0, 0, 0, 1, 1, 1, 1], "fov": 40 } });
assert_eq!(compare(&s, &now), Vec::<Value>::new());
}
#[test]
fn each_change_is_one_edit() {
let h = std::f64::consts::FRAC_1_SQRT_2;
let now = json!({ "parts": [
{ "id": "mesh|a#0", "at": [1, 0.5, 0, 0, h, 0, h, 2, 2, 2], "material": { "color": "#00ff00", "roughness": 0.2, "metallic": 0 } }
], "camera": { "at": [0, 1, 5, 0, 0, 0, 1, 1, 1, 1], "fov": 30 }, "new": [{ "name": "Cube", "file": "media/cube.glb", "at": [2, 0, 0, 0, 0, 0, 1, 1, 1, 1] }] });
let e = compare(&sent(), &now);
let changes: Vec<&str> = e.iter().map(|x| x["change"].as_str().unwrap()).collect();
assert_eq!(changes, ["moved", "turned", "scaled", "recoloured", "resurfaced", "deleted", "lens", "added"]);
assert_eq!(e[1]["to"], json!([0.0, 1.5708, 0.0]));
assert!(e[7]["says"].as_str().unwrap().contains("staticFile(\"cube.glb\")"));
}
#[test]
fn a_part_is_found_by_its_name() {
let f = std::env::temp_dir().join(format!("raea-back-{}.tsx", std::process::id()));
std::fs::write(&f, "a\n <Cuboid name=\"crate\" size={[1, 1, 1]} />\n <Camera3d transform={t} />\n <PointLight intensity={1} />\n <PointLight intensity={2} />\n").unwrap();
let file = f.file_name().unwrap().to_string_lossy().to_string();
assert_eq!(line_of(&f, &json!({ "name": "crate" })).unwrap(), format!("{file}:2"));
assert_eq!(line_of(&f, &json!({ "id": "camera", "name": "camera" })).unwrap(), format!("{file}:3"));
assert_eq!(line_of(&f, &json!({ "id": "point|#1", "name": null })).unwrap(), format!("{file}:5"));
assert_eq!(line_of(&f, &json!({ "id": "spot|#0", "name": null })), None);
assert_eq!(line_of(&f, &json!({ "name": "lamp", "loc": "edit.tsx:9:3" })).unwrap(), "edit.tsx:9:3");
let _ = std::fs::remove_file(&f);
}
}
+315
View File
@@ -0,0 +1,315 @@
//! `raea scene export EDIT.tsx -o DIR [--composition ID] [--frame N | --at A-B]` (docs/blender.feature BL37): the
//! composition's 3D at a frame, or on every frame of a span, as DIR/scene.json, with each mesh that isn't a primitive in
//! DIR/meshes/ and each model's file in DIR/models/. Every part is placed in the world (y up, metres; a quaternion
//! x y z w), so Blender (sdk/blender/src/scene.ts) and Godot (godot.rs) each build it with their own parts.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use raea_core_scene::{Item, hex, light_power, n, num, tracks_of, vec3};
use serde_json::{Value, json};
use crate::R;
pub const USAGE: &str = "raea scene export EDIT.tsx -o DIR [--composition ID] [--frame N | --at A-B]";
/// The frames asked for: --frame N, every frame of --at A-B, else 0.
fn frames_of(args: &[String]) -> R<Vec<i64>> {
let fl = |k: &str| args.iter().position(|a| a == k).and_then(|i| args.get(i + 1));
if let Some(span) = fl("--at") {
let (a, b) = span.split_once('-').ok_or("--at takes A-B, the first and last frame")?;
let (a, b): (i64, i64) = (a.trim().parse().map_err(|_| "--at A-B: A is a frame")?, b.trim().parse().map_err(|_| "--at A-B: B is a frame")?);
if b < a || b - a > 10_000 {
return Err("--at A-B: B at or after A, at most 10 000 frames".into());
}
return Ok((a..=b).collect());
}
Ok(vec![fl("--frame").map(|f| f.parse().map_err(|_| "--frame takes a frame number")).transpose()?.unwrap_or(0)])
}
fn r6(x: f32) -> f64 {
(x as f64 * 1e6).round() / 1e6
}
/// A rotation turning -Z (the way a camera and a light face, in glTF, Blender and Godot alike) to `dir`, +Y towards
/// `up`: x y z w.
pub fn look_quat(dir: [f64; 3], up: [f64; 3]) -> [f64; 4] {
let norm = |v: [f64; 3]| {
let l = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
if l < 1e-12 { None } else { Some([v[0] / l, v[1] / l, v[2] / l]) }
};
let cross = |a: [f64; 3], b: [f64; 3]| [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
let Some(f) = norm(dir) else { return [0.0, 0.0, 0.0, 1.0] };
let z = [-f[0], -f[1], -f[2]];
let x = norm(cross(up, z)).or_else(|| norm(cross([0.0, 0.0, 1.0], z))).unwrap_or([1.0, 0.0, 0.0]);
let y = cross(z, x);
// the rotation matrix's columns x, y, z as a quaternion
let (m00, m11, m22) = (x[0], y[1], z[2]);
let t = m00 + m11 + m22;
let q = if t > 0.0 {
let s = (t + 1.0).sqrt() * 2.0;
[(y[2] - z[1]) / s, (z[0] - x[2]) / s, (x[1] - y[0]) / s, 0.25 * s]
} else if m00 > m11 && m00 > m22 {
let s = (1.0 + m00 - m11 - m22).sqrt() * 2.0;
[0.25 * s, (y[0] + x[1]) / s, (z[0] + x[2]) / s, (y[2] - z[1]) / s]
} else if m11 > m22 {
let s = (1.0 + m11 - m00 - m22).sqrt() * 2.0;
[(y[0] + x[1]) / s, 0.25 * s, (z[1] + y[2]) / s, (z[0] - x[2]) / s]
} else {
let s = (1.0 + m22 - m00 - m11).sqrt() * 2.0;
[(z[0] + x[2]) / s, (z[1] + y[2]) / s, 0.25 * s, (x[1] - y[0]) / s]
};
q.map(|v| (v * 1e6).round() / 1e6)
}
/// A mesh or model's placement: position, rotation (x y z w), scale.
fn placed(it: &Item) -> Value {
let (s, q, t) = it.world.to_scale_rotation_translation();
let q = if q.is_finite() { [q.x, q.y, q.z, q.w] } else { [0.0, 0.0, 0.0, 1.0] };
json!([r6(t.x), r6(t.y), r6(t.z), r6(q[0]), r6(q[1]), r6(q[2]), r6(q[3]), r6(s.x), r6(s.y), r6(s.z)])
}
/// A light's placement: where it is, turned to face its target (a sun's from its position to its target too).
fn light_placed(it: &Item) -> Value {
let p = vec3(&it.props, "position", if it.kind == "directional" { [0.0, 1.0, 0.0] } else { [0.0; 3] });
let w = it.world.transform_point3([p[0] as f32, p[1] as f32, p[2] as f32].into());
let t = vec3(&it.props, "target", [0.0; 3]);
let w = [w.x as f64, w.y as f64, w.z as f64];
let q = look_quat([t[0] - w[0], t[1] - w[1], t[2] - w[2]], [0.0, 1.0, 0.0]);
let r = |x: f64| (x * 1e6).round() / 1e6;
json!([r(w[0]), r(w[1]), r(w[2]), q[0], q[1], q[2], q[3], 1, 1, 1])
}
/// What a mesh is made of, as the parts another tool has: a primitive with its sizes, else its Manifold mesh as a .glb.
fn shape(expr: &str, out: &Path, meshes: &mut BTreeMap<String, String>) -> R<Value> {
if let Some(s) = raea_core_shape::cuboid_of(expr) {
return Ok(json!({ "type": "cuboid", "size": s }));
}
if let Some(raea_core_shape::SphereOf::Ico { radius, .. } | raea_core_shape::SphereOf::Uv { radius, .. }) = raea_core_shape::sphere_of(expr) {
return Ok(json!({ "type": "sphere", "radius": radius }));
}
if let Some((radius, height)) = raea_core_shape::cylinder_of(expr) {
return Ok(json!({ "type": "cylinder", "radius": radius, "height": height }));
}
if let Some((_, size)) = raea_core_shape::plane_of(expr).filter(|(n, _)| *n == [0.0, 1.0, 0.0]) {
return Ok(json!({ "type": "plane", "size": size }));
}
let k = meshes.len();
let file = match meshes.get(expr) {
Some(f) => f.clone(),
None => {
let f = format!("meshes/mesh{k}.glb");
let m = raea_core_shape::solid(expr)?;
raea_core_shape::export(&m, &out.join(&f).to_string_lossy(), "glb")?;
// and as an .obj, which Godot imports as a mesh of its own (a .glb comes in as a scene)
raea_core_shape::export(&m, &out.join(f.replace(".glb", ".obj")).to_string_lossy(), "obj")?;
meshes.insert(expr.to_string(), f.clone());
f
}
};
Ok(json!({ "type": "mesh", "file": file, "obj": file.replace(".glb", ".obj") }))
}
/// A file the scene names (a model, a texture) copied into `sub` of the export with its licence sidecar: its path there.
fn copied(dir: &Path, src: &str, out: &Path, sub: &str, files: &mut BTreeMap<PathBuf, String>) -> R<String> {
let from = raea_core_scene::media_path(dir, if src.starts_with('/') || src.contains("://") { src.to_string() } else { format!("/media/{src}") }.as_str());
let from = if from.exists() { from } else { raea_core_scene::media_path(dir, src) };
if let Some(f) = files.get(&from) {
return Ok(f.clone());
}
let name = from.file_name().and_then(|n| n.to_str()).ok_or_else(|| format!("{src}: no file"))?;
let mut rel = format!("{sub}/{name}");
if files.values().any(|v| *v == rel) {
rel = format!("{sub}/{}-{name}", files.len());
}
std::fs::create_dir_all(out.join(sub)).map_err(|e| e.to_string())?;
std::fs::copy(&from, out.join(&rel)).map_err(|e| format!("{}: {e}", from.display()))?;
for side in [format!("{}.json", from.display()), format!("{}.json", from.with_extension("").display())] {
if Path::new(&side).is_file() {
let _ = std::fs::copy(&side, out.join(format!("{rel}.json")));
break;
}
}
files.insert(from, rel.clone());
Ok(rel)
}
/// A part's surface: three.js-style props as the renderer reads them (runtime/scene's meshes_rows).
fn material(it: &Item, dir: &Path, out: &Path, files: &mut BTreeMap<PathBuf, String>) -> Value {
let Some(m) = &it.material else { return json!({ "color": "#cccccc", "roughness": 0.5, "metallic": 0.0 }) };
let p = &m.props;
let mut v = json!({ "color": hex(p.get("color")).unwrap_or("#cccccc".into()), "roughness": n(p, "roughness", 0.5), "metallic": n(p, "metalness", 0.0) });
if let Some(e) = hex(p.get("emissive")).filter(|e| e != "#000000") {
v["emissive"] = json!(e);
v["emissive_strength"] = json!(raea_core_scene::emissive_power(p));
}
if let Some(o) = num(p, "opacity").filter(|o| *o < 1.0) {
v["opacity"] = json!(o);
}
if &*m.kind == "MeshBasicMaterial" || p.get("unlit") == Some(&Value::Bool(true)) {
v["unlit"] = json!(true);
}
for (prop, key) in [("map", "color_map"), ("normalMap", "normal_map"), ("roughnessMap", "roughness_map"), ("metalnessMap", "metallic_map"), ("emissiveMap", "emissive_map")] {
if let Some(src) = p.get(prop).and_then(Value::as_str)
&& let Ok(f) = copied(dir, src, out, "textures", files)
{
v[key] = json!(f);
}
}
v
}
/// The light another tool sets: its kind, colour, intensity as raea reads it (1 is a 3d.tsx light's default) and in
/// Bevy's units (lux for a sun, lumens else), reach and cone.
fn light(it: &Item) -> Value {
let p = &it.props;
let power = light_power(it.kind, p);
let unit = if it.kind == "directional" { raea_core_scene::LUX } else { raea_core_scene::LUMENS };
let mut v = json!({ "type": it.kind, "color": hex(p.get("color")).unwrap_or("#ffffff".into()), "intensity": power / unit });
v[if it.kind == "directional" { "lux" } else { "lumens" }] = json!(power);
if let Some(d) = num(p, "distance").filter(|d| *d > 0.0) {
v["range"] = json!(d);
}
if it.kind == "spot" {
v["angle"] = json!(n(p, "angle", std::f64::consts::FRAC_PI_3));
v["penumbra"] = json!(n(p, "penumbra", 0.0));
}
if it.kind == "rect" {
v["width"] = json!(n(p, "width", 1.0));
v["height"] = json!(n(p, "height", 1.0));
}
v
}
/// Where the part is written in the TSX, when the bundle stamped it, and its name.
fn source(it: &Item) -> Value {
let s = |k: &str| it.props.get(k).and_then(Value::as_str).map(str::to_string);
json!({ "name": s("name"), "loc": s("data-raea-loc"), "use": s("data-raea-use") })
}
/// The parts of every frame asked for (`all`, one list of items each), written into `out`: scene.json's value.
pub fn scene(all: &[Vec<Item>], frames: &[i64], dir: &Path, out: &Path) -> R<Value> {
let (mut meshes, mut files) = (BTreeMap::new(), BTreeMap::new());
let mut parts = Vec::new();
for (id, track) in tracks_of(all, &["mesh", "model", "directional", "point", "spot", "rect"]) {
let Some(first) = track.iter().flatten().next() else { continue };
let mut part = json!({ "id": id, "kind": if first.kind == "mesh" || first.kind == "model" { first.kind } else { "light" }, "source": source(first) });
match first.kind {
// an <Instances> set is many copies of one mesh: left out (counted in `left`)
"mesh" if first.at.is_some() => continue,
"mesh" => {
let Some(expr) = first.shape.as_deref() else { continue };
part["shape"] = shape(expr, out, &mut meshes)?;
part["material"] = material(first, dir, out, &mut files);
}
"model" => {
let src = first.props.get("src").and_then(Value::as_str).unwrap_or_default();
part["model"] = json!(copied(dir, src, out, "models", &mut files)?);
}
_ => part["light"] = light(first),
}
let at: Vec<Value> = track.iter().map(|t| t.as_ref().map_or(Value::Null, |it| if part["kind"] == "light" { light_placed(it) } else { placed(it) })).collect();
part["at"] = json!(at);
parts.push(part);
}
// the camera: the first drawing one each frame, from its position to what it looks at
let cam: Vec<Value> = all.iter().map(|its| {
its.iter().find(|i| i.kind == "camera").map_or(Value::Null, |c| {
let (p, l, up) = (vec3(&c.props, "position", [0.0, 0.0, 5.0]), vec3(&c.props, "lookAt", [0.0; 3]), vec3(&c.props, "up", [0.0, 1.0, 0.0]));
let q = look_quat([l[0] - p[0], l[1] - p[1], l[2] - p[2]], up);
json!({ "at": [p[0], p[1], p[2], q[0], q[1], q[2], q[3], 1, 1, 1], "look": l, "fov": n(&c.props, "fov", 50.0) })
})
}).collect();
let ambient = all[0].iter().find(|i| i.kind == "ambient").map(|a| json!({ "color": hex(a.props.get("color")).unwrap_or("#ffffff".into()), "nits": light_power("ambient", &a.props) }));
// what doesn't cross, by kind, counted on the first frame
let mut left: BTreeMap<&str, usize> = BTreeMap::new();
for i in &all[0] {
match i.kind {
// a mesh drawn at many places (<Instances>) crosses as its first copy only
"mesh" if i.at.is_some() => *left.entry("instances").or_default() += 1,
"mesh" | "model" | "directional" | "point" | "spot" | "rect" | "camera" | "ambient" => {}
k => *left.entry(k).or_default() += 1,
}
}
Ok(json!({ "raea": "scene/1", "frames": frames, "parts": parts, "camera": cam, "ambient": ambient, "left": left }))
}
/// `raea scene export ...`: scene.json written, and its value.
pub fn export(args: &[String]) -> R<(PathBuf, Value)> {
let edit = args.get(2).ok_or(USAGE)?;
let tsx = PathBuf::from(edit).canonicalize().map_err(|e| format!("{edit}: {e}"))?;
let dir = tsx.parent().ok_or("the edit's folder")?.to_path_buf();
let out = args.iter().position(|a| a == "-o").and_then(|i| args.get(i + 1)).ok_or(USAGE)?;
let out = std::path::absolute(out).map_err(|e| e.to_string())?;
let frames = frames_of(args)?;
let js = std::env::temp_dir().join(format!("raea-scene-export-{}.js", std::process::id()));
// each part's place in the TSX (data-raea-loc), which raea blender back and raea godot back say their edits at
// SAFETY: the CLI sets it before the bundle starts any thread that reads the environment
unsafe { std::env::set_var("RAEA_SOURCE_STAMPS", "1") };
raea_runtime_bundle::bundle_composition(&tsx, &js, &raea_runtime_bundle::comp_opts(args)?, None)?;
let got = raea_runtime_export::scene_frames(&js, &dir, frames[frames.len() - 1] + 1, false, &frames);
let _ = std::fs::remove_file(&js);
let (got, w, h, fps) = got?.ok_or("the composition has no 3D")?;
let all: Vec<Vec<Item>> = frames.iter().map(|f| got.iter().find(|(k, _)| k == f).map(|(_, fr)| raea_runtime_scene::items_of(&fr.scene)).unwrap_or_default()).collect();
if all.iter().all(Vec::is_empty) {
return Err(format!("{edit}: no 3D on frame {}", frames[0]));
}
let _ = std::fs::remove_dir_all(out.join("meshes"));
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
let mut v = scene(&all, &frames, &dir, &out)?;
v["from"] = json!(tsx.to_string_lossy());
v["fps"] = json!(fps);
v["size"] = json!([w, h]);
std::fs::write(out.join("scene.json"), serde_json::to_string_pretty(&v).unwrap_or_default()).map_err(|e| e.to_string())?;
Ok((out, v))
}
/// The summary line of an export.
pub fn said(out: &Path, v: &Value) -> String {
let parts = v["parts"].as_array().map_or(0, Vec::len);
let frames = v["frames"].as_array().map_or(0, Vec::len);
let left: Vec<String> = v["left"].as_object().into_iter().flatten().map(|(k, n)| format!("{n} {k}")).collect();
let left = if left.is_empty() { String::new() } else { format!("; not carried: {}", left.join(", ")) };
format!("{parts} parts on {frames} frame{} in {}{left}", if frames == 1 { "" } else { "s" }, out.join("scene.json").display())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_rotation_faces_where_it_is_turned() {
// looking down -Z is no turn; looking down +X turns -90 degrees about Y
assert_eq!(look_quat([0.0, 0.0, -1.0], [0.0, 1.0, 0.0]), [0.0, 0.0, 0.0, 1.0]);
let q = look_quat([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]);
assert!((q[1] + std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-6 && (q[3] - std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-6, "{q:?}");
// straight down still has a way up
let q = look_quat([0.0, -1.0, 0.0], [0.0, 1.0, 0.0]);
assert!(q.iter().all(|v| v.is_finite()) && (q.iter().map(|v| v * v).sum::<f64>() - 1.0).abs() < 1e-5);
}
#[test]
fn frames_are_one_or_a_span() {
let a = |s: &str| s.split_whitespace().map(String::from).collect::<Vec<_>>();
assert_eq!(frames_of(&a("scene export e.tsx")).unwrap(), vec![0]);
assert_eq!(frames_of(&a("scene export e.tsx --frame 12")).unwrap(), vec![12]);
assert_eq!(frames_of(&a("scene export e.tsx --at 3-5")).unwrap(), vec![3, 4, 5]);
assert!(frames_of(&a("scene export e.tsx --at 5-3")).is_err());
}
#[test]
fn primitives_cross_as_themselves_and_the_rest_as_a_mesh() {
let out = std::env::temp_dir().join(format!("raea-interchange-shape-{}", std::process::id()));
std::fs::create_dir_all(out.join("meshes")).unwrap();
let mut m = BTreeMap::new();
assert_eq!(shape("box(1, 2, 3)", &out, &mut m).unwrap(), json!({ "type": "cuboid", "size": [1.0, 2.0, 3.0] }));
assert_eq!(shape("sphere(0.5)", &out, &mut m).unwrap()["type"], "sphere");
assert_eq!(shape("rotate(cone(0.5, 0.5, 2), -90, 0, 0)", &out, &mut m).unwrap()["height"], 2.0);
let v = shape("difference(box(1, 1, 1), sphere(0.6))", &out, &mut m).unwrap();
assert_eq!(v["type"], "mesh");
assert!(out.join(v["file"].as_str().unwrap()).is_file());
// the same mesh twice is one file
assert_eq!(shape("difference(box(1, 1, 1), sphere(0.6))", &out, &mut m).unwrap(), v);
let _ = std::fs::remove_dir_all(&out);
}
}
+291
View File
@@ -0,0 +1,291 @@
//! A raea scene as a Godot project (docs/godot.feature GD12): scene export's folder made into project.godot and
//! main.tscn, each part Godot's own node (a primitive its own mesh with a StandardMaterial3D, any other mesh an imported
//! .obj, a model its .glb instanced, lights, the camera, a WorldEnvironment), named for the part and carrying its id;
//! a span's frames an AnimationPlayer that plays as the project runs.
use std::collections::BTreeSet;
use std::fmt::Write as _;
use std::path::Path;
use serde_json::Value;
use crate::R;
/// `#rrggbb` as Godot's Color (sRGB, as Godot's albedo and light colours are given).
fn color(hex: &str, a: f64) -> String {
let h = hex.trim_start_matches('#');
let c = |i: usize| u8::from_str_radix(h.get(i..i + 2).unwrap_or("cc"), 16).unwrap_or(204) as f64 / 255.0;
format!("Color({:.4}, {:.4}, {:.4}, {a})", c(0), c(2), c(4))
}
/// A placement (x y z, qx qy qz qw, sx sy sz) as Godot's Transform3D: the basis by rows, the rotation's columns scaled.
pub fn transform(at: &Value) -> String {
let v: Vec<f64> = at.as_array().into_iter().flatten().filter_map(Value::as_f64).collect();
if v.len() < 10 {
return "Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0)".into();
}
let (x, y, z, w) = (v[3], v[4], v[5], v[6]);
let r = [
[1.0 - 2.0 * (y * y + z * z), 2.0 * (x * y - z * w), 2.0 * (x * z + y * w)],
[2.0 * (x * y + z * w), 1.0 - 2.0 * (x * x + z * z), 2.0 * (y * z - x * w)],
[2.0 * (x * z - y * w), 2.0 * (y * z + x * w), 1.0 - 2.0 * (x * x + y * y)],
];
let s = [v[7], v[8], v[9]];
let b: Vec<String> = (0..3).flat_map(|i| (0..3).map(move |j| (i, j))).map(|(i, j)| num(r[i][j] * s[j])).collect();
format!("Transform3D({}, {}, {}, {})", b.join(", "), num(v[0]), num(v[1]), num(v[2]))
}
fn num(x: f64) -> String {
let r = (x * 1e6).round() / 1e6;
if r == 0.0 { "0".into() } else { format!("{r}") }
}
/// A node name Godot takes (no . : @ / " %), unique in the scene.
fn node_name(want: &str, taken: &mut BTreeSet<String>) -> String {
let base: String = want.chars().map(|c| if ".:@/\"%#|".contains(c) || c.is_control() { '_' } else { c }).collect();
let base = if base.trim().is_empty() { "Part".to_string() } else { base.trim().to_string() };
let mut name = base.clone();
let mut k = 2;
while !taken.insert(name.clone()) {
name = format!("{base}{k}");
k += 1;
}
name
}
/// A part's node name: its name in the TSX, else what it is ("Sun", "PointLight", "Cuboid", the model's file).
pub fn wanted(p: &Value) -> String {
if let Some(n) = p["source"]["name"].as_str() {
return n.to_string();
}
let what = match (p["kind"].as_str(), p["light"]["type"].as_str(), p["shape"]["type"].as_str()) {
(_, Some("directional"), _) => "Sun",
(_, Some("point"), _) => "PointLight",
(_, Some("spot"), _) => "SpotLight",
(_, Some("rect"), _) => "AreaLight",
(Some("model"), _, _) => return p["model"].as_str().and_then(|m| Path::new(m).file_stem()?.to_str()).unwrap_or("Model").to_string(),
(_, _, Some("cuboid")) => "Cuboid",
(_, _, Some("sphere")) => "Sphere",
(_, _, Some("cylinder")) => "Cylinder",
(_, _, Some("plane")) => "Plane",
_ => "Mesh",
};
what.to_string()
}
/// The tscn's resources and nodes, written in order: ext_resources, sub_resources, then nodes.
#[derive(Default)]
struct Tscn {
ext: String,
sub: String,
nodes: String,
n_ext: usize,
n_sub: usize,
}
impl Tscn {
fn ext(&mut self, kind: &str, path: &str) -> String {
self.n_ext += 1;
let _ = writeln!(self.ext, "[ext_resource type=\"{kind}\" path=\"res://{path}\" id=\"{}\"]", self.n_ext);
format!("ExtResource(\"{}\")", self.n_ext)
}
fn sub(&mut self, kind: &str, body: &str) -> String {
self.n_sub += 1;
let _ = write!(self.sub, "\n[sub_resource type=\"{kind}\" id=\"{kind}_{}\"]\n{body}", self.n_sub);
format!("SubResource(\"{kind}_{}\")", self.n_sub)
}
}
fn material(m: &Value) -> String {
// each number the material gives, else raea's default for it
let f = |k: &str| m[k].as_f64().unwrap_or(match k { "opacity" | "emissive_strength" => 1.0, "roughness" => 0.5, _ => 0.0 });
let mut s = format!("albedo_color = {}\nmetallic = {}\nroughness = {}\n", color(m["color"].as_str().unwrap_or("#cccccc"), f("opacity")), num(f("metallic")), num(f("roughness")));
if let Some(e) = m["emissive"].as_str() {
let _ = write!(s, "emission_enabled = true\nemission = {}\nemission_energy_multiplier = {}\n", color(e, 1.0), num(f("emissive_strength")));
}
if m["opacity"].as_f64().is_some_and(|o| o < 1.0) {
s.push_str("transparency = 1\n");
}
if m["unlit"] == true {
s.push_str("shading_mode = 0\n");
}
// its textures need their files' ext_resources: part() adds them
s
}
/// One part's node (and its resources); the first frame it's in places it.
fn part(t: &mut Tscn, p: &Value, name: &str) {
let first = p["at"].as_array().into_iter().flatten().find(|a| !a.is_null()).cloned().unwrap_or(Value::Null);
let meta = format!("metadata/raea_id = \"{}\"\n", p["id"].as_str().unwrap_or("").replace('"', "'"));
let tr = transform(&first);
match p["kind"].as_str() {
Some("mesh") => {
let sh = &p["shape"];
let mesh = match sh["type"].as_str() {
Some("cuboid") => {
let s = &sh["size"];
t.sub("BoxMesh", &format!("size = Vector3({}, {}, {})\n", num(s[0].as_f64().unwrap_or(1.0)), num(s[1].as_f64().unwrap_or(1.0)), num(s[2].as_f64().unwrap_or(1.0))))
}
Some("sphere") => {
let r = sh["radius"].as_f64().unwrap_or(0.5);
t.sub("SphereMesh", &format!("radius = {}\nheight = {}\n", num(r), num(2.0 * r)))
}
Some("cylinder") => {
let r = num(sh["radius"].as_f64().unwrap_or(0.5));
t.sub("CylinderMesh", &format!("top_radius = {r}\nbottom_radius = {r}\nheight = {}\n", num(sh["height"].as_f64().unwrap_or(1.0))))
}
Some("plane") => {
let s = &sh["size"];
t.sub("PlaneMesh", &format!("size = Vector2({}, {})\n", num(s[0].as_f64().unwrap_or(1.0)), num(s[1].as_f64().unwrap_or(1.0))))
}
_ => t.ext("ArrayMesh", sh["obj"].as_str().unwrap_or("")),
};
let mut mat = material(&p["material"]);
if let Some(f) = p["material"]["color_map"].as_str() {
let tex = t.ext("Texture2D", f);
let _ = writeln!(mat, "albedo_texture = {tex}");
}
if let Some(f) = p["material"]["normal_map"].as_str() {
let tex = t.ext("Texture2D", f);
let _ = writeln!(mat, "normal_enabled = true\nnormal_texture = {tex}");
}
let mat = t.sub("StandardMaterial3D", &mat);
let _ = write!(t.nodes, "\n[node name=\"{name}\" type=\"MeshInstance3D\" parent=\".\"]\ntransform = {tr}\nmesh = {mesh}\nsurface_material_override/0 = {mat}\n{meta}");
}
Some("model") => {
let scene = t.ext("PackedScene", p["model"].as_str().unwrap_or(""));
let _ = write!(t.nodes, "\n[node name=\"{name}\" parent=\".\" instance={scene}]\ntransform = {tr}\n{meta}");
}
_ => {
let l = &p["light"];
let kind = match l["type"].as_str() {
Some("directional") => "DirectionalLight3D",
Some("spot") => "SpotLight3D",
_ => "OmniLight3D",
};
let mut body = format!("transform = {tr}\nlight_color = {}\nlight_energy = {}\nshadow_enabled = true\n", color(l["color"].as_str().unwrap_or("#ffffff"), 1.0), num(l["intensity"].as_f64().unwrap_or(1.0)));
let range = num(l["range"].as_f64().unwrap_or(20.0));
match kind {
"SpotLight3D" => {
let _ = write!(body, "spot_range = {range}\nspot_angle = {}\n", num(l["angle"].as_f64().unwrap_or(std::f64::consts::FRAC_PI_3).to_degrees().min(89.0)));
}
"OmniLight3D" => {
let _ = writeln!(body, "omni_range = {range}");
}
_ => {}
}
let _ = write!(t.nodes, "\n[node name=\"{name}\" type=\"{kind}\" parent=\".\"]\n{body}{meta}");
}
}
}
/// A placement track of the animation: each frame the node is in, as (time, transition, values...).
fn tracks(anim: &mut String, k: &mut usize, path: &str, at: &[Value], fps: f64, f0: i64, frames: &[i64]) {
let keyed: Vec<(f64, Vec<f64>)> = at.iter().zip(frames).filter_map(|(a, f)| {
let v: Vec<f64> = a.as_array()?.iter().filter_map(Value::as_f64).collect();
(v.len() >= 10).then(|| ((f - f0) as f64 / fps, v))
}).collect();
for (kind, range) in [("position_3d", 0..3), ("rotation_3d", 3..7), ("scale_3d", 7..10)] {
// a channel that holds still isn't a track: a part that only turns keys its rotation alone
if keyed.windows(2).all(|w| w[0].1[range.clone()] == w[1].1[range.clone()]) {
continue;
}
let keys: Vec<String> = keyed.iter().flat_map(|(t, v)| [num(*t), "1".into()].into_iter().chain(v[range.clone()].iter().map(|x| num(*x)))).collect();
let _ = write!(anim, "tracks/{k}/type = \"{kind}\"\ntracks/{k}/imported = false\ntracks/{k}/enabled = true\ntracks/{k}/path = NodePath(\"{path}\")\ntracks/{k}/interp = 1\ntracks/{k}/loop_wrap = true\ntracks/{k}/keys = PackedFloat32Array({})\n", keys.join(", "));
*k += 1;
}
}
/// project.godot and main.tscn in `dir` (scene export's folder), from its scene.json `v`: the name of the project.
pub fn project(dir: &Path, v: &Value, name: &str) -> R<String> {
let fps = v["fps"].as_f64().unwrap_or(30.0);
let frames: Vec<i64> = v["frames"].as_array().into_iter().flatten().filter_map(Value::as_i64).collect();
let f0 = frames.first().copied().unwrap_or(0);
let (w, h) = (v["size"][0].as_u64().unwrap_or(1920), v["size"][1].as_u64().unwrap_or(1080));
let mut t = Tscn::default();
let mut taken = BTreeSet::from(["WorldEnvironment".to_string(), "Camera3D".to_string(), "AnimationPlayer".to_string()]);
let mut anim = String::new();
let mut k = 0;
for p in v["parts"].as_array().into_iter().flatten() {
let name = node_name(&wanted(p), &mut taken);
part(&mut t, p, &name);
if frames.len() > 1 {
tracks(&mut anim, &mut k, &name, p["at"].as_array().map(Vec::as_slice).unwrap_or(&[]), fps, f0, &frames);
}
}
// the ambient and a background: Bevy's own clear colour unless the scene says otherwise
let amb = &v["ambient"];
let mut env = "background_mode = 1\nbackground_color = Color(0.1686, 0.1725, 0.1843, 1)\ntonemap_mode = 3\n".to_string();
if amb.is_object() {
let _ = write!(env, "ambient_light_source = 2\nambient_light_color = {}\nambient_light_energy = {}\n", color(amb["color"].as_str().unwrap_or("#ffffff"), 1.0), num(amb["nits"].as_f64().unwrap_or(400.0) / 400.0));
}
let env = t.sub("Environment", &env);
let mut nodes = format!("\n[node name=\"WorldEnvironment\" type=\"WorldEnvironment\" parent=\".\"]\nenvironment = {env}\n");
nodes.push_str(&t.nodes);
let cams: Vec<Value> = v["camera"].as_array().into_iter().flatten().cloned().collect();
if let Some(c) = cams.iter().find(|c| c.is_object()) {
let _ = write!(nodes, "\n[node name=\"Camera3D\" type=\"Camera3D\" parent=\".\"]\ntransform = {}\nfov = {}\ncurrent = true\n", transform(&c["at"]), num(c["fov"].as_f64().unwrap_or(50.0)));
if frames.len() > 1 {
let at: Vec<Value> = cams.iter().map(|c| c["at"].clone()).collect();
tracks(&mut anim, &mut k, "Camera3D", &at, fps, f0, &frames);
}
}
if k > 0 {
let len = (frames.len().saturating_sub(1)) as f64 / fps;
let a = t.sub("Animation", &format!("resource_name = \"raea\"\nlength = {}\n{anim}", num(len.max(1.0 / fps))));
let lib = t.sub("AnimationLibrary", &format!("_data = {{\n&\"raea\": {a}\n}}\n"));
let _ = write!(nodes, "\n[node name=\"AnimationPlayer\" type=\"AnimationPlayer\" parent=\".\"]\nlibraries = {{\n&\"\": {lib}\n}}\nautoplay = &\"raea\"\n");
}
let tscn = format!("[gd_scene load_steps={} format=3]\n\n{}{}\n[node name=\"{}\" type=\"Node3D\"]\n{nodes}", t.n_ext + t.n_sub + 1, t.ext, t.sub, node_name(name, &mut BTreeSet::new()));
std::fs::write(dir.join("main.tscn"), tscn).map_err(|e| e.to_string())?;
let godot = format!(
"; written by raea godot export (docs/godot.feature GD12)\nconfig_version=5\n\n[application]\nconfig/name=\"{}\"\nrun/main_scene=\"res://main.tscn\"\nconfig/features=PackedStringArray(\"4.6\", \"Forward Plus\")\n\n[display]\nwindow/size/viewport_width={w}\nwindow/size/viewport_height={h}\n\n[rendering]\nrenderer/rendering_method=\"forward_plus\"\n",
name.replace('"', "'")
);
std::fs::write(dir.join("project.godot"), godot).map_err(|e| e.to_string())?;
Ok(format!("{} parts{}", v["parts"].as_array().map_or(0, Vec::len), if k > 0 { format!(", {k} animation track{} over {} frames", if k == 1 { "" } else { "s" }, frames.len()) } else { String::new() }))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn a_placement_is_a_transform_by_rows() {
assert_eq!(transform(&json!([1, 2, 3, 0, 0, 0, 1, 1, 1, 1])), "Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 2, 3)");
// a quarter turn about Y, then scaled by 2 along x: the x column is twice as long
let h = std::f64::consts::FRAC_1_SQRT_2;
assert_eq!(transform(&json!([0, 0, 0, 0, h, 0, h, 2, 1, 1])), "Transform3D(0, 0, 1, 0, 1, 0, -2, 0, 0, 0, 0, 0)");
}
#[test]
fn names_are_godots_and_unique() {
let mut t = BTreeSet::new();
assert_eq!(node_name("crate", &mut t), "crate");
assert_eq!(node_name("crate", &mut t), "crate2");
assert_eq!(node_name("mesh|a.b#0", &mut t), "mesh_a_b_0");
}
#[test]
fn a_scene_becomes_a_project_that_moves() {
let dir = std::env::temp_dir().join(format!("raea-godot-project-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let v = json!({ "fps": 30, "size": [640, 360], "frames": [0, 1],
"parts": [
{ "id": "mesh|box(1, 1, 1)#0", "kind": "mesh", "source": { "name": "crate" }, "shape": { "type": "cuboid", "size": [1, 1, 1] }, "material": { "color": "#ff0000", "roughness": 0.4, "metallic": 0 }, "at": [[0, 0.5, 0, 0, 0, 0, 1, 1, 1, 1], [1, 0.5, 0, 0, 0, 0, 1, 1, 1, 1]] },
{ "id": "directional|#0", "kind": "light", "source": {}, "light": { "type": "directional", "color": "#ffffff", "intensity": 1 }, "at": [[0, 5, 0, 0, 0, 0, 1, 1, 1, 1], [0, 5, 0, 0, 0, 0, 1, 1, 1, 1]] }
],
"camera": [{ "at": [0, 1, 5, 0, 0, 0, 1, 1, 1, 1], "fov": 40 }, { "at": [0, 1, 5, 0, 0, 0, 1, 1, 1, 1], "fov": 40 }], "ambient": null });
let said = project(&dir, &v, "box test").unwrap();
// the crate only moves: its position is keyed, its rotation and scale aren't tracks
assert!(said.contains("1 animation track over 2 frames"), "{said}");
let tscn = std::fs::read_to_string(dir.join("main.tscn")).unwrap();
assert!(!tscn.contains("tracks/1/"), "{tscn}");
for want in ["[node name=\"crate\" type=\"MeshInstance3D\"", "size = Vector3(1, 1, 1)", "albedo_color = Color(1.0000, 0.0000, 0.0000, 1)", "[node name=\"Sun\" type=\"DirectionalLight3D\"", "fov = 40", "tracks/0/type = \"position_3d\"", "autoplay = &\"raea\"", "tracks/0/path = NodePath(\"crate\")", "metadata/raea_id = \"mesh|box(1, 1, 1)#0\""] {
assert!(tscn.contains(want), "{want} in\n{tscn}");
}
assert!(std::fs::read_to_string(dir.join("project.godot")).unwrap().contains("window/size/viewport_width=640"));
let _ = std::fs::remove_dir_all(&dir);
}
}
+13
View File
@@ -0,0 +1,13 @@
//! A composition's 3D for other tools, and back (docs/blender.feature BL37-BL39, docs/godot.feature GD12-GD13):
//! `raea scene export` writes the parts of a frame (or a span) as scene.json with their meshes and models; godot.rs
//! makes that folder a Godot project; back.rs compares scene.json with what Blender or Godot holds after a person
//! changed it there, as edits to the TSX at their lines. apps/engines runs Blender and Godot for these verbs.
/// `raea scene export`: scene.json, meshes/, models/
pub mod export;
/// scene export's folder as a Godot project: project.godot, main.tscn
pub mod godot;
/// what changed in Blender or Godot, as edits to the TSX
pub mod back;
type R<T> = Result<T, String>;
+2
View File
@@ -8,6 +8,8 @@ description = "raea judge: a review's sheets judged by clef-omni on a frozen rub
[dependencies]
raea-io-home = { path = "../../io/home" }
# what a judge saw, as raea's one Finding (docs/direction.feature DR3)
raea-core-facts = { path = "../../core/facts" }
serde_json = "1"
raea-runtime-bundle = { path = "../../runtime/bundle" }
ureq = { version = "2", features = ["json"] }
+32 -7
View File
@@ -18,6 +18,7 @@ pub use agent::BY;
use std::path::{Path, PathBuf};
use raea_core_facts::{Finding, Level, finding};
use raea_runtime_bundle::flag;
use serde_json::{Value, json};
@@ -125,6 +126,31 @@ pub fn cli(args: &[String]) -> Result<String, String> {
finish(args, &dir, scores, raw, defects, photo, cost, "clef", !gating, json!({"calibrated": cal.is_some()}))
}
/// The defects a judge saw, as raea's one Finding (docs/direction.feature DR3): a blocking one an error and a detail a
/// warn, each a level lower from a judge that only advises. A judge sees pictures, not parts: a finding names its
/// sheet in its words and is about no entity.
pub fn findings(defects: &[Value], by: &str, advice: bool) -> Vec<Finding> {
let found = defects.iter().filter(|d| d["present"] == true).map(|d| {
let blocking = d["level"] == "blocking";
let level = match (blocking, advice) {
(true, false) => Level::Error,
(true, true) | (false, false) => Level::Warn,
(false, true) => Level::Note,
};
let sheet = d["sheet"].as_str().unwrap_or("");
let check = format!("judge.{}", if by == "clef" { d["defect"].as_str().unwrap_or("defect") } else { sheet });
let mut f = Finding::new(&check, level, format!("{sheet} sheet: {}", d["asked"].as_str().unwrap_or("")), &format!("raea judge ({by})"));
if let Some(p) = d["p"].as_f64() {
f = f.measure("p", p, "", Some(0.5));
}
match d["fix"].as_str() {
Some(x) if !x.is_empty() => f.fix(x),
_ => f,
}
});
finding::ranked(found.collect())
}
/// The verdict decided in code, written (DIR/judge.json for clef, DIR/judge.BY.json for an agent; every round in the
/// log), and said. `advice` marks a judge not yet trusted to gate (clef before calibration).
#[allow(clippy::too_many_arguments)]
@@ -133,8 +159,9 @@ fn finish(args: &[String], dir: &Path, scores: serde_json::Map<String, Value>, r
let vals: Vec<f64> = scores.values().filter_map(Value::as_f64).collect();
let mean = if vals.is_empty() { 0.0 } else { (vals.iter().sum::<f64>() / vals.len() as f64 * 100.0).round() / 100.0 };
let model = if by == "clef" { "@cf/cloudflare/clef-omni".to_string() } else { format!("{by} cli") };
let found = findings(&defects, by, advice);
let mut verdict = json!({"dir": dir.display().to_string(), "by": by, "scores": scores, "raw": raw, "mean": mean, "defects": defects, "photo": photo,
"pass": pass, "why": why, "gating": !advice, "cost": cost, "model": model});
"pass": pass, "why": why, "gating": !advice, "cost": cost, "model": model, "findings": found, "count": finding::count(&found)});
if let (Some(v), Some(e)) = (verdict.as_object_mut(), extra.as_object()) {
v.extend(e.clone());
}
@@ -155,15 +182,13 @@ fn finish(args: &[String], dir: &Path, scores: serde_json::Map<String, Value>, r
let who = if by == "clef" { String::new() } else { format!("({by}) ") };
let mut t = vec![format!("{} {who}{}{}", if pass { "PASS" } else { "NOT YET" }, if advice { "(advice: the judge isn't calibrated against your eye yet) " } else { "" }, why.join("; "))];
t.push(format!("scores: {}", scores.iter().map(|(k, v)| format!("{k} {v}")).collect::<Vec<_>>().join(", ")));
for d in verdict["defects"].as_array().into_iter().flatten().filter(|d| d["present"] == true) {
if by == "clef" {
t.push(format!(" {:<8} {} (p {}, {} sheet): {}", d["level"].as_str().unwrap_or(""), d["defect"].as_str().unwrap_or(""), d["p"], d["sheet"].as_str().unwrap_or(""), d["asked"].as_str().unwrap_or("")));
} else {
t.push(format!(" {:<8} {} tile: {} (fix: {})", d["level"].as_str().unwrap_or(""), d["sheet"].as_str().unwrap_or(""), d["asked"].as_str().unwrap_or(""), d["fix"].as_str().unwrap_or("")));
}
for f in &found {
let p = f.measure.as_ref().map(|m| format!(" (p {})", m.value)).unwrap_or_default();
t.push(format!(" {}{p}", f.line()));
}
let p = &verdict["progress"];
t.push(format!("round {}: {} passes in a row{}{}; ${cost:.4}", p["rounds"], p["passesInARow"], if p["done"] == true { ", done" } else { "" }, if p["stall"] == true { ", stalled: change the approach for the part, not the dose" } else { "" }));
t.push(format!("raea judge: {}", finding::count(&found)));
Ok(t.join("\n"))
}
+5
View File
@@ -69,4 +69,9 @@ fn an_agent_verdict_is_read_from_the_end_of_its_thinking() {
let (pass, why) = crate::rubric::pass(&scores, &defects);
assert!(!pass && why[0].starts_with("blocking"));
assert!(crate::agent::last_verdict("no json here").is_none());
// what it saw, as Findings (DR3): a gating judge's blocking defect is an error, an advising one's a warn
let f = &crate::findings(&defects, "kimi", false)[0];
assert_eq!((f.check.as_str(), f.level, f.fix.as_deref(), f.by.as_str()), ("judge.iso", raea_core_facts::Level::Error, Some("model legs"), "raea judge (kimi)"));
assert!(f.says.starts_with("iso sheet: "), "{}", f.says);
assert_eq!(crate::findings(&defects, "kimi", true)[0].level, raea_core_facts::Level::Warn);
}
+2
View File
@@ -15,3 +15,5 @@ raea-runtime-encode = { path = "../../runtime/encode" }
raea-io-media = { path = "../../io/media", default-features = false }
raea-page = { path = "../../engine/page" }
serde_json = "1"
# a model's lower levels of detail (lod.rs): the simplifier Bevy's meshlets use
meshopt = "0.6.2"
+1 -1
View File
@@ -1,7 +1,7 @@
//! The media verbs' command line (`raea media|ffmpeg|ffprobe`, and raea's shell, in process): the agent's media
//! work on raea-media (lib.rs and its files), and an HTML composition's render (html.rs).
//!
//! media probe|still|sheet|audio|loudness|motion|cuts|freezes|proxy|trim|concat FILE ... media work, native (media help)
//! media probe|still|sheet|audio|loudness|motion|cuts|freezes|proxy|lod|trim|concat FILE ... media work, native (media help)
//! ffmpeg ARGS | ffprobe ARGS ffmpeg and ffprobe command lines read as the media verbs (no ffmpeg involved)
//! render PAGE.html -o OUT.mp4|OUT.png|DIR [--at F,F] [--alpha] [--codec apple|soft|av1|ffmpeg] [--kbps K | --quality Q]
//! shots [--size WxH] [--root DIR] plain HTML pages' first frames as PNGs, over white: stdin lines `PAGE\tOUT.png`,
+1 -1
View File
@@ -170,7 +170,7 @@ pub(crate) fn ffmpeg(args: &[String]) -> R<()> {
if vf.is_some() {
return Err(format!("-vf on a still isn't read here: take the still (raea media still), then crop or scale it in an edit; {VERBS_HINT}"));
}
still(&path, from.unwrap_or(0.0), Path::new(&out))?;
still(&path, from.unwrap_or(0.0), Path::new(&out), None)?;
return Ok(());
}
// video: concat, trim, scale
+11 -4
View File
@@ -2,7 +2,7 @@
//! What agents used ffmpeg and ffprobe for, on raea-media (the platform's decoders and encoders, Symphonia's audio):
//!
//! raea media probe FILE duration, size, fps, codec, audio (JSON)
//! raea media still FILE --at S -o OUT.png|.jpg the frame showing at S
//! raea media still FILE --at S [--width W] -o OUT.png|.jpg the frame showing at S (an image: itself), W px wide at most
//! raea media sheet FILE... [--n 12] [--width 240] -o OUT a contact sheet (n frames of one file, or each file's middle)
//! raea media audio FILE [--rate 16000] [--mono] [--from S --to S] -o OUT.wav|- (- is f32le on stdout)
//! raea media loudness FILE [--from S --to S] integrated LUFS, mean and peak dB, true peak
@@ -10,6 +10,7 @@
//! raea media cuts FILE [--threshold 0.08] shot changes (ffmpeg's scene score)
//! raea media freezes FILE [--noise 0.001] [--min 2] held pictures (ffmpeg's freezedetect)
//! raea media proxy FILE [--height 720] -o OUT.mp4 a smaller copy
//! raea media lod MODEL.glb [--level 1] [--texture 1024] -o OUT.glb a model at a lower level of detail (triangles halved a level)
//! raea media trim FILE --from S --to S -o OUT.mp4 a stretch, frame-exact (re-encoded)
//! raea media concat A B ... -o OUT.mp4 one after another (same aspect)
//! raea media encode --size WxH [--fps 60] [--quality Q] [--audio FILE] -o OUT.mp4 raw RGBA frames on stdin, signed
@@ -28,6 +29,8 @@ use serde_json::{Value, json};
// `raea media|ffmpeg|ffprobe|render|shots` as one in-process command line
mod command;
pub use command::command;
/// a model at a lower level of detail (docs/preview.feature PV3c)
mod lod;
mod probe;
use probe::*;
mod picture;
@@ -86,11 +89,11 @@ fn num(fl: &BTreeMap<String, String>, k: &str) -> R<Option<f64>> {
}
/// The verbs `raea media` answers here.
pub const VERBS: &[&str] = &["probe", "still", "sheet", "audio", "loudness", "motion", "cuts", "freezes", "proxy", "trim", "concat", "encode", "help"];
pub const VERBS: &[&str] = &["probe", "still", "sheet", "audio", "loudness", "motion", "cuts", "freezes", "proxy", "lod", "trim", "concat", "encode", "help"];
pub fn cli(args: &[String]) -> i32 {
let Some(verb) = args.first() else {
println!("usage: raea media <probe|still|sheet|audio|loudness|motion|cuts|proxy|trim|concat|encode> FILE ... (raea media help)");
println!("usage: raea media <probe|still|sheet|audio|loudness|motion|cuts|proxy|lod|trim|concat|encode> FILE ... (raea media help)");
return 2;
};
let (pos, fl) = parse(&args[1..]);
@@ -116,7 +119,7 @@ fn run(verb: &str, pos: &[String], fl: &BTreeMap<String, String>) -> R<Option<Va
"probe" => probe(&file()?).map(Some),
"still" => {
let at = num(fl, "at")?.unwrap_or(0.0);
still(&file()?, at, &out()?).map(Some)
still(&file()?, at, &out()?, fl.get("width").and_then(|n| n.parse().ok())).map(Some)
}
"sheet" => {
let files: Vec<PathBuf> = pos.iter().map(PathBuf::from).collect();
@@ -158,6 +161,10 @@ fn run(verb: &str, pos: &[String], fl: &BTreeMap<String, String>) -> R<Option<Va
let (from, to) = range()?;
cuts(&file()?, th, from, to).map(|(v, _)| Some(v))
}
"lod" => {
let level = fl.get("level").and_then(|v| v.parse().ok()).unwrap_or(1);
lod::lod(&file()?, level, fl.get("texture").and_then(|v| v.parse().ok()).unwrap_or(1024), &out()?).map(Some)
}
"proxy" => {
let h = fl.get("height").and_then(|h| h.parse().ok()).unwrap_or(720);
encode(&[(file()?, None, None)], Some(h), &out()?, fl.get("kbps").and_then(|k| k.parse().ok())).map(Some)
+314
View File
@@ -0,0 +1,314 @@
//! `raea media lod MODEL.glb [--level 1] [--texture 1024] -o OUT.glb`: a model at a lower level of detail
//! (docs/preview.feature PV3c). Each level halves the triangles of every mesh (meshoptimizer's simplifier, on the
//! mesh's own vertices, so skins, morph targets, UVs and materials are untouched: only the index lists are replaced)
//! and its embedded pictures are made at most `--texture` px on their longer side. What nothing uses any more leaves
//! the file. A .glb with its buffer inside it only: a .gltf's separate files are left to their own tools.
use std::path::Path;
use serde_json::json;
use super::*;
const GLB: u32 = 0x4654_6c67;
const JSON: u32 = 0x4e4f_534a;
const BIN: u32 = 0x004e_4942;
/// The file's JSON and its binary chunk.
fn read(path: &Path) -> R<(Value, Vec<u8>)> {
let b = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
let u32_at = |i: usize| b.get(i..i + 4).map(|s| u32::from_le_bytes(s.try_into().unwrap()));
if u32_at(0) != Some(GLB) {
return Err(format!("{}: not a .glb (raea media lod reads a binary glTF with its buffer inside it)", path.display()));
}
let (mut at, mut doc, mut bin) = (12usize, None, Vec::new());
while let (Some(len), Some(kind)) = (u32_at(at), u32_at(at + 4)) {
let body = b.get(at + 8..at + 8 + len as usize).ok_or("the glb's chunk runs past its end")?;
match kind {
JSON => doc = Some(serde_json::from_slice::<Value>(body).map_err(|e| format!("the glb's JSON: {e}"))?),
BIN if bin.is_empty() => bin = body.to_vec(),
_ => {}
}
at += 8 + len as usize;
}
Ok((doc.ok_or("the glb has no JSON chunk")?, bin))
}
fn write(path: &Path, doc: &Value, bin: &[u8]) -> R<()> {
let mut text = serde_json::to_vec(doc).map_err(|e| e.to_string())?;
while text.len() % 4 != 0 {
text.push(b' ');
}
let mut bin = bin.to_vec();
while bin.len() % 4 != 0 {
bin.push(0);
}
let mut out = Vec::with_capacity(28 + text.len() + bin.len());
for v in [GLB, 2, (28 + text.len() + bin.len()) as u32, text.len() as u32, JSON] {
out.extend_from_slice(&v.to_le_bytes());
}
out.extend_from_slice(&text);
out.extend_from_slice(&(bin.len() as u32).to_le_bytes());
out.extend_from_slice(&BIN.to_le_bytes());
out.extend_from_slice(&bin);
std::fs::write(path, out).map_err(|e| format!("{}: {e}", path.display()))
}
fn n(v: &Value, k: &str) -> Option<usize> {
Some(v.get(k)?.as_u64()? as usize)
}
/// An accessor's bytes in the buffer: where they start, the step between elements, how many.
fn span(doc: &Value, acc: usize) -> Option<(usize, usize, usize, u64)> {
let a = doc["accessors"].get(acc)?;
if a.get("sparse").is_some() {
return None;
}
let view = doc["bufferViews"].get(n(a, "bufferView")?)?;
if n(view, "buffer").unwrap_or(0) != 0 {
return None;
}
let ty = a["componentType"].as_u64()?;
let size = match ty { 5120 | 5121 => 1, 5122 | 5123 => 2, _ => 4 } * match a["type"].as_str()? { "SCALAR" => 1, "VEC2" => 2, "VEC3" => 3, _ => 4 };
Some((n(view, "byteOffset").unwrap_or(0) + n(a, "byteOffset").unwrap_or(0), n(view, "byteStride").filter(|s| *s > 0).unwrap_or(size), n(a, "count")?, ty))
}
/// A view of `bytes` added at the end of the buffer (aligned to 4), and its index.
fn push_view(doc: &mut Value, bin: &mut Vec<u8>, bytes: &[u8], target: Option<u64>) -> usize {
while bin.len() % 4 != 0 {
bin.push(0);
}
let mut view = json!({"buffer": 0, "byteOffset": bin.len(), "byteLength": bytes.len()});
if let Some(t) = target {
view["target"] = json!(t);
}
bin.extend_from_slice(bytes);
let views = doc["bufferViews"].as_array_mut().unwrap();
views.push(view);
views.len() - 1
}
/// Every triangle list's indices simplified to `keep` of its triangles (never under 12): the triangles before and after.
fn simplify(doc: &mut Value, bin: &mut Vec<u8>, keep: f32) -> (usize, usize) {
let (mut before, mut after) = (0, 0);
// an index list several primitives share is simplified once (against the first one's positions), in its own
// accessor, so the old indices are left with nothing using them and leave the file
let mut done: std::collections::HashSet<usize> = Default::default();
let prims: Vec<(usize, usize)> = doc["meshes"].as_array().into_iter().flatten().enumerate().flat_map(|(m, mesh)| (0..mesh["primitives"].as_array().map_or(0, Vec::len)).map(move |p| (m, p))).collect();
for (m, p) in prims {
let prim = &doc["meshes"][m]["primitives"][p];
if prim.get("mode").and_then(Value::as_u64).unwrap_or(4) != 4 {
continue;
}
let (Some(ia), Some(pa)) = (n(prim, "indices"), n(&prim["attributes"], "POSITION")) else { continue };
if done.contains(&ia) {
continue;
}
let (Some((io, is, ic, ity)), Some((po, ps, pc, 5126))) = (span(doc, ia), span(doc, pa)) else { continue };
before += ic / 3;
let read = |i: usize| -> u32 {
let at = io + i * is;
match ity {
5121 => bin[at] as u32,
5123 => u16::from_le_bytes([bin[at], bin[at + 1]]) as u32,
_ => u32::from_le_bytes([bin[at], bin[at + 1], bin[at + 2], bin[at + 3]]),
}
};
if io + ic.saturating_sub(1) * is + 1 > bin.len() || po + pc * ps > bin.len() + ps - 12 {
continue;
}
let indices: Vec<u32> = (0..ic).map(read).collect();
let target = (((ic / 3) as f32 * keep) as usize).max(12).min(ic / 3) * 3;
// the positions as meshoptimizer reads them: a stride of bytes, three floats at its start
let positions = &bin[po..(po + pc * ps).min(bin.len())];
let positions: Vec<u8> = if positions.len() % ps == 0 { positions.to_vec() } else { (0..pc).flat_map(|v| bin[po + v * ps..po + v * ps + 12].to_vec()).collect() };
let stride = if positions.len() == pc * 12 { 12 } else { ps };
let Ok(adapter) = meshopt::VertexDataAdapter::new(&positions, stride, 0) else { continue };
// a loose error bound: the count is what a level asks for, the shape is kept as far as it allows
let out = meshopt::simplify(&indices, &adapter, target, 0.05, meshopt::SimplifyOptions::None, None);
let out = if out.len() >= 3 && out.len() < indices.len() { out } else { indices };
after += out.len() / 3;
let bytes: Vec<u8> = out.iter().flat_map(|i| i.to_le_bytes()).collect();
let view = push_view(doc, bin, &bytes, Some(34963));
doc["accessors"][ia] = json!({"bufferView": view, "componentType": 5125, "count": out.len(), "type": "SCALAR"});
done.insert(ia);
}
(before, after)
}
/// Each embedded PNG or JPEG longer than `max` px made that long, in its own format: how many were.
fn shrink_pictures(doc: &mut Value, bin: &mut Vec<u8>, max: u32) -> usize {
let mut made = 0;
for i in 0..doc["images"].as_array().map_or(0, Vec::len) {
let img = &doc["images"][i];
let (Some(view), Some(mime)) = (n(img, "bufferView"), img["mimeType"].as_str().map(str::to_string)) else { continue };
let v = &doc["bufferViews"][view];
let (at, len) = (n(v, "byteOffset").unwrap_or(0), n(v, "byteLength").unwrap_or(0));
let Some(bytes) = bin.get(at..at + len) else { continue };
let Ok(pic) = image::load_from_memory(bytes) else { continue };
if pic.width().max(pic.height()) <= max {
continue;
}
let k = max as f64 / pic.width().max(pic.height()) as f64;
let small = pic.resize_exact(((pic.width() as f64 * k).round() as u32).max(1), ((pic.height() as f64 * k).round() as u32).max(1), image::imageops::FilterType::CatmullRom);
let mut out = std::io::Cursor::new(Vec::new());
let wrote = if mime == "image/jpeg" { image::DynamicImage::ImageRgb8(small.to_rgb8()).write_to(&mut out, image::ImageFormat::Jpeg) } else { small.write_to(&mut out, image::ImageFormat::Png) };
if wrote.is_err() || (mime != "image/jpeg" && mime != "image/png") {
continue;
}
let view = push_view(doc, bin, out.get_ref(), None);
doc["images"][i]["bufferView"] = json!(view);
made += 1;
}
made
}
/// The buffer with only the views something still uses, the views numbered again.
fn compact(doc: &mut Value, bin: &[u8]) -> Vec<u8> {
let views = doc["bufferViews"].as_array().cloned().unwrap_or_default();
let mut used = vec![false; views.len()];
let mut mark = |v: &Value| {
if let Some(i) = n(v, "bufferView").filter(|i| *i < used.len()) {
used[i] = true;
}
};
for a in doc["accessors"].as_array().into_iter().flatten() {
mark(a);
mark(&a["sparse"]["indices"]);
mark(&a["sparse"]["values"]);
}
for i in doc["images"].as_array().into_iter().flatten() {
mark(i);
}
// anything an extension points at by "bufferView" stays too
fn walk(v: &Value, mark: &mut dyn FnMut(&Value)) {
match v {
Value::Object(m) => {
mark(v);
m.values().for_each(|x| walk(x, mark));
}
Value::Array(a) => a.iter().for_each(|x| walk(x, mark)),
_ => {}
}
}
walk(&doc["extensions"].clone(), &mut mark);
for m in doc["meshes"].as_array().into_iter().flatten() {
walk(&m["primitives"], &mut |v| if v.get("extensions").is_some() { walk(&v["extensions"], &mut |x| if let Some(i) = n(x, "bufferView").filter(|i| *i < used.len()) { used[i] = true }) });
}
let mut out = Vec::new();
let mut to = vec![usize::MAX; views.len()];
let mut kept = Vec::new();
for (i, v) in views.iter().enumerate().filter(|(i, _)| used[*i]) {
while out.len() % 4 != 0 {
out.push(0);
}
let (at, len) = (n(v, "byteOffset").unwrap_or(0), n(v, "byteLength").unwrap_or(0));
let mut v = v.clone();
v["byteOffset"] = json!(out.len());
out.extend_from_slice(bin.get(at..at + len).unwrap_or(&[]));
to[i] = kept.len();
kept.push(v);
}
fn renumber(v: &mut Value, to: &[usize]) {
match v {
Value::Object(m) => {
if let Some(i) = m.get("bufferView").and_then(Value::as_u64).map(|i| i as usize).filter(|i| *i < to.len() && to[*i] != usize::MAX) {
m.insert("bufferView".into(), json!(to[i]));
}
m.values_mut().for_each(|x| renumber(x, to));
}
Value::Array(a) => a.iter_mut().for_each(|x| renumber(x, to)),
_ => {}
}
}
doc["bufferViews"] = Value::Array(kept);
for k in ["accessors", "images", "meshes", "extensions"] {
if doc.get(k).is_some() {
renumber(&mut doc[k], &to);
}
}
doc["buffers"] = json!([{"byteLength": out.len()}]);
out
}
pub fn lod(path: &Path, level: u32, texture: u32, out: &Path) -> R<Value> {
let (mut doc, mut bin) = read(path)?;
if doc["buffers"].as_array().is_some_and(|b| b.len() > 1 || b.iter().any(|x| x.get("uri").is_some())) {
return Err(format!("{}: its buffers are separate files; raea media lod reads a .glb with its buffer inside it", path.display()));
}
let (before, after) = simplify(&mut doc, &mut bin, 0.5f32.powi(level.max(1) as i32));
let pictures = shrink_pictures(&mut doc, &mut bin, texture.max(16));
let bin = compact(&mut doc, &bin);
write(out, &doc, &bin)?;
let bytes = |p: &Path| std::fs::metadata(p).map(|m| m.len()).unwrap_or(0);
Ok(json!({"wrote": out, "level": level.max(1), "triangles": [before, after], "pictures_made_smaller": pictures, "bytes": [bytes(path), bytes(out)]}))
}
#[cfg(test)]
mod tests {
use super::*;
/// A flat grid of `n` by `n` squares as a .glb: positions and u16 indices, and a picture nothing shrinks.
fn grid(n: u16) -> (Value, Vec<u8>) {
let mut bin = Vec::new();
for y in 0..=n {
for x in 0..=n {
for v in [x as f32, 0.0, y as f32] {
bin.extend_from_slice(&v.to_le_bytes());
}
}
}
let verts = (n as usize + 1) * (n as usize + 1);
let index_at = bin.len();
let mut count = 0;
for y in 0..n {
for x in 0..n {
let a = y * (n + 1) + x;
for i in [a, a + 1, a + n + 1, a + 1, a + n + 2, a + n + 1] {
bin.extend_from_slice(&i.to_le_bytes());
count += 1;
}
}
}
let doc = json!({
"asset": {"version": "2.0"},
"buffers": [{"byteLength": bin.len()}],
"bufferViews": [{"buffer": 0, "byteOffset": 0, "byteLength": verts * 12}, {"buffer": 0, "byteOffset": index_at, "byteLength": count * 2}],
"accessors": [{"bufferView": 0, "componentType": 5126, "count": verts, "type": "VEC3"}, {"bufferView": 1, "componentType": 5123, "count": count, "type": "SCALAR"}],
"meshes": [{"primitives": [{"attributes": {"POSITION": 0}, "indices": 1}]}],
"nodes": [{"mesh": 0}], "scenes": [{"nodes": [0]}], "scene": 0,
});
(doc, bin)
}
#[test]
fn a_level_halves_the_triangles_and_the_old_indices_leave_the_file() {
let dir = std::env::temp_dir().join(format!("raea-lod-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let (doc, bin) = grid(16);
let (src, out) = (dir.join("grid.glb"), dir.join("grid.lod1.glb"));
write(&src, &doc, &bin).unwrap();
let said = lod(&src, 1, 1024, &out).unwrap();
let (before, after) = (said["triangles"][0].as_u64().unwrap(), said["triangles"][1].as_u64().unwrap());
assert_eq!(before, 512);
assert!(after <= 256 && after >= 12, "{after} triangles");
// read back: one index view (the new one), the positions as they were, every index a vertex of the mesh
let (doc, bin) = read(&out).unwrap();
assert_eq!(doc["bufferViews"].as_array().unwrap().len(), 2);
let (io, _, ic, ty) = span(&doc, doc["meshes"][0]["primitives"][0]["indices"].as_u64().unwrap() as usize).unwrap();
assert_eq!((ic as u64, ty), (after * 3, 5125));
assert!((0..ic).all(|i| u32::from_le_bytes(bin[io + i * 4..io + i * 4 + 4].try_into().unwrap()) < 289));
assert_eq!(doc["accessors"][0]["count"], 289);
let two = lod(&src, 2, 1024, &dir.join("grid.lod2.glb")).unwrap();
assert!(two["triangles"][1].as_u64().unwrap() <= 128);
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn a_file_that_is_not_a_glb_is_refused() {
let p = std::env::temp_dir().join(format!("raea-lod-not-{}.glb", std::process::id()));
std::fs::write(&p, b"plain text").unwrap();
assert!(lod(&p, 1, 1024, &p.with_extension("out.glb")).unwrap_err().contains("not a .glb"));
std::fs::remove_file(&p).ok();
}
}
+6 -1
View File
@@ -25,12 +25,17 @@ pub(crate) fn frame(path: &Path, t: f64) -> R<image::RgbaImage> {
to_image(d.frame_at(t)?)
}
pub fn still(path: &Path, at: f64, out: &Path) -> R<Value> {
/// `width`: the still made that wide (its height in proportion) when the picture is wider; never made bigger.
pub fn still(path: &Path, at: f64, out: &Path, width: Option<u32>) -> R<Value> {
let img = if IMAGE_EXTS.contains(&ext(path).as_str()) {
image::open(path).map_err(|e| format!("{}: {e}", path.display()))?.to_rgba8()
} else {
frame(path, at)?
};
let img = match width.filter(|w| *w > 0 && *w < img.width()) {
Some(w) => image::imageops::resize(&img, w, ((img.height() as f64 * w as f64 / img.width() as f64).round() as u32).max(1), image::imageops::FilterType::CatmullRom),
None => img,
};
save(&img, out)?;
Ok(json!({"wrote": out, "at": at, "width": img.width(), "height": img.height()}))
}
+21
View File
@@ -0,0 +1,21 @@
[package]
name = "raea-app-notes"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "A person's notes on a project as files the work is held to (docs/direction.feature DR5, DR6): `raea notes take`, `check`, `ls` and `post`"
[dependencies]
# Note and Ask, the project found by its .raea/project, and the world a note is an entity in
raea-core-facts = { path = "../../core/facts" }
# when a run of an ask's check was (UTC), as raea check stamps its record
raea-io-trace = { path = "../../io/trace" }
# what each ask has been through, kept as JSON (state.rs)
serde = { version = "1", features = ["derive"] }
serde_json = "1"
# the render a clip to sign is cut from, by its SHA-256 (check.rs)
sha2 = "0.10"
[dev-dependencies]
tempfile = "3"
+235
View File
@@ -0,0 +1,235 @@
//! `raea notes check` (docs/direction.feature DR6): each ask's check run as a rule on the work as it stands, through
//! `raea check`'s run (apps/direction, which the CLI lends). An ask's check must fail first: one that passes on its
//! first run is refused, as it isn't measuring the ask, and the work may change only once it has failed. What each run
//! found is kept (state.rs); `raea check` keeps it too, when it runs the notes' checks beside its rules. An ask the
//! person signs gets its clip cut here, from its composition's newest render.
use std::path::{Path, PathBuf};
use raea_core_facts::{Finding, Level, record};
/// A rule as `raea check` runs one: an ask's is one, run through the CLI's Runner.
pub use raea_core_facts::Rule;
use crate::state::{self, Clip, Failed, Run, State};
use crate::{Eval, Kept, R, place, quoted, read};
/// One composition's run: its file from the project (`#ID` after it where the file registers several), what the
/// rules found and which waited and for what, its newest render, its shots (name, first frame, end) and its rate.
pub struct Ran {
pub of: String,
pub found: Vec<Finding>,
pub waits: Vec<(String, String)>,
pub render: Option<Rendered>,
pub shots: Vec<(String, i64, Option<i64>)>,
pub fps: f64,
}
/// A composition's newest render: its file, whether the composition changed after it, and how many frames it drew.
pub struct Rendered {
pub out: PathBuf,
pub stale: bool,
pub frames: i64,
}
/// Runs rules on a project's compositions as `raea check` runs its own (taking its --composition, --render and
/// --no-render), every frame read when `whole` (a clip's shot is found in them).
pub type Runner = fn(&Path, &[Rule], &[String], bool) -> R<Vec<Ran>>;
/// An ask's rule's `by`, which its findings carry, so two asks that run one check are told apart.
pub fn by(id: &str) -> String {
format!("note {id}")
}
/// Whether `of`, the composition an ask names (its file from the project, `#ID` after it where the file registers
/// several), is the one a run names `named` (its file, and `#ID` when it has one): a file alone is any composition
/// in it.
pub fn is_of(of: &str, named: &str) -> bool {
let (file, id) = named.split_once('#').map_or((named, None), |(f, i)| (f, Some(i)));
match of.split_once('#') {
Some((f, i)) => f == file && id == Some(i),
None => of == file,
}
}
/// What ask `id`'s check found in a run.
fn found_by<'a>(ran: &'a [Ran], id: &str) -> impl Iterator<Item = &'a Finding> {
let by = by(id);
ran.iter().flat_map(|r| &r.found).filter(move |f| f.by == by)
}
/// Each note's file number with the note, for those that read.
fn numbered<'a>(project: &Path, notes: &'a [Kept]) -> Vec<(u32, &'a Kept, &'a raea_core_facts::Note)> {
notes.iter().filter_map(|k| Some((place(project, &project.join(&k.file))?.1, k, k.note.as_ref().ok()?))).collect()
}
/// The notes' asks that have a check, each as a rule: the ask's id (n3.2) and words, its check (a .ts check's path
/// from the note's folder, as a controller's is from its own), its values, `by` the ask; and each note that can't be
/// read, as a finding.
pub fn rules(project: &Path, notes: &[Kept]) -> (Vec<Rule>, Vec<Finding>) {
let bad = notes.iter().filter_map(|k| k.note.as_ref().err().map(|e| Finding::new("note", Level::Error, format!("raea can't read it: {e}"), "raea notes").about(k.file.display().to_string(), None))).collect();
let mut out = Vec::new();
for (number, k, n) in numbered(project, notes) {
for (i, a) in n.asks.iter().enumerate() {
let Some(c) = &a.check else { continue };
let check = if c.ends_with(".ts") { project.join(k.file.parent().unwrap_or(Path::new(""))).join(c).display().to_string() } else { c.clone() };
let id = state::id(number, i + 1);
out.push(Rule { by: by(&id), id, text: a.text.clone(), check, values: a.values.clone().unwrap_or_default(), level: None, of: a.of.clone() });
}
}
(out, bad)
}
/// What a run of the notes' rules says of each ask whose rule was among `rules` (`--only` runs one), kept in `s`: a
/// line for each, and whether one was refused (its first run passed).
pub fn settle(project: &Path, notes: &[Kept], rules: &[Rule], ran: &[Ran], stamp: &str, s: &mut State) -> (Vec<String>, bool) {
let commit = record::commit(project, ".");
let (mut out, mut refused) = (Vec::new(), false);
for (number, k, n) in numbered(project, notes) {
for (i, a) in n.asks.iter().enumerate() {
let id = state::id(number, i + 1);
let Some(check) = a.check.as_ref().filter(|_| rules.iter().any(|r| r.id == id)) else { continue };
let found = found_by(ran, &id).count();
let waits = ran.iter().flat_map(|r| &r.waits).find(|(r, _)| *r == id).map(|(_, w)| w.clone());
let run = Run { at: stamp.into(), commit: commit.clone(), found, waits: waits.clone().filter(|_| found == 0) };
let kept = s.entry(id.clone()).or_default();
let first = kept.failed.as_ref().is_none_or(|f| !state::same_check(a, f));
let head = format!("{id} {}: {}", k.file.display(), quoted(&a.text, 70));
out.push(match (&run.waits, found, first) {
(Some(w), _, _) => format!("{head}: waits for {w}"),
(None, 0, true) => {
refused = true;
kept.refused = Some(run.clone());
format!("{head}: refused: its check passes on the work as it stands, so it isn't measuring the ask; write one that fails now, before the work changes")
}
(None, 0, false) => format!("{head}: passing"),
(None, n, true) => {
kept.failed = Some(Failed { check: check.clone(), values: a.values.clone().unwrap_or_default(), run: run.clone() });
kept.refused = None;
format!("{head}: fails on the work as it stands ({n} finding{}): its check measures the ask, and the work may change now", if n == 1 { "" } else { "s" })
}
(None, n, false) => format!("{head}: failing ({n} finding{})", if n == 1 { "" } else { "s" }),
});
kept.last = Some(run);
}
}
(out, refused)
}
/// A file's SHA-256.
fn sha256(p: &Path) -> R<String> {
use sha2::{Digest, Sha256};
let mut f = std::fs::File::open(p).map_err(|e| format!("{}: {e}", p.display()))?;
let mut d = Sha256::new();
std::io::copy(&mut f, &mut d).map_err(|e| format!("{}: {e}", p.display()))?;
Ok(format!("{:x}", d.finalize()))
}
/// Frames `a` to `b` (the frame after its last) of `out` at `fps`, cut to `to` with ffmpeg.
fn cut(out: &Path, [a, b]: [i64; 2], fps: f64, to: &Path) -> R<()> {
if let Some(d) = to.parent() {
std::fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?;
}
let (from, len) = (format!("{:.4}", a as f64 / fps), format!("{:.4}", (b - a) as f64 / fps));
let args = ["-hide_banner", "-loglevel", "error", "-y", "-ss", &from, "-i"];
let o = std::process::Command::new("ffmpeg").args(args).arg(out).args(["-t", &len, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac"]).arg(to).output().map_err(|e| format!("ffmpeg: {e}"))?;
if !o.status.success() {
return Err(format!("ffmpeg: {}", String::from_utf8_lossy(&o.stderr).trim()));
}
Ok(())
}
/// Each ask the person signs, its clip cut from its composition's newest render (again only when the render or the
/// frames changed), kept in `s`: a line for each.
pub fn clips(project: &Path, notes: &[Kept], ran: &[Ran], s: &mut State) -> Vec<String> {
let mut out = Vec::new();
for (number, k, n) in numbered(project, notes) {
for (i, a) in n.asks.iter().enumerate() {
let Some(p) = a.proof.as_ref().filter(|p| p.sign) else { continue };
let id = state::id(number, i + 1);
let head = format!("{id} {}: its clip", k.file.display());
let comp = match &a.of {
Some(of) => ran.iter().find(|r| is_of(of, &r.of)),
None if ran.len() == 1 => ran.first(),
None => {
out.push(format!("{head}: which composition? the project has {}: name one in the ask's `of`", ran.iter().map(|r| r.of.as_str()).collect::<Vec<_>>().join(", ")));
continue;
}
};
let Some(r) = comp else {
out.push(format!("{head}: no composition {} was checked", a.of.as_deref().unwrap_or("")));
continue;
};
let Some(render) = &r.render else {
out.push(format!("{head} waits for a render of {}", r.of));
continue;
};
// a render the composition changed after isn't the work: nothing is cut from it, and the clip kept from it
// (what the person signed, if they did) is marked so, until it's rendered again
if render.stale {
if let Some(c) = s.get_mut(&id).and_then(|k| k.clip.as_mut()) {
c.stale = true;
}
out.push(format!("{head} waits for a render of {} as it stands: it changed after its newest render", r.of));
continue;
}
let frames = match (p.frames, &p.shot) {
(Some(f), _) => f,
(None, Some(shot)) => match r.shots.iter().find(|(name, ..)| name == shot) {
Some((_, from, to)) => [*from, to.unwrap_or(render.frames)],
None => {
out.push(format!("{head}: {} has no shot named {shot}", r.of));
continue;
}
},
(None, None) => [0, render.frames],
};
let hash = match sha256(&render.out) {
Ok(h) => h,
Err(e) => {
out.push(format!("{head}: {e}"));
continue;
}
};
let kept = s.entry(id.clone()).or_default();
let file = project.join(".raea/notes-clips").join(format!("{id}.mp4"));
let same = kept.clip.as_ref().is_some_and(|c| c.render == hash && c.frames == frames && c.file.is_file());
if !same {
if let Err(e) = cut(&render.out, frames, r.fps, &file) {
out.push(format!("{head}: {e}"));
continue;
}
}
kept.clip = Some(Clip { file: file.clone(), of: r.of.clone(), render: hash, frames, stale: false });
out.push(format!("{head}, frames {}-{} of {}, {} from its newest render", frames[0], frames[1] - 1, r.of, if same { "kept" } else { "cut" }));
}
}
out
}
/// `raea notes check`: each ask's check on the work as it stands, and each clip to sign cut; 1 when an ask was
/// refused or a note can't be read.
pub(crate) fn check(project: &Path, args: &[String], eval: Eval, run: Runner) -> R<(String, i32)> {
let notes = read(project, eval);
let (rules, bad) = rules(project, &notes);
let signs = notes.iter().filter_map(|k| k.note.as_ref().ok()).flat_map(|n| &n.asks).any(|a| a.proof.as_ref().is_some_and(|p| p.sign));
let mut out: Vec<String> = bad.iter().map(Finding::line).collect();
if rules.is_empty() && !signs {
out.push("no ask has a check or a clip to sign yet: restate the notes' asks with one each (raea notes ls)".into());
return Ok((out.join("\n"), i32::from(!bad.is_empty())));
}
let ran = run(project, &rules, args, signs)?;
let stamp = raea_io_trace::utc(std::time::SystemTime::now()).1;
let mut s = state::read(project);
let (lines, refused) = settle(project, &notes, &rules, &ran, &stamp, &mut s);
// each ask's line, then what its check found
for l in lines {
let id = l.split(' ').next().unwrap_or("").to_string();
out.push(l);
out.extend(found_by(&ran, &id).map(|f| format!(" {}", f.line())));
}
out.extend(clips(project, &notes, &ran, &mut s));
state::write(project, &s)?;
let tally = crate::tally(project, &notes, &s);
out.push(tally);
Ok((out.join("\n"), i32::from(refused || !bad.is_empty())))
}
+188
View File
@@ -0,0 +1,188 @@
//! A person's notes on a project (docs/direction.feature DR5, DR6). `raea notes take` writes each note the person
//! sends from the raea app (an edit comment with its pin, or a note on an item) or says in a session to a file,
//! notes/<round>/<id>.ts, with their words verbatim and no asks. The agent restates each as its asks before anything
//! in the work changes, each with a check, or a clip for the person to sign. `raea notes check` runs each ask's check
//! on the work as it stands, which must fail first, and `raea notes ls` says where each note and ask stands and what
//! its restatement still owes. `raea notes post` shows the asks and where they stand on the person's comments in the
//! app, and their corrections and signs come back with the next take. In a project's world each note is an entity
//! with a Note.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use raea_core_facts::{Facts, Note, record};
use serde_json::json;
pub mod check;
mod post;
pub mod state;
mod take;
pub const USAGE: &str = "raea notes take [PROJECT] [--inbox NAME] [--said WORDS]... | raea notes check [PROJECT] [--composition ID] [--render OUT | --no-render] | raea notes ls [PROJECT] [--json] | raea notes post [PROJECT] (a person's notes as files the work is held to: take writes each note sent from the raea app or said in a session to notes/ROUND/ID.ts, the words verbatim, to be restated as asks before anything changes, and writes in each correction and sign the person sent back; check runs each ask's check on the work as it stands, which must fail before the work changes (a check that passes first is refused), and cuts each clip the person is to sign from the newest render; ls says where each note and ask stands (to restate, to check, failing, to sign, passing, signed) and what its restatement still owes; post shows each note's asks and where they stand on its comment in the raea app, and each clip to sign)";
/// Evaluates a .ts file's default export to its JSON (the CLI's spec host).
pub type Eval = fn(&Path) -> Result<String, String>;
pub(crate) type R<T> = Result<T, String>;
/// The flags `raea notes` takes, and whether each takes a value.
const FLAGS: [(&str, bool); 6] = [("--inbox", true), ("--said", true), ("--json", false), ("--composition", true), ("--render", true), ("--no-render", false)];
/// One note file: where it is in the project, and the note, or why it can't be read.
pub struct Kept {
pub file: PathBuf,
pub note: R<Note>,
}
/// `raea notes VERB ...`, printed; its exit code (1: a note that can't be read, or an ask's check refused; 2: the
/// command was wrong). `run` is `raea check`'s run of rules on the project's compositions (apps/direction).
pub fn cli(args: &[String], eval: Eval, run: check::Runner) -> i32 {
match go(args, eval, run) {
Ok((out, code)) => {
println!("{out}");
code
}
Err(e) => {
eprintln!("raea notes: {e}");
2
}
}
}
fn go(args: &[String], eval: Eval, run: check::Runner) -> R<(String, i32)> {
let Some(verb) = args.first().map(String::as_str).filter(|v| !matches!(*v, "--help" | "-h" | "help")) else {
return Ok((USAGE.into(), 0));
};
let rest = &args[1..];
let mut target = None;
let mut it = rest.iter();
while let Some(a) = it.next() {
match FLAGS.iter().find(|(f, _)| f == a) {
Some((_, true)) => {
it.next().ok_or_else(|| format!("{a} takes a value\n{USAGE}"))?;
}
Some(_) => {}
None if a.starts_with("--") => return Err(format!("no flag {a}\n{USAGE}")),
None if target.is_none() => target = Some(a.as_str()),
None => return Err(format!("one project at a time ({a} is a second)\n{USAGE}")),
}
}
let target = target.unwrap_or(".");
let project = record::up(Path::new(target), ".raea/project").ok_or_else(|| format!("{target} isn't in a raea project (no .raea/project at or above it)\n{USAGE}"))?;
match verb {
"take" => take::take(&project, rest).map(|s| (s, 0)),
"ls" => Ok(ls(&project, rest.iter().any(|a| a == "--json"), eval)),
"check" => check::check(&project, rest, eval, run),
"post" => Ok(post::post(&project, eval, post::run_raea)),
v => Err(format!("no verb {v}\n{USAGE}")),
}
}
/// The values a flag was given, in order.
pub(crate) fn values<'a>(args: &'a [String], flag: &str) -> Vec<&'a str> {
args.iter().zip(args.iter().skip(1)).filter_map(|(f, v)| (f == flag).then_some(v.as_str())).collect()
}
/// A note file's round and number: notes/2/n7.ts is (2, 7); anything else under notes/ isn't a note.
pub(crate) fn place(project: &Path, f: &Path) -> Option<(u32, u32)> {
let rel = f.strip_prefix(project.join("notes")).ok()?;
let round = rel.parent()?.to_str()?.parse().ok()?;
let n = rel.file_name()?.to_str()?.strip_prefix('n')?.strip_suffix(".ts")?.parse().ok()?;
Some((round, n))
}
/// The project's note files, by round and number.
pub fn files(project: &Path) -> Vec<PathBuf> {
let dirs = std::fs::read_dir(project.join("notes")).into_iter().flatten().flatten().map(|e| e.path());
let mut out: Vec<((u32, u32), PathBuf)> = dirs.flat_map(|d| std::fs::read_dir(d).into_iter().flatten().flatten().map(|e| e.path())).filter_map(|f| Some((place(project, &f)?, f))).collect();
out.sort();
out.into_iter().map(|(_, f)| f).collect()
}
/// Every note in the project, read through its file's default export.
pub fn read(project: &Path, eval: Eval) -> Vec<Kept> {
let of = |f: &Path| eval(f).and_then(|j| serde_json::from_str::<Note>(&j).map_err(|e| format!("not a note ({e})")));
files(project).into_iter().map(|f| Kept { note: of(&f), file: f.strip_prefix(project).map(Path::to_path_buf).unwrap_or(f) }).collect()
}
/// The notes as entities in a world, one with a Note each.
pub fn spawn(world: &mut Facts, notes: &[Kept]) {
for n in notes.iter().filter_map(|k| k.note.as_ref().ok()) {
let e = world.spawn(None);
world.put(e, n);
}
}
/// A note's first line, quoted and cut to `n` characters.
pub(crate) fn quoted(words: &str, n: usize) -> String {
let line = words.lines().next().unwrap_or("").trim();
if line.chars().count() > n { format!("\"{}…\"", line.chars().take(n).collect::<String>().trim_end()) } else { format!("\"{line}\"") }
}
/// Each note's number (its file's: n7 is 7), where it stands and each of its asks'.
fn standings(project: &Path, n: &Note, file: &Path, s: &state::State) -> (u32, state::Standing, Vec<state::Standing>) {
let number = place(project, &project.join(file)).map_or(0, |p| p.1);
let (note, asks) = state::of_note(n, number, s);
(number, note, asks)
}
/// How many notes stand where: "5 notes: 2 failing, 1 to restate".
pub(crate) fn tally(project: &Path, notes: &[Kept], s: &state::State) -> String {
let mut t: BTreeMap<&str, usize> = BTreeMap::new();
for k in notes {
*t.entry(k.note.as_ref().map_or("can't be read", |n| standings(project, n, &k.file, s).1.word())).or_default() += 1;
}
let counts: Vec<String> = t.iter().map(|(s, c)| format!("{c} {s}")).collect();
format!("{} note{}: {}", notes.len(), if notes.len() == 1 { "" } else { "s" }, counts.join(", "))
}
/// `raea notes ls`: each note with where it stands, each ask with its id and where it stands, and what its
/// restatement still owes; 1 when a note can't be read.
fn ls(project: &Path, as_json: bool, eval: Eval) -> (String, i32) {
let notes = read(project, eval);
let s = state::read(project);
let code = i32::from(notes.iter().any(|k| k.note.is_err()));
if as_json {
let v: Vec<_> = notes
.iter()
.map(|k| match &k.note {
Ok(n) => {
let (number, note, asks) = standings(project, n, &k.file, &s);
let each: Vec<_> = asks.iter().enumerate().map(|(i, a)| json!({ "id": state::id(number, i + 1), "state": a.word(), "says": a.said() })).collect();
json!({ "file": k.file, "note": n, "state": note.word(), "asks": each, "flags": n.flags() })
}
Err(e) => json!({ "file": k.file, "error": e }),
})
.collect();
return (serde_json::to_string_pretty(&v).unwrap_or_default(), code);
}
if notes.is_empty() {
return ("no notes yet: `raea notes take` writes each one the person sends from the raea app or says".into(), 0);
}
let mut out = Vec::new();
let mut restate = false;
for k in &notes {
let file = k.file.display();
let Ok(n) = &k.note else {
out.push(format!("{file}: can't be read: {}", k.note.as_ref().err().map_or("", String::as_str)));
continue;
};
let (number, note, asks) = standings(project, n, &k.file, &s);
restate |= note == state::Standing::ToRestate;
out.push(format!("{file}: round {}, {}: {}", n.round, note.word(), quoted(n.words.first().map_or("", String::as_str), 90)));
for (i, (a, st)) in n.asks.iter().zip(&asks).enumerate() {
let medium = a.medium.as_deref().map(|m| format!(" [{m}]")).unwrap_or_default();
let not = if a.not.is_empty() { String::new() } else { format!("; not: {}", a.not.join(", ")) };
out.push(format!(" {} {}{medium}{not}: {}", state::id(number, i + 1), a.text, st.said()));
}
out.extend(n.flags().into_iter().map(|f| format!(" ! {f}")));
}
out.push(tally(project, &notes, &s));
if restate {
out.push(take::RESTATE.into());
}
(out.join("\n"), code)
}
#[cfg(test)]
mod tests;
+140
View File
@@ -0,0 +1,140 @@
//! `raea notes post`: each note sent from the raea app gets where it stands shown on its comment (DR5, DR6), through
//! `raea show --on ITEM --working COMMENT`: its asks once restated (`--ask TEXT...`), for the person to correct one in
//! a word, which `raea notes take` writes into the note to be restated again; the note's state for the comment's
//! badge and each ask's (`--status S --states S1,S2`: to restate, to check, failing, to sign, passing, signed); and
//! each clip the person is to sign, under its ask (`--sign N --clip FILE --render HASH`). "done" is never the agent's:
//! a note closes when the person retires it.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use crate::state::{self, Standing};
use crate::{Eval, R, place, read};
/// What was last shown for each note, by where it came from (`.raea/notes-shown.json`): its asks, its states and its
/// clips. A note shown so already isn't shown again, so a comment isn't marked working again for nothing.
fn shown_at(project: &Path) -> PathBuf {
project.join(".raea/notes-shown.json")
}
/// The note from `from` as not shown: the person corrected it, so its next restatement is shown even in the same words
/// (the app takes new asks as the answer to their correction).
pub(crate) fn forget(project: &Path, from: &str) -> R<()> {
let f = shown_at(project);
let Ok(t) = std::fs::read_to_string(&f) else { return Ok(()) };
let mut shown: BTreeMap<String, Vec<String>> = serde_json::from_str(&t).unwrap_or_default();
if shown.remove(from).is_some() {
let t = serde_json::to_string_pretty(&shown).map_err(|e| e.to_string())?;
std::fs::write(&f, t + "\n").map_err(|e| format!("{}: {e}", f.display()))?;
}
Ok(())
}
/// Runs raea with these arguments: what it printed, or why it failed.
pub type Run = fn(&[String]) -> R<String>;
/// This raea, run again with `args`.
pub fn run_raea(args: &[String]) -> R<String> {
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let out = std::process::Command::new(exe).args(args).output().map_err(|e| e.to_string())?;
let said = |b: &[u8]| String::from_utf8_lossy(b).trim().to_string();
if out.status.success() { Ok(said(&out.stdout)) } else { Err(said(&out.stderr).lines().last().unwrap_or("raea show failed").to_string()) }
}
/// The item and comment a note sent from the app came from ("app ITEM cm-N"); a note on an item as a whole has none.
pub(crate) fn comment_of(from: &str) -> Option<(&str, &str)> {
let mut it = from.strip_prefix("app ")?.split(' ');
let (item, comment) = (it.next()?, it.next()?);
(comment.starts_with("cm-") && it.next().is_none()).then_some((item, comment))
}
/// The arguments that show a note on its comment: its asks (none while it's to restate), its state and each ask's.
pub(crate) fn args(item: &str, comment: &str, asks: &[&str], status: &str, states: &[&str]) -> Vec<String> {
let mut a: Vec<String> = ["show", "--on", item, "--working", comment].map(String::from).to_vec();
a.extend(asks.iter().flat_map(|t| ["--ask".to_string(), t.to_string()]));
a.extend(["--status".to_string(), status.to_string()]);
if !states.is_empty() {
a.extend(["--states".to_string(), states.join(",")]);
}
a
}
/// `raea notes post`: what was shown where, and what wasn't and why; 1 when one couldn't be posted.
pub(crate) fn post(project: &Path, eval: Eval, run: Run) -> (String, i32) {
let mut out = Vec::new();
let mut code = 0;
let mut shown: BTreeMap<String, Vec<String>> = std::fs::read_to_string(shown_at(project)).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default();
let before = shown.clone();
let kept = state::read(project);
for k in read(project, eval) {
let file = k.file.display().to_string();
let n = match k.note {
Ok(n) => n,
Err(e) => {
out.push(format!("{file}: can't be read: {e}"));
code = 1;
continue;
}
};
let Some((item, comment)) = comment_of(&n.from) else {
if n.from.starts_with("app ") {
out.push(format!("{file}: a note on its item as a whole has no comment to show its asks on: say them to the person"));
}
continue;
};
let number = place(project, &project.join(&k.file)).map_or(0, |p| p.1);
let owed = n.flags();
let (standing, each) = state::of_note(&n, number, &kept);
// a restatement that still owes something isn't shown: the comment reads "to restate" until it's whole
let whole = n.state() != "to restate" && owed.is_empty();
let asks: Vec<&str> = if whole { n.asks.iter().map(|a| a.text.as_str()).collect() } else { Vec::new() };
let status = if whole { standing.word() } else { "to restate" };
let states: Vec<&str> = if whole { each.iter().map(Standing::word).collect() } else { Vec::new() };
// each clip the person is to sign, under its ask: (its number, file, render)
let clips: Vec<(usize, String, String)> = if whole {
each.iter().enumerate().filter(|(_, s)| matches!(s, Standing::ToSign(_))).filter_map(|(i, _)| {
let c = kept.get(&state::id(number, i + 1))?.clip.as_ref().filter(|c| !c.stale)?;
Some((i + 1, c.file.display().to_string(), c.render.clone()))
}).collect()
} else {
Vec::new()
};
let mut said: Vec<String> = asks.iter().map(|a| a.to_string()).collect();
said.push(format!("status {status} {}", states.join(",")));
said.extend(clips.iter().map(|(i, _, h)| format!("clip {i} {h}")));
if shown.get(&n.from) == Some(&said) {
out.push(format!("{file}: shown on {comment} of {item} as it stands already ({status})"));
continue;
}
let mut calls = vec![args(item, comment, &asks, status, &states)];
calls.extend(clips.iter().map(|(i, f, h)| ["show", "--on", item, "--working", comment, "--sign", &i.to_string(), "--clip", f, "--render", h].map(String::from).to_vec()));
match calls.iter().try_for_each(|a| run(a).map(|_| ())) {
Ok(()) => {
let what = match (asks.len(), whole) {
(_, false) if owed.is_empty() => "to restate".to_string(),
(_, false) => format!("to restate: its restatement still owes: {}", owed.join("; ")),
(1, true) => format!("its ask, {status}"),
(n, true) => format!("its {n} asks, {status}"),
};
let signs = if clips.is_empty() { String::new() } else { format!(", with {} clip{} to sign", clips.len(), if clips.len() == 1 { "" } else { "s" }) };
out.push(format!("{file}: shown on {comment} of {item}: {what}{signs}"));
shown.insert(n.from.clone(), said);
}
Err(e) => {
out.push(format!("{file}: not posted: {e}"));
code = 1;
}
}
}
if shown != before {
let written = serde_json::to_string_pretty(&shown).map_err(|e| e.to_string()).and_then(|t| std::fs::write(shown_at(project), t + "\n").map_err(|e| e.to_string()));
if let Err(e) = written {
out.push(format!("what was shown isn't kept ({}: {e}): the next post shows these again", shown_at(project).display()));
code = 1;
}
}
if out.is_empty() {
out.push("no notes from the raea app to post: `raea notes ls` lists them".into());
}
(out.join("\n"), code)
}
+191
View File
@@ -0,0 +1,191 @@
//! What each ask has been through (docs/direction.feature DR6), kept in the project's .raea/notes-checks.json by its
//! id (n3.2: note 3's second ask): its check and values as they first failed on the work, the run before that if it
//! passed (refused: it wasn't measuring the ask), its last run, the clip cut for the person to sign and their sign.
//! From these and the note, each ask reads to check, failing, to sign, passing or signed, and the note its worst.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use raea_core_facts::{Ask, Note};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use crate::R;
/// A run of an ask's check: when (UTC), the project's commit ("+" when not all of it was committed), what it found,
/// and what it waited for instead, when it did.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Run {
pub at: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub commit: Option<String>,
pub found: usize,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub waits: Option<String>,
}
/// An ask's check as it first failed: the check, its values, and that run.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Failed {
pub check: String,
#[serde(default, skip_serializing_if = "Map::is_empty")]
pub values: Map<String, Value>,
pub run: Run,
}
/// The clip cut for an ask the person signs: its file, the composition, the render it was cut from (its SHA-256),
/// the frames, and whether the composition changed after that render.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Clip {
pub file: PathBuf,
pub of: String,
pub render: String,
pub frames: [i64; 2],
#[serde(default)]
pub stale: bool,
}
/// The person's sign on a clip: their name (none when the app had no account to name), the render they watched, and
/// when.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Sign {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
pub render: String,
pub at: String,
}
/// What one ask has been through.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Kept {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub failed: Option<Failed>,
/// its check's first run, when it passed: refused, as it wasn't measuring the ask
#[serde(default, skip_serializing_if = "Option::is_none")]
pub refused: Option<Run>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last: Option<Run>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub clip: Option<Clip>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub signed: Option<Sign>,
}
/// Every ask's, by its id.
pub type State = BTreeMap<String, Kept>;
fn path(project: &Path) -> PathBuf {
project.join(".raea/notes-checks.json")
}
pub fn read(project: &Path) -> State {
std::fs::read_to_string(path(project)).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()
}
pub fn write(project: &Path, s: &State) -> R<()> {
let f = path(project);
if let Some(d) = f.parent() {
std::fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?;
}
let t = serde_json::to_string_pretty(s).map_err(|e| e.to_string())?;
std::fs::write(&f, t + "\n").map_err(|e| format!("{}: {e}", f.display()))
}
/// An ask's id: the note's number and the ask's (1 is the first).
pub fn id(note: u32, ask: usize) -> String {
format!("n{note}.{ask}")
}
/// Where an ask stands, the word the app's badge shows, and why when that isn't plain.
#[derive(Debug, Clone, PartialEq)]
pub enum Standing {
ToRestate,
ToCheck(String),
Failing(usize),
ToSign(String),
Passing,
Signed(Option<String>),
}
impl Standing {
pub fn word(&self) -> &'static str {
match self {
Standing::ToRestate => "to restate",
Standing::ToCheck(_) => "to check",
Standing::Failing(_) => "failing",
Standing::ToSign(_) => "to sign",
Standing::Passing => "passing",
Standing::Signed(_) => "signed",
}
}
/// The word, and why or by whom.
pub fn said(&self) -> String {
match self {
Standing::ToCheck(why) | Standing::ToSign(why) => format!("{}: {why}", self.word()),
Standing::Failing(n) => format!("failing ({n} finding{})", if *n == 1 { "" } else { "s" }),
Standing::Signed(Some(name)) => format!("signed by {name}"),
Standing::Signed(None) => "signed (unnamed: the app had no account)".into(),
_ => self.word().into(),
}
}
/// How far it is from settled: the note reads its asks' worst.
fn rank(&self) -> u8 {
match self {
Standing::ToRestate => 5,
Standing::ToCheck(_) => 4,
Standing::Failing(_) => 3,
Standing::ToSign(_) => 2,
Standing::Passing => 1,
Standing::Signed(_) => 0,
}
}
}
/// Whether the check an ask names now is the one that failed first (its check and its values).
pub fn same_check(a: &Ask, f: &Failed) -> bool {
a.check.as_deref() == Some(f.check.as_str()) && a.values.clone().unwrap_or_default() == f.values
}
/// Where an ask stands, from the ask and what it has been through.
pub fn standing(a: &Ask, k: Option<&Kept>) -> Standing {
let sign = a.proof.as_ref().is_some_and(|p| p.sign);
if a.check.is_none() && !sign {
return Standing::ToCheck("no check, and no clip to sign".into());
}
if a.check.is_some() {
let failed = k.and_then(|k| k.failed.as_ref());
match (failed, k.and_then(|k| k.last.as_ref())) {
(Some(f), _) if !same_check(a, f) => return Standing::ToCheck("its check changed since it failed: show the new one failing (raea notes check)".into()),
(Some(_), Some(Run { waits: Some(w), .. })) => return Standing::ToCheck(format!("its check waits for {w}")),
(Some(_), Some(r)) if r.found > 0 => return Standing::Failing(r.found),
(Some(_), _) => {}
(None, _) if k.and_then(|k| k.refused.as_ref()).is_some() => return Standing::ToCheck("its check passed on its first run, so it isn't measuring the ask: write one that fails on the work as it stands".into()),
(None, Some(Run { waits: Some(w), .. })) => return Standing::ToCheck(format!("its check waits for {w}")),
(None, _) => return Standing::ToCheck("its check isn't shown failing on the work yet (raea notes check)".into()),
}
if !sign {
return Standing::Passing;
}
}
let clip = k.and_then(|k| k.clip.as_ref());
match (clip, k.and_then(|k| k.signed.as_ref())) {
// the agent's move until there's a clip of the work as it stands: to check, not the person's to sign
(None, _) => Standing::ToCheck("no clip yet: render, and raea notes check cuts it from the newest render".into()),
(Some(c), _) if c.stale => Standing::ToCheck(format!("{} changed after the render its clip is cut from: render it again", c.of)),
(Some(c), Some(s)) if s.render == c.render => Standing::Signed(s.name.clone()),
(Some(_), Some(s)) => Standing::ToSign(format!("{} signed an older render; its clip is new", s.name.as_deref().unwrap_or("the person"))),
(Some(_), None) => Standing::ToSign("its clip waits on the person (raea notes post shows it)".into()),
}
}
/// Each ask of a note with where it stands, and the note's: to restate, else its asks' worst.
pub fn of_note(n: &Note, number: u32, s: &State) -> (Standing, Vec<Standing>) {
let asks: Vec<Standing> = n.asks.iter().enumerate().map(|(i, a)| standing(a, s.get(&id(number, i + 1)))).collect();
if n.state() == "to restate" {
return (Standing::ToRestate, asks);
}
let worst = asks.iter().max_by_key(|a| a.rank()).cloned().unwrap_or(Standing::ToRestate);
(worst, asks)
}
+289
View File
@@ -0,0 +1,289 @@
//! `raea notes take`: what the person sent from the raea app to this project (the inbox lines it wrote: each edit
//! comment of a send, with its pin, or a note on an item) and what they said in a session (`--said`), each written
//! as a note file with their words verbatim and no asks, all in one new round. A note already taken isn't taken again.
//! What the person sends back on a restated note comes the same way: a correction, written into its note (DR5), and
//! a sign on an ask's clip, kept with what that ask has been through (state.rs, DR6).
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use raea_core_facts::{Pin, note};
use serde_json::Value;
use crate::{R, files, place, quoted, state, values};
/// What a note asks of the agent before anything changes, said where notes are taken and listed.
pub(crate) const RESTATE: &str = "restate each note before changing anything: one ask for each thing it asks for, the medium where its words name one (2D, 3D, flat, extruded, real, modelled, voxel), what it is about, and what it doesn't ask for (`not`), so a change keeps the rest";
/// A note to write: the person's words, where they came from, its pin, and where it was as the app said it.
pub(crate) struct New {
pub words: String,
pub from: String,
pub pin: Option<Pin>,
pub at: Option<String>,
}
/// Where the raea app writes what the person sends (the app's host, inbox.ts).
fn inbox_dir() -> PathBuf {
match std::env::var_os("RAEA_INBOX_DIR") {
Some(dir) => dir.into(),
None => Path::new(&std::env::var_os("HOME").unwrap_or_default()).join(".raea/inbox"),
}
}
/// The app's pin ({kind: "place", x, y, t, part} or {kind: "time", t}) as a note's.
fn pin_of(v: &Value) -> Option<Pin> {
v.is_object().then(|| Pin { t: v["t"].as_f64(), x: v["x"].as_f64(), y: v["y"].as_f64(), part: v["part"].as_str().map(Into::into) })
}
/// The notes in one inbox line sent to `project`: each comment of a send of edits, or a note on an item.
pub(crate) fn of_line(v: &Value, project: &str) -> Vec<New> {
if v["project"].as_str() != Some(project) {
return Vec::new();
}
let item = v["item"].as_str().unwrap_or("");
let said = |v: &Value| v.as_str().map(str::trim).filter(|s| !s.is_empty()).map(String::from);
match v["kind"].as_str() {
// a send's own text is its comments listed again
Some("edits") => v["comments"].as_array().into_iter().flatten().filter_map(|c| {
Some(New { words: said(&c["text"])?, from: format!("app {item} {}", c["id"].as_str()?), pin: pin_of(&c["pin"]), at: said(&c["at"]) })
}).collect(),
Some("note") => said(&v["text"]).map(|words| New { words, from: format!("app {item} {}", v["when"].as_str().unwrap_or("")), pin: pin_of(&v["pin"]), at: None }).into_iter().collect(),
_ => Vec::new(),
}
}
/// A correction the person made in the app to a restated note: the note (by where it came from), the ask (1 is the
/// first; none: the note as a whole), and their line.
pub(crate) struct Correction {
pub from: String,
pub ask: u32,
pub text: String,
}
/// The correction in one inbox line sent to `project`, if it is one.
pub(crate) fn correction_of(v: &Value, project: &str) -> Option<Correction> {
if v["project"].as_str() != Some(project) || v["kind"].as_str() != Some("correction") {
return None;
}
let text = v["text"].as_str().map(str::trim).filter(|t| !t.is_empty())?;
let ask = v["ask"].as_u64().and_then(|n| u32::try_from(n).ok()).unwrap_or(0);
Some(Correction { from: format!("app {} {}", v["item"].as_str()?, v["comment"].as_str()?), ask, text: text.into() })
}
/// Where the list that opens at `open` (its `[`) in `t` closes, past what is quoted in it.
fn close_of(t: &str, open: usize) -> Option<usize> {
let (mut depth, mut quote, mut escaped) = (0, None, false);
for (i, c) in t[open..].char_indices() {
match (quote, c) {
(Some(_), _) if escaped => escaped = false,
(Some(_), '\\') => escaped = true,
(Some(q), c) if c == q => quote = None,
(Some(_), _) => {}
(None, '"' | '\'' | '`') => quote = Some(c),
(None, '[') => depth += 1,
(None, ']') => {
depth -= 1;
if depth == 0 {
return Some(open + i);
}
}
_ => {}
}
}
None
}
/// A note file's text with the person's correction added: their line last in its words, and its ask in `corrected`.
/// None when the file has no words list or asks to add them beside.
pub(crate) fn corrected(t: &str, c: &Correction) -> Option<String> {
let line = if c.ask == 0 { c.text.clone() } else { format!("on ask {}: {}", c.ask, c.text) };
let open = t.find("words: [")? + "words: ".len();
let end = close_of(t, open)?;
let mut out = format!("{}, {}{}", t[..end].trim_end().trim_end_matches(','), serde_json::to_string(&line).ok()?, &t[end..]);
match out.find("corrected: [") {
Some(at) => {
let at = at + "corrected: [".len();
let sep = if out[at..].starts_with(']') { "" } else { ", " };
out.insert_str(at, &format!("{}{sep}", c.ask));
}
None => {
// `asks:` where it starts its line, so a word in a quote is never taken for it
let at = out.match_indices("asks:").map(|(i, _)| i).find(|&i| out[..i].rsplit('\n').next().is_some_and(|l| l.trim().is_empty()))?;
let start = out[..at].rfind('\n').map_or(0, |i| i + 1);
let indent = out[start..at].to_string();
out.insert_str(start, &format!("{indent}corrected: [{}],\n", c.ask));
}
}
Some(out)
}
/// The person's sign on an ask's clip in the app: the note (by where it came from), the ask (1 is the first), the
/// render they watched (its SHA-256), their name (none when the app had no account) and when.
pub(crate) struct Signed {
pub from: String,
pub ask: u32,
pub render: String,
pub name: Option<String>,
pub when: String,
}
/// The sign in one inbox line sent to `project`, if it is one.
pub(crate) fn sign_of(v: &Value, project: &str) -> Option<Signed> {
if v["project"].as_str() != Some(project) || v["kind"].as_str() != Some("sign") {
return None;
}
let ask = v["ask"].as_u64().and_then(|n| u32::try_from(n).ok()).filter(|n| *n > 0)?;
let name = v["name"].as_str().map(str::trim).filter(|n| !n.is_empty()).map(String::from);
Some(Signed { from: format!("app {} {}", v["item"].as_str()?, v["comment"].as_str()?), ask, render: v["render"].as_str()?.into(), name, when: v["when"].as_str().unwrap_or("").into() })
}
/// Each ask's last sign kept with what it has been through (state.rs), once: what was signed, or why it wasn't.
fn sign(project: &Path, kept: &[PathBuf], signs: Vec<Signed>) -> R<Vec<String>> {
// the last sign of each ask: a newer render's sign replaces an older one's
let mut last: BTreeMap<(String, u32), Signed> = BTreeMap::new();
for g in signs {
last.insert((g.from.clone(), g.ask), g);
}
let mut s = state::read(project);
let before = s.clone();
let mut out = Vec::new();
for g in last.into_values() {
let from = format!("from: {}", serde_json::to_string(&g.from).unwrap_or_default());
// the note whose file says it came from this comment
let note = kept.iter().find_map(|f| {
let said = std::fs::read_to_string(f).ok()?;
if said.contains(&from) { Some((f, place(project, f)?)) } else { None }
});
let Some((f, (_, number))) = note else {
out.push(format!("a sign for a note not in notes/ ({}, ask {})", g.from, g.ask));
continue;
};
let k = s.entry(state::id(number, g.ask as usize)).or_default();
let signed = state::Sign { name: g.name.clone(), render: g.render.clone(), at: g.when.clone() };
if k.signed.as_ref() == Some(&signed) {
continue;
}
let now = k.clip.as_ref().is_some_and(|c| c.render == g.render);
k.signed = Some(signed);
let rel = f.strip_prefix(project).unwrap_or(f).display();
let by = g.name.as_deref().unwrap_or("the person (unnamed: the app had no account)");
let short: String = g.render.chars().take(12).collect();
out.push(format!("{rel}: ask {} signed by {by}, on the render {short}…{}", g.ask, if now { "" } else { ", not the one its clip is cut from now: it is to sign again" }));
}
if s != before {
state::write(project, &s)?;
}
Ok(out)
}
/// Each correction applied to its note's file, once: what was done, or why it wasn't.
fn apply(project: &Path, kept: &[PathBuf], corrections: &[Correction]) -> R<Vec<String>> {
let s = |v: &str| serde_json::to_string(v).unwrap_or_default();
let mut out = Vec::new();
for c in corrections {
let line = if c.ask == 0 { c.text.clone() } else { format!("on ask {}: {}", c.ask, c.text) };
let Some(f) = kept.iter().find(|f| std::fs::read_to_string(f).is_ok_and(|t| t.contains(&format!("from: {}", s(&c.from))))) else {
out.push(format!("a correction for a note not in notes/ ({}): {}", c.from, quoted(&c.text, 90)));
continue;
};
let t = std::fs::read_to_string(f).map_err(|e| format!("{}: {e}", f.display()))?;
if t.contains(&s(&line)) {
continue;
}
let rel = f.strip_prefix(project).unwrap_or(f).display().to_string();
match corrected(&t, c) {
Some(new) => {
std::fs::write(f, new).map_err(|e| format!("{}: {e}", f.display()))?;
crate::post::forget(project, &c.from)?;
let which = if c.ask == 0 { "the note".to_string() } else { format!("ask {}", c.ask) };
out.push(format!("{rel}: the person corrected {which}: {}: restate it again", quoted(&c.text, 90)));
}
None => out.push(format!("{rel}: a correction can't be written in (no `words: [` and `asks:` to put it beside): {}", quoted(&c.text, 90))),
}
}
Ok(out)
}
/// A note's file: its words and where they came from, its round, its pin, and no asks.
pub(crate) fn file_text(n: &New, round: u32) -> String {
let s = |v: &str| serde_json::to_string(v).unwrap_or_default();
// what the pin doesn't say is left out, as the type has it (a key with no value isn't written as null)
let pin = n.pin.as_ref().and_then(|p| serde_json::to_value(p).ok()).map(|mut p| {
if let Some(o) = p.as_object_mut() {
o.retain(|_, v| !v.is_null());
}
format!(" pin: {p},\n")
});
let redesign = if note::redesign(&n.words) { " redesign: true,\n" } else { "" };
let words: Vec<String> = n.words.lines().map(s).collect();
format!(
"// A note from the person, as they wrote it (raea notes take). Keep its words; restate it as asks below, one for each\n// thing it asks for, before anything in the work changes.\nimport {{ note }} from \"raea/note\";\n\nexport default note({{\n words: [{}],\n from: {},\n round: {round},\n{pin}{redesign} asks: [],\n}});\n",
words.join(", "),
s(&n.from),
pin = pin.unwrap_or_default()
)
}
pub(crate) fn take(project: &Path, args: &[String]) -> R<String> {
take_from(&inbox_dir(), project, args)
}
/// `take`, reading the inbox files in `dir`.
pub(crate) fn take_from(dir: &Path, project: &Path, args: &[String]) -> R<String> {
let name = project.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let inboxes: Vec<PathBuf> = match values(args, "--inbox").first() {
Some(n) => vec![dir.join(format!("{}.jsonl", n.trim_end_matches(".jsonl")))],
None => {
let mut v: Vec<PathBuf> = std::fs::read_dir(dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "jsonl")).collect();
v.sort();
v
}
};
let (mut new, mut fixes, mut signs): (Vec<New>, Vec<Correction>, Vec<Signed>) = (Vec::new(), Vec::new(), Vec::new());
for f in &inboxes {
let text = std::fs::read_to_string(f).map_err(|e| format!("{}: {e}", f.display()))?;
for v in text.lines().filter_map(|l| serde_json::from_str::<Value>(l).ok()) {
new.extend(of_line(&v, &name));
fixes.extend(correction_of(&v, &name));
signs.extend(sign_of(&v, &name));
}
}
new.extend(values(args, "--said").into_iter().map(str::trim).filter(|w| !w.is_empty()).map(|w| New { words: w.into(), from: "session".into(), pin: None, at: None }));
// a note already in notes/ (by where it came from; one said in a session, by its words too) isn't taken again
let kept = files(project);
let texts: Vec<String> = kept.iter().filter_map(|f| std::fs::read_to_string(f).ok()).collect();
let s = |v: &str| serde_json::to_string(v).unwrap_or_default();
let mut seen: Vec<(String, String)> = Vec::new();
new.retain(|n| {
let had = texts.iter().any(|t| t.contains(&format!("from: {}", s(&n.from))) && (n.from != "session" || n.words.lines().all(|l| t.contains(&s(l)))));
let twice = seen.contains(&(n.from.clone(), n.words.clone()));
seen.push((n.from.clone(), n.words.clone()));
!had && !twice
});
let mut out = Vec::new();
if !new.is_empty() {
let at = kept.iter().filter_map(|f| place(project, f));
let (round, mut last) = at.fold((0, 0), |(r, n), (fr, fnum)| (r.max(fr), n.max(fnum)));
let round = round + 1;
let folder = project.join("notes").join(round.to_string());
std::fs::create_dir_all(&folder).map_err(|e| format!("{}: {e}", folder.display()))?;
for n in &new {
last += 1;
let file = folder.join(format!("n{last}.ts"));
std::fs::write(&file, file_text(n, round)).map_err(|e| format!("{}: {e}", file.display()))?;
let at = n.at.as_deref().map(|a| format!(" (at {a})")).unwrap_or_default();
let redesign = if note::redesign(&n.words) { ", a redesign" } else { "" };
out.push(format!("notes/{round}/n{last}.ts: to restate{redesign}: {}{at}", quoted(&n.words, 90)));
}
out.push(format!("round {round}: {} note{} taken. {RESTATE}", new.len(), if new.len() == 1 { "" } else { "s" }));
}
// corrections last, so one for a note taken just now finds its file
out.extend(apply(project, &files(project), &fixes)?);
out.extend(sign(project, &files(project), signs)?);
if out.is_empty() {
return Ok(format!("no new notes for {name}: what was sent to it from the raea app ({} inbox file{}) or said is in notes/ already (raea notes ls)", inboxes.len(), if inboxes.len() == 1 { "" } else { "s" }));
}
Ok(out.join("\n"))
}
+351
View File
@@ -0,0 +1,351 @@
use std::path::Path;
use raea_core_facts::Finding;
use super::*;
use crate::take::take_from;
/// A note file's object as JSON, for a test without raea's TS host: its keys quoted and a comma before a close
/// dropped (the files take writes are in that form).
fn eval(f: &Path) -> Result<String, String> {
let t = std::fs::read_to_string(f).map_err(|e| e.to_string())?;
let body = t.split_once("note(").ok_or("no note(")?.1.rsplit_once(");").ok_or("no );")?.0;
let line = |l: &str| match l.trim().split_once(':') {
Some((k, v)) if !k.is_empty() && k.chars().all(char::is_alphanumeric) => format!("\"{k}\":{v}"),
_ => l.trim().to_string(),
};
Ok(body.lines().map(line).collect::<String>().replace(",}", "}").replace(",]", "]"))
}
/// A project folder named `shop`, and an inbox folder beside it.
fn project() -> (tempfile::TempDir, PathBuf, PathBuf) {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("shop");
std::fs::create_dir_all(p.join(".raea")).unwrap();
std::fs::write(p.join(".raea/project"), "").unwrap();
let inbox = tmp.path().join("inbox");
std::fs::create_dir_all(&inbox).unwrap();
(tmp, p, inbox)
}
fn args(a: &[&str]) -> Vec<String> {
a.iter().map(|s| s.to_string()).collect()
}
const SENT: &str = r#"{"item":"i-show-1","project":"shop","title":"Spring ad","kind":"edits","text":"1. [0:04.5] the lamp","when":"2026-11-10T10:00:00Z","comments":[{"id":"cm-1","text":"I want 2D text with occlusion, not 3D. Think of a lyric video.","kind":"edit","pin":{"kind":"place","x":0.57,"y":0.67,"t":4.5},"at":"0:04.5 · 57%, 67%"},{"id":"cm-2","text":"the \"jug\" isn't visible","kind":"edit"}]}
{"item":"i-show-9","project":"other","kind":"note","text":"not this project's","when":"2026-11-10T10:01:00Z"}"#;
#[test]
fn what_the_person_sends_or_says_is_taken_once_as_notes_to_restate() {
let (_tmp, p, inbox) = project();
std::fs::write(inbox.join("claude-code-1.jsonl"), SENT).unwrap();
let out = take_from(&inbox, &p, &args(&["--said", "redo the intro from scratch"])).unwrap();
assert!(out.contains("notes/1/n1.ts: to restate: \"I want 2D text with occlusion, not 3D. Think of a lyric video.\" (at 0:04.5 · 57%, 67%)"), "{out}");
assert!(out.contains("notes/1/n3.ts: to restate, a redesign: \"redo the intro from scratch\""), "{out}");
assert!(out.contains("round 1: 3 notes taken."), "{out}");
let notes = read(&p, eval);
let n: Vec<&Note> = notes.iter().map(|k| k.note.as_ref().unwrap()).collect();
assert_eq!(n[0].words, ["I want 2D text with occlusion, not 3D. Think of a lyric video."]);
assert_eq!((n[0].from.as_str(), n[0].round), ("app i-show-1 cm-1", 1));
assert_eq!(n[0].pin.as_ref().map(|p| (p.t, p.part.clone())), Some((Some(4.5), None)));
assert_eq!(n[1].words, ["the \"jug\" isn't visible"], "words kept as written");
assert_eq!((n[2].from.as_str(), n[2].redesign), ("session", Some(true)));
assert!(!std::fs::read_to_string(p.join("notes/1/n1.ts")).unwrap().contains("null"), "a pin's missing keys aren't written");
// taken again: nothing new; a later send is the next round
let again = take_from(&inbox, &p, &args(&["--said", "redo the intro from scratch"])).unwrap();
assert!(again.starts_with("no new notes for shop"), "{again}");
let later = r#"{"item":"i-show-2","project":"shop","kind":"note","text":"hold the end card longer","when":"2026-11-10T11:00:00Z","pin":{"kind":"time","t":28.0}}"#;
std::fs::write(inbox.join("claude-code-1.jsonl"), format!("{SENT}\n{later}")).unwrap();
let out = take_from(&inbox, &p, &[]).unwrap();
assert!(out.starts_with("notes/2/n4.ts: to restate: \"hold the end card longer\""), "{out}");
}
#[test]
fn ls_says_where_each_note_stands_and_what_it_owes() {
let (_tmp, p, inbox) = project();
std::fs::write(inbox.join("a.jsonl"), SENT).unwrap();
take_from(&inbox, &p, &[]).unwrap();
let (out, code) = ls(&p, false, eval);
assert_eq!(code, 0);
assert!(out.contains("notes/1/n1.ts: round 1, to restate: \"I want 2D text"), "{out}");
assert!(out.ends_with(take::RESTATE), "{out}");
assert!(out.contains("2 notes: 2 to restate"), "{out}");
// restated as one ask with no medium: read again, and its 2D said
let f = p.join("notes/1/n1.ts");
let t = std::fs::read_to_string(&f).unwrap().replace("asks: [],", "asks: [{ \"text\": \"the lyric is flat type behind the singer\", \"not\": [] }],");
std::fs::write(&f, t).unwrap();
std::fs::write(p.join("notes/1/n9.ts"), "export default 3;").unwrap();
let (out, code) = ls(&p, false, eval);
assert_eq!(code, 1, "a note that can't be read");
assert!(out.contains("notes/1/n1.ts: round 1, to check: ") && out.contains(" n1.1 the lyric is flat type behind the singer: to check: no check, and no clip to sign"), "{out}");
assert!(out.contains(" ! one ask from 2 sentences: read it again for what else it asks"), "{out}");
assert!(out.contains(" ! its words say 2D and no ask says it, as its medium or in its `not`") && out.contains(" ! its words say 3D and no ask says it"), "{out}");
assert!(out.contains("notes/1/n9.ts: can't be read"), "{out}");
}
#[test]
fn notes_are_found_in_round_and_number_order_and_nothing_else_is_one() {
let (_tmp, p, _) = project();
for f in ["notes/2/n10.ts", "notes/2/n9.ts", "notes/1/n1.ts", "notes/1/check.ts", "notes/x/n2.ts"] {
std::fs::create_dir_all(p.join(f).parent().unwrap()).unwrap();
std::fs::write(p.join(f), "").unwrap();
}
let got: Vec<String> = files(&p).iter().map(|f| f.strip_prefix(&p).unwrap().display().to_string()).collect();
assert_eq!(got, ["notes/1/n1.ts", "notes/2/n9.ts", "notes/2/n10.ts"]);
}
#[test]
fn a_note_is_an_entity_in_the_world() {
let (_tmp, p, inbox) = project();
std::fs::write(inbox.join("a.jsonl"), SENT).unwrap();
take_from(&inbox, &p, &[]).unwrap();
let mut w = Facts::new(0, 1920, 1080, 30.0);
spawn(&mut w, &read(&p, eval));
assert_eq!(w.find(&["Note"]).len(), 2);
}
/// n1 of SENT restated as two asks that owe nothing.
fn restate_n1(p: &Path, asks: &str) {
let f = p.join("notes/1/n1.ts");
let t = std::fs::read_to_string(&f).unwrap();
let at = t.find("asks: [").unwrap();
let end = at + t[at..].find("],\n").unwrap() + 2;
std::fs::write(&f, format!("{}asks: [{asks}],{}", &t[..at], &t[end..])).unwrap();
}
const TWO: &str = r#"{ "text": "the lyric is flat type the singer passes in front of", "medium": "2D", "not": ["3D text"] }, { "text": "the words arrive as a lyric video's do", "medium": "2D", "not": [] }"#;
#[test]
fn a_correction_from_the_app_is_written_into_its_note_once_and_it_is_restated_again() {
let (_tmp, p, inbox) = project();
std::fs::write(inbox.join("a.jsonl"), SENT).unwrap();
take_from(&inbox, &p, &[]).unwrap();
restate_n1(&p, TWO);
assert_eq!(read(&p, eval)[0].note.as_ref().unwrap().state(), "to check");
let fix = |ask: &str, text: &str, comment: &str| format!(r#"{{"kind":"correction","item":"i-show-1","project":"shop","title":"Spring ad","comment":"{comment}",{ask}"text":"{text}"}}"#);
let lines = [SENT.to_string(), fix(r#""ask":2,"#, "no, keep the font as it is", "cm-1"), fix("", "it's about the chorus only", "cm-1"), fix("", "lost", "cm-7")];
std::fs::write(inbox.join("a.jsonl"), lines.join("\n")).unwrap();
let out = take_from(&inbox, &p, &[]).unwrap();
assert!(out.contains("notes/1/n1.ts: the person corrected ask 2: \"no, keep the font as it is\": restate it again"), "{out}");
assert!(out.contains("notes/1/n1.ts: the person corrected the note: \"it's about the chorus only\": restate it again"), "{out}");
assert!(out.contains("a correction for a note not in notes/ (app i-show-1 cm-7): \"lost\""), "{out}");
assert!(!out.contains("no new notes"), "{out}");
let n = read(&p, eval).remove(0).note.unwrap();
assert_eq!(n.words, ["I want 2D text with occlusion, not 3D. Think of a lyric video.", "on ask 2: no, keep the font as it is", "it's about the chorus only"]);
assert_eq!(n.corrected, Some(vec![0, 2]));
assert_eq!(n.state(), "to restate");
assert_eq!(n.asks.len(), 2, "the asks are kept for the agent to restate again");
// taken again: each correction is in already
let again = take_from(&inbox, &p, &[]).unwrap();
assert!(!again.contains("corrected"), "{again}");
assert_eq!(read(&p, eval).remove(0).note.unwrap().words.len(), 3);
}
thread_local! {
static RAN: std::cell::RefCell<Vec<Vec<String>>> = const { std::cell::RefCell::new(Vec::new()) };
}
fn ran(a: &[String]) -> R<String> {
RAN.with(|r| r.borrow_mut().push(a.to_vec()));
Ok("Marked cm-1 working".into())
}
fn refused(_: &[String]) -> R<String> {
Err("the raea app isn't running".into())
}
fn calls() -> Vec<Vec<String>> {
RAN.with(|r| r.borrow().clone())
}
#[test]
fn post_shows_each_note_on_its_comment_as_it_stands_once() {
let (_tmp, p, inbox) = project();
let whole = r#"{"item":"i-show-2","project":"shop","kind":"note","text":"hold the end card longer","when":"2026-11-10T11:00:00Z"}"#;
std::fs::write(inbox.join("a.jsonl"), format!("{SENT}\n{whole}")).unwrap();
take_from(&inbox, &p, &[]).unwrap();
// taken and not restated: each comment's badge reads "to restate"
let (out, code) = post::post(&p, eval, refused);
assert_eq!((code, out.contains("notes/1/n1.ts: not posted: the raea app isn't running")), (1, true), "{out}");
assert!(out.contains("notes/1/n3.ts: a note on its item as a whole has no comment to show its asks on"), "{out}");
let (out, code) = post::post(&p, eval, ran);
assert_eq!(code, 0, "{out}");
assert!(out.contains("notes/1/n1.ts: shown on cm-1 of i-show-1: to restate"), "{out}");
assert_eq!(calls()[0], args(&["show", "--on", "i-show-1", "--working", "cm-1", "--status", "to restate"]));
assert_eq!(calls().len(), 2, "cm-1 and cm-2");
// one ask for two sentences still owes a reading: its asks aren't shown, and it still reads to restate
restate_n1(&p, r#"{ "text": "the lyric is flat type", "medium": "2D", "not": ["3D text"] }"#);
let (out, _) = post::post(&p, eval, ran);
assert!(out.contains("notes/1/n1.ts: shown on cm-1 of i-show-1 as it stands already (to restate)"), "{out}");
assert_eq!(calls().len(), 2);
// whole: its asks, the note to check (no check yet) and each ask's state
restate_n1(&p, TWO);
let (out, _) = post::post(&p, eval, ran);
assert!(out.contains("notes/1/n1.ts: shown on cm-1 of i-show-1: its 2 asks, to check"), "{out}");
let want = args(&["show", "--on", "i-show-1", "--working", "cm-1", "--ask", "the lyric is flat type the singer passes in front of", "--ask", "the words arrive as a lyric video's do", "--status", "to check", "--states", "to check,to check"]);
assert_eq!(calls()[2], want);
let (out, _) = post::post(&p, eval, ran);
assert!(out.contains("notes/1/n1.ts: shown on cm-1 of i-show-1 as it stands already (to check)"), "{out}");
assert_eq!(calls().len(), 3);
// the person corrects ask 1: back to restate; restated again in the same words, it's shown again, as the answer
let fix = r#"{"kind":"correction","item":"i-show-1","project":"shop","title":"Spring ad","comment":"cm-1","ask":1,"text":"yes, that"}"#;
std::fs::write(inbox.join("a.jsonl"), format!("{SENT}\n{whole}\n{fix}")).unwrap();
take_from(&inbox, &p, &[]).unwrap();
let (out, _) = post::post(&p, eval, ran);
assert!(out.contains("notes/1/n1.ts: shown on cm-1 of i-show-1: to restate: its restatement still owes: the person corrected ask 1"), "{out}");
let f = p.join("notes/1/n1.ts");
std::fs::write(&f, std::fs::read_to_string(&f).unwrap().replace(" corrected: [1],\n", "")).unwrap();
post::post(&p, eval, ran);
assert_eq!(calls().last().unwrap(), &want);
}
/// A finding of the ask `id`'s check, as a run gives it.
fn found(id: &str) -> Finding {
Finding::new("faces", raea_core_facts::Level::Error, "desk-3 is turned 180 degrees from facing chair-3", &check::by(id))
}
/// One composition's run that found `fs`.
fn run_of(fs: Vec<Finding>) -> Vec<check::Ran> {
vec![check::Ran { of: "office.tsx".into(), found: fs, waits: vec![], render: None, shots: vec![], fps: 30.0 }]
}
/// A project with n1 restated as two asks that run one check with different values, the second on one composition.
fn two_asks() -> (tempfile::TempDir, PathBuf) {
let (tmp, p, inbox) = project();
std::fs::write(inbox.join("a.jsonl"), SENT).unwrap();
take_from(&inbox, &p, &[]).unwrap();
restate_n1(&p, r#"{ "text": "every desk faces its chair", "medium": "2D", "not": ["3D"], "check": "../../checks/faces.ts", "values": { "what": "desk" } }, { "text": "every chair faces its desk", "medium": "2D", "not": [], "of": "office.tsx", "check": "../../checks/faces.ts", "values": { "what": "chair" } }"#);
(tmp, p)
}
#[test]
fn an_asks_check_must_fail_first_and_one_that_passes_first_is_refused() {
let (_tmp, p) = two_asks();
let notes = read(&p, eval);
let (rules, bad) = check::rules(&p, &notes);
assert!(bad.is_empty());
assert_eq!(rules.iter().map(|r| (r.id.as_str(), r.by.as_str(), r.of.as_deref())).collect::<Vec<_>>(), [("n1.1", "note n1.1", None), ("n1.2", "note n1.2", Some("office.tsx"))]);
assert_eq!(rules[0].check, p.join("notes/1/../../checks/faces.ts").display().to_string(), "a check's path is from the note's folder");
let ask = |s: &state::State, i: usize| state::of_note(notes[0].note.as_ref().unwrap(), 1, s).1[i].clone();
// the first run passes n1.1 (refused) and fails n1.2; each counts only its own findings
let mut s = state::State::new();
let (lines, refused) = check::settle(&p, &notes, &rules, &run_of(vec![found("n1.2"), found("n1.2")]), "20261110-120000", &mut s);
assert!(refused);
assert!(lines[0].contains("n1.1 notes/1/n1.ts: \"every desk faces its chair\": refused: its check passes on the work as it stands"), "{lines:?}");
assert!(lines[1].contains("n1.2 notes/1/n1.ts: \"every chair faces its desk\": fails on the work as it stands (2 findings)"), "{lines:?}");
assert!(matches!(ask(&s, 0), state::Standing::ToCheck(why) if why.contains("passed on its first run")));
assert_eq!(ask(&s, 1), state::Standing::Failing(2));
// n1.1 shown failing later counts; the work changes and both pass
check::settle(&p, &notes, &rules, &run_of(vec![found("n1.1")]), "20261110-120100", &mut s);
assert_eq!((ask(&s, 0), ask(&s, 1)), (state::Standing::Failing(1), state::Standing::Passing));
let (lines, refused) = check::settle(&p, &notes, &rules, &run_of(vec![]), "20261110-120200", &mut s);
assert!(!refused && lines.iter().all(|l| l.ends_with(": passing")), "{lines:?}");
// --only runs one: the other isn't judged on a run it wasn't in
let (lines, _) = check::settle(&p, &notes, &rules[1..], &run_of(vec![found("n1.2")]), "20261110-120300", &mut s);
assert_eq!(lines.len(), 1);
assert_eq!((ask(&s, 0), ask(&s, 1)), (state::Standing::Passing, state::Standing::Failing(1)));
// a check changed after it failed is to be shown failing again; kept as written, ls says each ask's state
let f = p.join("notes/1/n1.ts");
std::fs::write(&f, std::fs::read_to_string(&f).unwrap().replace(r#""what": "desk""#, r#""what": "desk", "within": 90"#)).unwrap();
let notes = read(&p, eval);
assert!(matches!(state::of_note(notes[0].note.as_ref().unwrap(), 1, &s).1[0].clone(), state::Standing::ToCheck(why) if why.contains("changed since it failed")));
state::write(&p, &s).unwrap();
let (out, _) = ls(&p, false, eval);
assert!(out.contains(" n1.2 every chair faces its desk [2D]: failing (1 finding)"), "{out}");
assert!(out.contains("notes/1/n1.ts: round 1, to check: "), "{out}");
}
#[test]
fn a_clip_is_signed_by_the_person_for_its_render_and_reopens_when_its_source_changes() {
let (_tmp, p, inbox) = project();
std::fs::write(inbox.join("a.jsonl"), SENT).unwrap();
take_from(&inbox, &p, &[]).unwrap();
restate_n1(&p, r#"{ "text": "the light turns on the cut", "medium": "2D", "not": ["3D"], "proof": { "shot": "reveal", "sign": true } }, { "text": "the lyric is flat type", "medium": "2D", "not": [] }"#);
let note = || read(&p, eval).remove(0).note.unwrap();
let ask = |s: &state::State| state::of_note(&note(), 1, s).1[0].clone();
let mut s = state::State::new();
assert!(matches!(ask(&s), state::Standing::ToCheck(why) if why.starts_with("no clip yet")), "the agent's move: render and cut it");
let clip = |render: &str, stale: bool| state::Clip { file: p.join(".raea/notes-clips/n1.1.mp4"), of: "edit.tsx".into(), render: render.into(), frames: [30, 150], stale };
s.insert("n1.1".into(), state::Kept { clip: Some(clip("aaa", false)), ..Default::default() });
state::write(&p, &s).unwrap();
assert!(matches!(ask(&s), state::Standing::ToSign(why) if why.contains("waits on the person")));
// posted under its ask, for the person to sign
let (out, _) = post::post(&p, eval, ran);
assert!(out.contains("notes/1/n1.ts: shown on cm-1 of i-show-1: its 2 asks, to check, with 1 clip to sign"), "{out}");
let file = p.join(".raea/notes-clips/n1.1.mp4").display().to_string();
assert_eq!(calls()[1], args(&["show", "--on", "i-show-1", "--working", "cm-1", "--sign", "1", "--clip", &file, "--render", "aaa"]), "after cm-1's asks, before cm-2");
// the person signs it in the app (a sign for a note not taken is said, not dropped); a second take changes nothing
let sign = |render: &str, name: &str| format!(r#"{{"kind":"sign","item":"i-show-1","project":"shop","comment":"cm-1","ask":1,"render":"{render}",{name}"when":"2026-11-10T12:00:00Z"}}"#);
let lost = r#"{"kind":"sign","item":"i-show-7","project":"shop","comment":"cm-1","ask":1,"render":"aaa","when":"x"}"#;
std::fs::write(inbox.join("a.jsonl"), [SENT.to_string(), sign("aaa", r#""name":"Sam","#), lost.to_string()].join("\n")).unwrap();
let out = take_from(&inbox, &p, &[]).unwrap();
assert!(out.contains("notes/1/n1.ts: ask 1 signed by Sam, on the render aaa…"), "{out}");
assert!(out.contains("a sign for a note not in notes/ (app i-show-7 cm-1, ask 1)"), "{out}");
let s = state::read(&p);
assert_eq!(ask(&s), state::Standing::Signed(Some("Sam".into())));
assert!(!take_from(&inbox, &p, &[]).unwrap().contains("signed"));
// its composition changed after the render: to sign again; a new render's clip: the old sign doesn't hold
let mut s = state::read(&p);
s.get_mut("n1.1").unwrap().clip = Some(clip("aaa", true));
assert!(matches!(ask(&s), state::Standing::ToCheck(why) if why.contains("changed after the render")), "the agent's move: render it again");
s.get_mut("n1.1").unwrap().clip = Some(clip("bbb", false));
assert!(matches!(ask(&s), state::Standing::ToSign(why) if why.starts_with("Sam signed an older render")));
state::write(&p, &s).unwrap();
// signed again for the new render, by a person the app had no account for: signed, unnamed
std::fs::write(inbox.join("a.jsonl"), [SENT.to_string(), sign("aaa", r#""name":"Sam","#), sign("bbb", "")].join("\n")).unwrap();
let out = take_from(&inbox, &p, &[]).unwrap();
assert!(out.contains("ask 1 signed by the person (unnamed: the app had no account), on the render bbb…"), "{out}");
assert_eq!(ask(&state::read(&p)), state::Standing::Signed(None));
}
#[test]
fn an_ask_names_its_composition_by_file_or_by_file_and_id() {
assert!(check::is_of("hold.tsx", "hold.tsx#hold"), "a file alone is any composition in it");
assert!(check::is_of("hold.tsx", "hold.tsx"));
assert!(check::is_of("cuts.tsx#b", "cuts.tsx#b"));
assert!(!check::is_of("cuts.tsx#b", "cuts.tsx#a"));
assert!(!check::is_of("cuts.tsx#b", "cuts.tsx"), "an id the run doesn't name");
assert!(!check::is_of("hold.tsx", "scenes/hold.tsx#hold"), "its file from the project, not its name");
}
#[test]
fn no_clip_is_cut_from_a_render_the_composition_changed_after() {
let (_tmp, p, inbox) = project();
std::fs::write(inbox.join("a.jsonl"), SENT).unwrap();
take_from(&inbox, &p, &[]).unwrap();
restate_n1(&p, r#"{ "text": "the light turns on the cut", "medium": "2D", "not": ["3D"], "of": "edit.tsx", "proof": { "shot": "reveal", "sign": true } }, { "text": "the lyric is flat type", "medium": "2D", "not": [] }"#);
let notes = read(&p, eval);
let mut s = state::State::new();
let clip = state::Clip { file: p.join(".raea/notes-clips/n1.1.mp4"), of: "edit.tsx#edit".into(), render: "aaa".into(), frames: [30, 150], stale: false };
s.insert("n1.1".into(), state::Kept { clip: Some(clip), ..Default::default() });
let run = |render: Option<check::Rendered>| vec![check::Ran { of: "edit.tsx#edit".into(), found: vec![], waits: vec![], render, shots: vec![("reveal".into(), 30, None)], fps: 30.0 }];
let stale = check::Rendered { out: p.join("out/edit.mp4"), stale: true, frames: 150 };
let lines = check::clips(&p, &notes, &run(Some(stale)), &mut s);
assert_eq!(lines, ["n1.1 notes/1/n1.ts: its clip waits for a render of edit.tsx#edit as it stands: it changed after its newest render"]);
assert!(s["n1.1"].clip.as_ref().unwrap().stale, "the clip kept from the render before is marked");
assert!(!p.join(".raea/notes-clips/n1.1.mp4").exists(), "nothing is cut from it");
let n = notes[0].note.as_ref().unwrap();
assert!(matches!(state::of_note(n, 1, &s).1[0].clone(), state::Standing::ToCheck(why) if why.contains("render it again")), "the agent's move");
// no render at all: said, and nothing is cut
assert_eq!(check::clips(&p, &notes, &run(None), &mut s), ["n1.1 notes/1/n1.ts: its clip waits for a render of edit.tsx#edit"]);
}
+22
View File
@@ -48,10 +48,32 @@ pub(crate) fn offscreen(mut run: Run, json: Option<String>, flat_out: bool, snap
// (bench/timelines/check.sh compares these with renders)
let seeks: Vec<(i64, String)> = std::env::args().collect::<Vec<_>>().windows(3).filter(|w| w[0] == "--seek").filter_map(|w| Some((w[1].parse().ok()?, w[2].clone()))).collect();
if !seeks.is_empty() {
// --view YAW,PITCH,DISTANCE[,X,Y,Z]: the 3D drawn from that orbit (radians, metres, about X,Y,Z) instead of
// the composition's camera; --pick X,Y (repeatable): what's under that point of each seeked frame (page px),
// the page and its 3D as one picture, a line of JSON each (docs/preview.feature PV1)
let args: Vec<String> = std::env::args().collect();
let nums = |flag: &str| -> Vec<Vec<f64>> { args.windows(2).filter(|w| w[0] == flag).map(|w| w[1].split(',').filter_map(|v| v.trim().parse().ok()).collect()).collect() };
let view = nums("--view").into_iter().find(|v| v.len() == 3 || v.len() == 6);
let picks: Vec<(f64, f64)> = nums("--pick").into_iter().filter(|p| p.len() == 2).map(|p| (p[0], p[1])).collect();
let mut said = Vec::new();
for (f, out) in &seeks {
live.step(*f, &[], None)?;
if let Some(v) = &view {
// the scene's engine opens at the first draw
live.snapshot()?;
let t = if v.len() == 6 { [v[3] as f32, v[4] as f32, v[5] as f32] } else { [0.0; 3] };
if !live.set_view(Some((v[0] as f32, v[1] as f32, v[2] as f32, t))) {
return Err("--view: this composition has no 3D to look around".into());
}
}
live.save_snapshot(std::path::Path::new(out))?;
eprintln!("seek to {f} -> {out}");
for (x, y) in &picks {
said.push(serde_json::json!({"frame": f, "x": x, "y": y, "pick": live.pick(*x, *y)}).to_string());
}
}
if !said.is_empty() {
return Ok(said.join("\n"));
}
return Ok(format!("SEEKED {} frames", seeks.len()));
}
+2
View File
@@ -8,6 +8,8 @@ description = "raea solid info and raea solid view: a solid file run, its parts
[dependencies]
raea-core-solidinfo = { path = "../../core/solidinfo" }
# what solid info finds, as raea's one Finding (docs/direction.feature DR3)
raea-core-facts = { path = "../../core/facts" }
serde_json = "1"
# --set's and the CLI's flags, read as the bundler reads them
raea-runtime-bundle = { path = "../../runtime/bundle" }
+16 -4
View File
@@ -11,6 +11,7 @@
use std::path::{Path, PathBuf};
use raea_core_facts::{Finding, Level, finding};
use raea_runtime_bundle::flag;
use serde_json::{Map, Value, json};
@@ -173,22 +174,33 @@ pub fn cli(args: &[String]) -> Result<String, String> {
}
out["walk"] = json!(walk);
}
let errors = out["errors"].as_u64().unwrap_or(0);
// what it found as raea's one Finding (docs/direction.feature DR3), about the part, or the solid's file
let name = file.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let found = finding::ranked(out["found"].as_array().into_iter().flatten().filter_map(|v| Finding::of_value(v, "raea solid info")).map(|f| if f.about.is_empty() { f.about(&name, None) } else { f }).collect());
let errors = found.iter().any(|f| f.level == Level::Error);
if let Some(o) = out.as_object_mut() {
for k in ["found", "errors", "warnings"] {
o.remove(k);
}
}
out["count"] = json!(finding::count(&found));
out["findings"] = json!(found);
let text = if json_out {
serde_json::to_string_pretty(&out).unwrap_or_default()
} else {
let s = &out["solid"];
let mut t: Vec<String> = out["found"].as_array().into_iter().flatten().filter(|f| !matches!(f["level"].as_str(), Some("ok"))).map(|f| format!("{:<8} {}{}", f["level"].as_str().unwrap_or(""), f["part"].as_str().map(|p| format!("{p}: ")).unwrap_or_default(), f["says"].as_str().unwrap_or(""))).collect();
let mut t: Vec<String> = found.iter().map(Finding::line).collect();
for p in out["parts"].as_array().into_iter().flatten() {
t.push(format!("part {}: {} m³, size {}, {} pieces, genus {}", p["part"].as_str().unwrap_or(""), p["volume"], p["box"]["size"], p["pieces"], p["genus"]));
}
for w in out["walk"].as_array().into_iter().flatten() {
t.push(format!("walk {} = {}: {}{}", w["param"].as_str().unwrap_or(""), w["value"], w["verdict"].as_str().unwrap_or(""), w["says"].as_str().map(|s| format!(" ({s})")).unwrap_or_default()));
}
t.push(format!("solid: {} m³, size {} m, {} pieces, genus {}, {} triangles; {errors} errors, {} warnings", s["volume"], s["box"]["size"], s["pieces"], s["genus"], s["tris"], out["warnings"]));
t.push(format!("solid: {} m³, size {} m, {} pieces, genus {}, {} triangles", s["volume"], s["box"]["size"], s["pieces"], s["genus"], s["tris"]));
t.push(format!("raea solid info: {}", finding::count(&found)));
t.join("\n")
};
if errors > 0 {
if errors {
println!("{text}");
std::process::exit(1);
}
+2 -1
View File
@@ -87,7 +87,8 @@ pub(crate) fn view(file: &Path, set: &Map<String, Value>, info: &Value, out: &Pa
let tsx = file.with_file_name(format!(".{}.view.tsx", file.file_stem().and_then(|s| s.to_str()).unwrap_or("solid")));
std::fs::write(&tsx, scene(file, set, lo, hi)).map_err(|e| format!("{}: {e}", tsx.display()))?;
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let run = std::process::Command::new(exe).arg("render").arg(&tsx).arg("--review").arg(out).current_dir(tsx.parent().unwrap_or(Path::new("."))).output().map_err(|e| e.to_string())?;
// a scene made for this look and deleted after it: nothing for the project's record (DR3)
let run = std::process::Command::new(exe).arg("render").arg(&tsx).arg("--review").arg(out).current_dir(tsx.parent().unwrap_or(Path::new("."))).env("RAEA_RECORD", "off").output().map_err(|e| e.to_string())?;
let said = format!("{}{}", String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr));
if !run.status.success() || !out.join("colour.png").is_file() {
// the scene is left for a look: what failed is in it or in the file
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "raea-app-sound"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "A render's sound alone (`raea render EDIT.tsx -o OUT.wav`, no frames drawn) and a video's sound written beside it from the same pass (`--audio OUT.wav`)"
[dependencies]
raea-runtime-export = { path = "../../runtime/export" }
raea-runtime-bundle = { path = "../../runtime/bundle" }
raea-sys-mix = { path = "../../systems/mix" }
raea-io-media = { path = "../../io/media", default-features = false }
+93
View File
@@ -0,0 +1,93 @@
//! A render's sound on its own (Shane 11-10: "we should add an audio-only render and also be able to render video and
//! audio at the same time"):
//! raea render EDIT.tsx -o OUT.wav the sound alone, mixed and mastered as the video's is, no frame drawn:
//! React stepped through every frame for its sounds (sound_only, which
//! live play also mixes from), so a 2-minute film's sound is minutes
//! sooner than its video
//! raea render EDIT.tsx -o OUT.mp4 --audio A.wav the video, and beside it the very bounce it carries (before AAC),
//! from the same pass: every render path writes RAEA_AUDIO_BOUNCE
use raea_runtime_bundle::{R, flag};
use std::path::{Path, PathBuf};
fn is_wav(p: &Path) -> bool {
p.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("wav"))
}
/// Every render comes here first (raea render, and raea export capcut's parts). The folders its files go in are made
/// (out_folders); then Some(the answer) for a sound render (`-o OUT.wav`), None for every other render, which goes on
/// as before. A video render's `--audio A.wav` is set up here (the render writes it) and also answers None.
pub fn render(args: &[String]) -> Option<R<String>> {
if let Err(e) = out_folders(args) {
return Some(Err(e));
}
let out = PathBuf::from(flag(args, "-o")?);
if is_wav(&out) {
return Some(sound(args, &out));
}
let a = flag(args, "--audio")?;
if !is_wav(Path::new(&a)) {
return Some(Err(format!("--audio {a}: the sound is written as a .wav (OUT.wav)")));
}
let a = match std::path::absolute(&a) {
Ok(a) => a,
Err(e) => return Some(Err(format!("{a}: {e}"))),
};
// read where each render path bounces (raea-runtime-export sound.rs and fed.rs, raea-runtime-encode sound.rs); set
// before the render starts, as cli.rs sets RAEA_ROOT
unsafe { std::env::set_var("RAEA_AUDIO_BOUNCE", a) };
None
}
/// The composition's sound alone: bundled as a render bundles it (its --composition and flags), stepped for its sounds,
/// mastered by its <Mix>, written as 48 kHz WAV, with what it measures.
fn sound(args: &[String], out: &Path) -> R<String> {
let edit = args.get(1).filter(|a| !a.starts_with('-')).ok_or("raea render EDIT.tsx -o OUT.wav")?;
let tsx = PathBuf::from(edit).canonicalize().map_err(|e| format!("{edit}: {e}"))?;
let dir = tsx.parent().ok_or("the edit has no folder")?.to_path_buf();
let js = std::env::temp_dir().join(format!("raea-sound-{}.js", std::process::id()));
raea_runtime_bundle::bundle_composition(&tsx, &js, &raea_runtime_bundle::comp_opts(args)?, None)?;
let t = std::time::Instant::now();
let a = raea_runtime_export::sound_only(&js, &dir);
let _ = std::fs::remove_file(&js);
let a = a?.ok_or_else(|| format!("{edit} makes no sound: no <Audio>, no <Video> with sound and no Tone in any frame"))?;
raea_sys_mix::write_wav(&a, out)?;
Ok(format!(
"{}: {:.1} s of sound, {:.1} LUFS, true peak {:.1} dBTP, in {:.1} s (no frames drawn)",
out.display(),
a.duration(),
raea_io_media::audio::lufs(&a),
raea_io_media::audio::true_peak_db(&a),
t.elapsed().as_secs_f64()
))
}
/// The folders a render's files go in (`-o out/a.mp4`, `--audio out/a.wav`), made before it starts: a project made by
/// hand has no out/, and the render ran to the end and then failed writing with "No such file or directory". `-o DIR`
/// (frames) makes only what's above DIR; the render makes DIR.
pub fn out_folders(args: &[String]) -> R<()> {
for f in ["-o", "--audio"] {
let Some(file) = flag(args, f).map(PathBuf::from) else { continue };
if let Some(d) = file.parent().filter(|d| !d.as_os_str().is_empty()) {
std::fs::create_dir_all(d).map_err(|e| format!("{f} {}: couldn't make {}: {e}", file.display(), d.display()))?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
#[test]
fn a_render_makes_the_folders_its_files_go_in() {
let root = std::env::temp_dir().join(format!("raea-out-folders-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let (video, sound) = (root.join("out/shots/a.mp4"), root.join("bounces/a.wav"));
let args: Vec<String> = ["render", "EDIT.tsx", "-o", video.to_str().unwrap(), "--audio", sound.to_str().unwrap()].map(String::from).to_vec();
super::out_folders(&args).unwrap();
assert!(root.join("out/shots").is_dir() && root.join("bounces").is_dir());
assert!(!video.exists() && !sound.exists(), "the folders only, not the files");
// a bare name (the project's own folder) and no -o at all are left as they are
super::out_folders(&["render", "EDIT.tsx", "-o", "a.png"].map(String::from)).unwrap();
super::out_folders(&["render", "EDIT.tsx"].map(String::from)).unwrap();
std::fs::remove_dir_all(&root).unwrap();
}
}
+148
View File
@@ -0,0 +1,148 @@
//! Grok Bot (xAI's desktop agent, made by Anysphere: /Applications/Grok Bot.app, bundle com.anysphere.sand) as a
//! `raea skills install --agent grokbot` target (docs/skills.feature SK13). Read from its app.asar, 1.1.0 (11-14):
//! Grok Bot keeps nothing on this Mac that raea could write. Its agent runs on a computer of its own in the cloud (its
//! "box"), its skills are held there, and its MCP servers belong to the person's account (Settings → Integrations →
//! Add a custom connector), a server's command running on that computer, not here. It has no hooks, no CLI and no ACP.
//! What does reach this Mac is its Execution on this computer: the Bot runs a command here, through its local daemon.
//! So raea stages its skill in a folder of its own, stamped and with a preface saying where raea runs, and gives the
//! grokbot:// links that finish it in Grok Bot: the Execution setting, and a message to the Bot, filled in but not
//! sent, asking it to make the skill from the staged file ("Ask your Bot to create one", as Grok Bot itself says).
use std::path::{Path, PathBuf};
type R<T> = Result<T, String>;
/// The folder raea stages Grok Bot's copy in: $RAEA_GROKBOT_HOME, else grokbot in raea's own folder in the home.
pub fn home() -> R<PathBuf> {
match std::env::var_os("RAEA_GROKBOT_HOME").filter(|v| !v.is_empty()) {
Some(d) => Ok(PathBuf::from(d)),
None => Ok(crate::agent_mcp::user_home()?.join(".raea").join("grokbot")),
}
}
/// Where the staged skills go, one folder per skill holding SKILL.md, as for every agent.
pub fn skills_dir() -> R<PathBuf> {
Ok(home()?.join("skills"))
}
/// The app, where macOS keeps it (/Applications, or ~/Applications).
pub fn app() -> Option<PathBuf> {
let home = crate::agent_mcp::user_home().ok();
[Some(PathBuf::from("/Applications")), home.map(|h| h.join("Applications"))].into_iter().flatten().map(|d| d.join("Grok Bot.app")).find(|a| a.join("Contents/Info.plist").is_file())
}
/// The largest SKILL.md Grok Bot's Skills → Add new skill → Upload file takes, in bytes (256 KB).
pub const MAX_SKILL: usize = 256_000;
/// After `raea skills install --agent grokbot` has copied raea's skills into `dir` (`said`, what it said doing so): the
/// preface in raea's SKILL.md, and the links that finish it. A linked folder is the person's, left as it is. Grok Bot
/// gets no hooks (it has none) and no MCP server (its command would run on the Bot's own computer, not this Mac).
pub fn stage(dir: &Path, said: String) -> R<String> {
let md = dir.join("raea/SKILL.md");
if !dir.join("raea").is_symlink() && let Ok(text) = std::fs::read_to_string(&md) {
let text = with_preface(&text, dir);
if text.len() >= MAX_SKILL {
return Err(format!("{}: {} KB, more than the 256 KB Grok Bot's Add new skill takes", md.display(), text.len() / 1000));
}
std::fs::write(&md, text).map_err(|e| format!("{}: {e}", md.display()))?;
}
Ok(format!("{said}{}", finish(dir)))
}
/// SKILL.md with the preface after its front matter (or first, when it has none): raea runs on the person's Mac, not on
/// the Bot's computer. A copy that has one keeps only one.
pub fn with_preface(text: &str, dir: &Path) -> String {
if text.contains("> **On Grok Bot.**") {
return text.to_string();
}
let p = format!(
"> **On Grok Bot.** raea runs on the person's Mac, not on your computer. Run every `raea` command there, and read\n> every file this skill links (3d.md, reference/cli.md and the rest) from its copy there, in {}, both\n> with Run a command on your local computer (the person turns on Settings → Computer → Execution on this computer).\n> No raea MCP server or hook is set up for you: after saving a composition run `raea check EDIT.tsx --quick` yourself,\n> and `raea show FILE` puts media in front of the person.\n",
dir.join("raea").display()
);
let Some(rest) = text.strip_prefix("---\n") else { return format!("{p}\n{text}") };
let Some(end) = rest.find("\n---\n") else { return format!("{p}\n{text}") };
let (front, body) = (&rest[..end], rest[end + 5..].trim_start_matches('\n'));
format!("---\n{front}\n---\n\n{p}\n{body}")
}
/// A query value as Grok Bot builds its own links (encodeURIComponent): every byte but A-Z a-z 0-9 - _ . ! ~ * ' ( ).
fn encode(v: &str) -> String {
v.bytes().map(|b| if b.is_ascii_alphanumeric() || b"-_.!~*'()".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }).collect()
}
/// One of Grok Bot's deep links (its route table: grokbot://app/v1/ROUTE?KEY=VALUE).
pub fn link(route: &str, key: &str, value: &str) -> String {
format!("grokbot://app/v1/{route}?{key}={}", encode(value))
}
/// The message to the Bot that makes the skill from the copy staged in `dir`: at most 1000 characters, as its prompt
/// link takes.
fn ask(dir: &Path) -> String {
let md = dir.join("raea/SKILL.md");
format!("Please make a private skill named raea from the file {} on my Mac: read it with Run a command on your local computer and keep its text as it is. raea runs on my Mac, so run every raea command there.", md.display())
}
/// What `raea skills install --agent grokbot` says once the copy is staged: where it is, and the links that finish it.
pub fn finish(dir: &Path) -> String {
let md = dir.join("raea/SKILL.md");
let here = match app() {
Some(a) => format!("Grok Bot is at {}.", a.display()),
None => "Grok Bot isn't installed on this Mac (cursor.com/download/bot); the copy is ready for when it is.".into(),
};
format!(
"{here} It keeps its skills on its own computer and its MCP servers on your account, so the copy waits here: {}. No hooks, and no MCP server: Grok Bot runs a server's command on its computer, where the blender server can't reach this Mac's Blender.\nTo finish, in Grok Bot, signed in:\n 1. turn on Execution on this computer: {}\n 2. send the message this fills in, and the Bot makes the skill from the copy: {}\n or by hand: Skills → Add new skill → Upload file → {}\n`open LINK` opens a link in Grok Bot",
dir.display(),
link("settings", "id", "local-execution"),
link("prompt", "text", &ask(dir)),
md.display()
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_preface_goes_after_the_front_matter_once() {
let d = Path::new("/h/.raea/grokbot/skills");
let md = "---\nname: raea\ndescription: d\nversion: 1\n---\n\n# raea\n";
let out = with_preface(md, d);
assert!(out.starts_with("---\nname: raea\ndescription: d\nversion: 1\n---\n\n> **On Grok Bot.** raea runs on the person's Mac"), "{out}");
assert!(out.contains("in /h/.raea/grokbot/skills/raea, both") && out.ends_with("\n\n# raea\n"), "{out}");
assert_eq!(with_preface(&out, d), out);
assert!(with_preface("# no front matter\n", d).starts_with("> **On Grok Bot.**"));
}
#[test]
fn links_are_built_as_grok_bot_builds_its_own() {
assert_eq!(link("settings", "id", "local-execution"), "grokbot://app/v1/settings?id=local-execution");
assert_eq!(link("prompt", "text", "a b/ü&+=?#'()"), "grokbot://app/v1/prompt?text=a%20b%2F%C3%BC%26%2B%3D%3F%23'()");
// its prompt route takes at most 1000 characters of text in a link of at most 2048, with no format characters
let a = ask(Path::new("/h/a-home-folder-with-a-rather-long-name/.raea/grokbot/skills"));
assert!(a.chars().count() <= 1000 && link("prompt", "text", &a).len() <= 2048, "{a}");
assert!(a.chars().all(|c| !c.is_control() && !('\u{200B}'..='\u{200F}').contains(&c) && !('\u{202A}'..='\u{202E}').contains(&c)));
}
#[test]
fn stage_prefaces_the_copy_once_and_refuses_one_too_big_to_upload() {
let d = std::env::temp_dir().join(format!("raea-grokbot-stage-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(d.join("raea")).unwrap();
std::fs::write(d.join("raea/SKILL.md"), "---\nname: raea\nversion: 1\n---\n\n# raea\n").unwrap();
let out = stage(&d, "copied\n".into()).unwrap();
assert!(out.starts_with("copied\n") && out.contains("grokbot://app/v1/prompt?text="), "{out}");
stage(&d, String::new()).unwrap();
let md = std::fs::read_to_string(d.join("raea/SKILL.md")).unwrap();
assert_eq!(md.matches("> **On Grok Bot.**").count(), 1, "{md}");
std::fs::write(d.join("raea/SKILL.md"), "x".repeat(MAX_SKILL)).unwrap();
assert!(stage(&d, String::new()).unwrap_err().contains("256 KB"));
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn finish_says_where_the_copy_is_and_both_links() {
let f = finish(Path::new("/h/.raea/grokbot/skills"));
assert!(f.contains("the copy waits here: /h/.raea/grokbot/skills."), "{f}");
assert!(f.contains("grokbot://app/v1/settings?id=local-execution") && f.contains("grokbot://app/v1/prompt?text=Please%20make%20a%20private%20skill"), "{f}");
assert!(f.contains("Upload file → /h/.raea/grokbot/skills/raea/SKILL.md"), "{f}");
}
}
+140
View File
@@ -0,0 +1,140 @@
//! The hooks `raea skills install` adds an agent (docs/agents.feature A5d, A5e; docs/skills.feature SK10), the same two
//! for every harness, each written where and how that harness reads hooks: before a shell command, `raea hook AGENT`
//! steers media opened in the Mac's viewer to `raea show`; after a file is saved, it runs the quick check on a
//! composition. An event that already has a `raea hook` entry is left as it is.
use crate::agent_mcp::user_home;
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
type R<T> = Result<T, String>;
/// One hook: the harness's event, the tools it matches, and the seconds it may take.
struct Hook {
event: &'static str,
matcher: &'static str,
secs: u64,
}
/// Each harness's two hooks, by its own event and tool names.
fn hooks(agent: &str) -> R<[Hook; 2]> {
let h = |event, matcher, secs| Hook { event, matcher, secs };
Ok(match agent {
"claude" => [h("PreToolUse", "Bash", 30), h("PostToolUse", "Write|Edit|MultiEdit", 60)],
"codex" => [h("PreToolUse", "^(Bash|shell|shell_command|exec_command)$", 30), h("PostToolUse", "^(apply_patch|Edit|Write)$", 60)],
"gemini" => [h("BeforeTool", "run_shell_command", 30), h("AfterTool", "write_file|replace", 60)],
"kimi" => [h("PreToolUse", "Bash|Shell", 30), h("PostToolUse", "Write|Edit|WriteFile|StrReplaceFile", 60)],
a => return Err(format!("no agent {a:?}: claude, codex, kimi or gemini")),
})
}
/// The folder an environment variable names, else the one given.
fn named_dir(var: &str, or: PathBuf) -> PathBuf {
std::env::var_os(var).filter(|v| !v.is_empty()).map_or(or, PathBuf::from)
}
/// Where the harness keeps its hooks.
fn file(agent: &str) -> R<PathBuf> {
let home = user_home()?;
Ok(match agent {
"claude" => home.join(".claude/settings.json"),
"codex" => named_dir("CODEX_HOME", home.join(".codex")).join("hooks.json"),
"gemini" => home.join(".gemini/settings.json"),
_ => named_dir("KIMI_CODE_HOME", home.join(".kimi-code")).join("config.toml"),
})
}
/// Adds a hook to a JSON file of `{"hooks": {EVENT: [{matcher, hooks: [...]}]}}` (Claude Code, Codex, Gemini CLI)
/// unless the event has a `raea hook` entry; true when it added.
fn add_json(path: &Path, agent: &str, h: &Hook) -> R<bool> {
let at = path.display();
let mut doc: Value = match std::fs::read_to_string(path) {
Ok(t) if !t.trim().is_empty() => serde_json::from_str(&t).map_err(|e| format!("{at}: {e}"))?,
_ => json!({}),
};
let hooks = doc.as_object_mut().ok_or(format!("{at} isn't a JSON object"))?.entry("hooks").or_insert_with(|| json!({}));
let list = hooks.as_object_mut().ok_or(format!("{at}: hooks isn't an object"))?.entry(h.event).or_insert_with(|| json!([]));
let list = list.as_array_mut().ok_or(format!("{at}: hooks.{} isn't a list", h.event))?;
if list.iter().any(|m| m["hooks"].as_array().into_iter().flatten().any(|x| x["command"].as_str().unwrap_or("").starts_with("raea hook"))) {
return Ok(false);
}
// Gemini CLI counts milliseconds and names each hook
let one = if agent == "gemini" { json!({"name": "raea", "type": "command", "command": "raea hook gemini", "timeout": h.secs * 1000}) } else { json!({"type": "command", "command": format!("raea hook {agent}"), "timeout": h.secs}) };
list.push(json!({"matcher": h.matcher, "hooks": [one]}));
write(path, &(serde_json::to_string_pretty(&doc).unwrap_or_default() + "\n"))?;
Ok(true)
}
/// Adds a `[[hooks]]` table to Kimi Code's config.toml (only event, matcher, command and timeout: it refuses other
/// keys) unless one runs `raea hook` on that event; true when it added.
fn add_toml(path: &Path, h: &Hook) -> R<bool> {
let text = std::fs::read_to_string(path).unwrap_or_default();
let ours = text.split("[[hooks]]").skip(1).any(|t| {
let t = t.split("\n[").next().unwrap_or(t);
t.contains("command = \"raea hook") && t.contains(&format!("event = \"{}\"", h.event))
});
if ours {
return Ok(false);
}
let sep = if text.is_empty() || text.ends_with("\n\n") { "" } else if text.ends_with('\n') { "\n" } else { "\n\n" };
write(path, &format!("{text}{sep}[[hooks]]\nevent = \"{}\"\nmatcher = \"{}\"\ncommand = \"raea hook kimi\"\ntimeout = {}\n", h.event, h.matcher, h.secs))?;
Ok(true)
}
/// Writes a config file whole, through a temporary file beside it.
fn write(path: &Path, text: &str) -> R<()> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
}
let tmp = path.with_extension("raea-tmp");
std::fs::write(&tmp, text).map_err(|e| format!("{}: {e}", tmp.display()))?;
std::fs::rename(&tmp, path).map_err(|e| format!("{}: {e}", path.display()))
}
/// Adds raea's hooks for an agent; the line says what happened.
pub fn install(agent: &str) -> R<String> {
let (path, mut added) = (file(agent)?, Vec::new());
for h in hooks(agent)? {
if if agent == "kimi" { add_toml(&path, &h)? } else { add_json(&path, agent, &h)? } {
added.push(h.event);
}
}
let what = if added.is_empty() { "already there".to_string() } else { format!("added ({})", added.join(", ")) };
// Codex runs a new or changed hook only once the person trusts it
let trust = if agent == "codex" && !added.is_empty() { "; trust them in Codex's /hooks" } else { "" };
Ok(format!("{}: hooks `raea hook {agent}` {what}{trust}\n", path.display()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn each_harness_gets_both_hooks_once_and_keeps_its_own() {
let d = std::env::temp_dir().join(format!("raea-agent-hooks-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
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] = hooks("claude").unwrap();
assert!(add_json(&c, "claude", &pre).unwrap() && !add_json(&c, "claude", &pre).unwrap());
assert!(!add_json(&c, "claude", &post).unwrap(), "an older raea's after-save hook stands");
let v: Value = serde_json::from_str(&std::fs::read_to_string(&c).unwrap()).unwrap();
assert_eq!((v["model"].as_str(), v["hooks"]["PostToolUse"].as_array().unwrap().len()), (Some("x"), 2));
assert_eq!(v["hooks"]["PreToolUse"][0]["hooks"][0]["command"], "raea hook claude");
let g = d.join("gemini/settings.json");
let [before, _] = hooks("gemini").unwrap();
assert!(add_json(&g, "gemini", &before).unwrap());
let v: Value = serde_json::from_str(&std::fs::read_to_string(&g).unwrap()).unwrap();
assert_eq!(v["hooks"]["BeforeTool"][0], json!({"matcher": "run_shell_command", "hooks": [{"name": "raea", "type": "command", "command": "raea hook gemini", "timeout": 30000}]}));
let k = d.join("kimi/config.toml");
std::fs::create_dir_all(k.parent().unwrap()).unwrap();
std::fs::write(&k, "default_model = \"k\"\n\n[[hooks]]\nevent = \"PreToolUse\"\nmatcher = \"Bash\"\ncommand = \"mine\"\n").unwrap();
let [pre, post] = hooks("kimi").unwrap();
assert!(add_toml(&k, &pre).unwrap() && !add_toml(&k, &pre).unwrap() && add_toml(&k, &post).unwrap() && !add_toml(&k, &post).unwrap());
let t = std::fs::read_to_string(&k).unwrap();
assert!(t.starts_with("default_model = \"k\"\n\n[[hooks]]\nevent = \"PreToolUse\"\nmatcher = \"Bash\"\ncommand = \"mine\"\n\n[[hooks]]\nevent = \"PreToolUse\"\nmatcher = \"Bash|Shell\"\ncommand = \"raea hook kimi\"\ntimeout = 30\n"), "{t}");
assert_eq!(t.matches("[[hooks]]").count(), 3);
assert!(hooks("cursor").is_err());
let _ = std::fs::remove_dir_all(&d);
}
}
Loaded 100 of 1289 files, more files were not shown because too many files have changed in this diff. Show more