Compare commits

...
249 Commits
Author SHA1 Message Date
shinyobjectz f8fd58d690 The sound guide says what the default mix ducks and how to cut air gaps (its lines reached the skill's copy and never main), and the skill's file list as main generates it 2026-11-30 20:16:57 -08:00
shaneandshinyobjectz bda521b3ce goal judge --by clef (the critic on raea cloud), and the skill's references for 0.1.15 (#284)
* The raea skill's references say make component list WORDS and render --keys (raea-skills #145)

* raea goal judge --by clef: clef-omni judges says rules on the files they name, and is the critic where an agent key is set (a raea cloud box has no Claude sign-in in the agent's shell)

* raea's own files find the packages raea ships: a release's render no longer ends "Cannot find package 'react'" with exit 1, and raea goal check runs outside a build tree (#278)

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-11-30 20:15:26 -08:00
shaneandshinyobjectz 740f3c2cf4 Engine side of the render-cost work: clip decoding, frame keys, NVENC (#282)
* A page reads a clip on from where it stopped: up to 4 readers a file, so a clip shown twice at once isn't sought every frame

Where two elements showed one 4K clip, they shared one decoder and ffmpeg restarted every frame (31 starts in 30
frames). Each file now keeps up to 4 readers, each reading on from its last frame (the one behind within 60 frames,
else a new one, else the least used), and the frame it read last for a second ask. Those frames: 909 to 53 ms on the
Mac, SSIM 1.000000; a 30 s ad of 4K street-interview clips on the farm's GPUs 277 s and $0.106 to 153 s and $0.033.

* render --keys: each frame's key with nothing drawn, and the largest each clip is drawn

raea render EDIT --keys keys.json steps React through every frame and makes the page match it without reading a clip
or drawing: each frame's key (its elements' place, kind, props and text, each video's file and time, its 3D rows;
paths named from the composition's folder), has3d, the piece's sounds, and the largest each clip is drawn (box as
drawn, transforms and punch-in applied). A render farm keeps runs by these keys and reads clips from copies no larger
than they're drawn. On the ad: 6.7 s for 894 frames; a caption word changed 70 frames' keys, a sound 3 dB louder none
(CR32, CR36).

* RAEA_NV=1: NVENC and NVDEC in the ffmpeg backend, each after a one-frame try on the machine

The render farm sets it on a GPU's runs of a piece with 3D in it. h264_nvenc at libx264's CRF number as constant QP
(SSIM 0.9925 to libx264's 0.9924 on the ad) and clips through CUDA; where a try fails, libx264 and ffmpeg's own,
said once. The answer is kept for the machine's later runs (CR34).

* The face track and render --review's sheets are crates of their own (raea-sys-facetrack, raea-runtime-review): raea-runtime-page and raea-runtime-export are under 2000 lines again

* One opener for a video (raea_io_media::open_video) and one step of React to a frame (step_react), where the render-cost work had copied each

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-11-30 19:16:06 -08:00
shaneandshinyobjectz dea4d75c8a The farm draws a video with no 3D without a GPU, keeps its runs by their frames' keys, reads clips at the size they're drawn, and joins every frame (#283)
- A video whose frame 0 has no 3D is drawn on containers with no GPU (cpus, 8 by default; 0 keeps it on GPUs); a run
  that fails there or draws 3D is drawn again on a GPU.
- A run's frame is timed by raea's own clocks over the whole frame, a part's start planned at 5 s at least, 2 parts
  at most a container with no GPU.
- With render --keys, a video's runs are kept under their frames' keys in a store named for the raea, the arguments
  and the job's files; a job draws only the frames no kept run holds, and a sound-only change draws none and joins
  the kept pictures to the new sound. A 30 s ad drawn again unchanged: 46 s and $0.000; one caption word changed:
  148 frames, $0.011.
- A clip much larger than it's drawn is read from a copy at its drawn size (lanczos, CRF 12, sound, frame times and
  face track kept), made on containers with no GPU and kept by hash. The ad as a half-size draft: frames in 30-37 s
  from copies against 48-65 s. A master that needs its clips whole gets no copies.
- A piece with 3D asks its GPU runs for NVENC and NVDEC (RAEA_NV=1; needs raea with engine-render-cost, older raea
  ignores it).
- The join reads only the runs' video tracks and cuts at the piece's length: each run's AAC track moved the joined
  video 21 ms after the sound and -shortest then ended it 2 frames early (892 of 894 frames on every split render).
- deploy/modal/build.py builds a Linux raea from a source folder into the volume; a test farm deployed with
  RAEA_FARM_BUILD=NAME runs it. bench/job.ts times one job, bench/encode.py the encoders.
- An unknown GPU name is a GPU, not a CPU, in the bill; A10G is an A10.

Without --keys (raea 0.1.13 and older) a job runs as before, on GPUs or CPUs by its probe, with nothing kept.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-30 18:36:22 -08:00
shaneandshinyobjectz 2563c183e7 The component library: 609 open-source effects sorted by use, searched and copied by raea make component (#281)
* The component library: 609 open-source effects sorted by use, searched by `raea make component list WORDS` and copied by `add NAME`

sdk/raea/library/components holds 475 pieces from remocn, 79 from the React Video Editor templates and 55 from snapcn,
ported to raea's composition API and sorted by what they're for (text, numbers, transitions, screens, HUDs and more),
not by who made them. catalog.json lists each piece's category, type, what it does, its files, the shared helpers it
needs, its fonts and npm packages and its source; CREDITS.md holds the licences and every file's first line names its
source.

- `raea make component list` ends with the library's categories; `list WORDS` searches by category, category/type or
  words (catalog.ts). `add NAME` copies the piece into components/CATEGORY/NAME/ with its helpers under
  components/_lib/, and installs its npm packages through the engine.
- The native host reads the library beside the binary (share/raea, which tools/release.sh already packs from
  sdk/raea/library), in RAEA_HOME, or in the tree a built raea runs from.
- tools/effects-catalog.sh writes the cut-down catalogue raea cloud's dashboard imports (Libraries › Effects).
- tools/size.sh leaves the library out: it's other people's code, kept as they wrote it but for imports.
- conformance/catalog.test.ts: every listed file exists, imports stay inside what a piece copies, none imports another
  video framework, and search finds by use.

* raea help's line for make component says list WORDS searches the library

* no-void leaves the component library out: its gradient shader's own name is void

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-11-30 18:27:08 -08:00
shaneandshinyobjectz 95b2c01a24 raea goal check reads an export's captions and hears its voice (captions + voice packs; farm reads text) (#280)
* raea goal check reads an export's captions and hears its voice: captions and voice packs, and the farm reads text

Shane 11-30: "running a transcription and ocr pass on the final output ... catch if audio captions pick up something
else that's not supposed to be there or if we cut off words. as well we should be checking audio if it's too quiet
for dialogue". Elfster's cut 1 shipped hand-typed captions that dropped "when they get", "okay, this is" and
"organize your"; Body Shop's reaction cut buried the host 7 dB over its music. No check saw either.

captions (sdk/goal/src/packs/captions.ts): the farm's /v1/scene now reads each line of text (texts, RapidOCR
PP-OCRv4, Apache-2.0, about 0.13 s a 540-wide frame on CPU). A line is a caption when it fits what's said while
it's up with few edits (capitals, a badge's style, held stricter), lasts under 4.5 s, sits in a row with other
captions, in a frame with 3 lines or fewer, and the cut has a track of them (8 showings, 40% of the speech).
Shown-not-said: letters no word near it holds. Said-not-shown: words between captioned words that no caption has,
an error for 3 or more in a row where the captions are phrases; a line at a caption run's edge is a warning.
Calibrated on our 8 Elfster/Body Shop cuts and 4 shipped client refs: the refs' phrase captions pass clean but
one (Body Shop Video6's opening line under its hook card), and ours find what was found by hand.

voice (packs/voice.ts): on the export, the speech's level (80th percentile inside words) over the bed between
words: under 6 dB an error, under 10 a warning; each line against the typical line: 6 dB quieter an error, 4 a
warning. The 4 refs are clean; Elfster 2am (4.5 dB) and Body Shop edible (4.4) fail.

Both are in the cut and floor sets. The Scene type carries texts; media.ts passes them through. The farm needs a
deploy (rapidocr in the image) before captions reads anything; until then it notes the reader has no texts.

* raea goal check times on-screen text against its words: the reading pack

Shane 11-30: "the words on screen relative to duration ... if a wordy CTA or component or scene is meant to be fully
read or if it just adds glossable content or context, and if it's on screen long enough to be read."

From the farm's texts, every line that isn't a caption (nor words shown as they're said) is followed frame to frame;
lines that come up together are one block. A block needs 0.5 s plus 3 words a second: under that a warning, under 60%
of it an error. A block of 25 words or more, small text (under 54 px of 1080x1920) or a phone's screen (a status-bar
clock) is texture: a warning that asks whether it's meant to be read. Frames with more than 6 lines (a shelf of
labels, an app shot whole) and blocks of 3 words or fewer are left out. Every finding gives words, seconds and words
a second.

Calibrated on the 8 Elfster/Body Shop cuts and 4 shipped refs: it finds Elfster cut 2's 15-word hook card up 1 s and
Body Shop's reaction CTA card (11 words, 2 s); the refs give one error (an Elfster app screen up 1 s). In cut and floor.

* raea goal check holds every size the brief asks for at done (sizes-all)

Shane 11-30: "it will show completed but what about doing all the resizes". Dutch finished on its 9:16 masters alone:
the brief's 4:5, 1:1 and 16:9 were never made, because one-size-first was a rule against resizing early and nothing
asked for the other sizes at the end. At done, every ad's newest version (adOf, _v#) must be in every format its
brief names (cut `formats`, the brief's and each cut's), unless a person's answer to the open item about "sizes"
names fewer. The finding says which sizes are missing and the file name each takes. test/sizes.test.ts.

* raea ducks music under the talking by default, and goal check holds the hook and the air between words

Shane 11-30: the StreetTalk cuts' music was "about 4 or 5 decibels too loud ... make sure standards and measurements
correctly mix by default to move audio down in the mix, especially while talking, but a CTA with no audio is fine";
Elfster's Voted cut opened on 1.5 s of a silent whiteboard ("a hook really should have audio and video stimulation");
and "measuring and cutting air gaps safely ... it CANNOT destroy words".

- systems/mix: an edit with no Tone graph gets DEFAULT_GRAPH: footage and voice files on a `talk` bus, effects on the
  master, any other audio file on a `bed` bus ducked DEFAULT_DUCK_DB (-6) under the talking, released where nobody
  talks. The names aren't raea/tone's, so an edit's own buses never change; `bus="master"` opts a sound out. Offline
  bounce and live play pick it the same way (score.rs routes a bus-less sound by default_bus). Test: the music sits
  6 dB down under the talk and comes back after it.
- @raea/video airgaps: airGaps(words) and tighten(words, { levels }): the spans of a take to keep, gaps cut to 0.15 s
  in the hook and 0.25 s after, only between words, 80 ms kept either side, each cut pulled back while the take is
  still loud (a transcript's early word end).
- goal packs hook and airgaps (cut and floor): a first word over 1 s in with a quiet opening is an error (Voted:
  1.5 s, -15 dB); gaps over 0.5 s in the first 3 s are errors, over 0.3 s warnings, over 0.8 s after warnings.
- sound pack: bus-less files classed as the mixer routes them (a music file with any name is music, not a voice
  line), the default duck counted, and music within 10 dB of the voice warns (was 6), as the voice pack does.

* The voice check judges the bed only on enough gaps between words

Body Shop's host-hook cut read "1.5 dB above what's under it" off a single 0.34 s gap between two "Mmm"s, where the
speaker was still humming; the agent's own measure (pauses of 0.8 s and more) read 11.7 dB. A tightly cut take has few
gaps, so the bed is judged only on 3 or more gaps and 1 s of them in all.

* The default mix's graph moves to raea-sys-tone, and its test to its own file, so raea-sys-mix is under 2000 lines

CI's size gate: raea-sys-mix was 2048 lines and offline.rs 530. DEFAULT_GRAPH, DEFAULT_DUCK_DB and default_bus are
the default Tone graph, so they live with the graph format in raea-sys-tone (defaults.rs) and raea-sys-mix re-exports
them; the duck test is duck_test.rs.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-11-30 15:13:18 -08:00
shaneandshinyobjectz c81b4e8c23 The farm shares its GPUs and says when a render waits; it encodes with libx264 (#275)
* The farm gives a job 4 GPUs unless it asks for more, and says when a GPU run hasn't answered

A 1,150-frame cut took all 10 of the workspace's GPUs, each drawing 10-20 s, so every other render queued behind it,
and a queued run printed nothing: StreetTalk's agents read the silence as "stalled before frame 0" (11-30).
RAEA_FARM_JOB_GPUS (4) is a job's default; farm_plan.waited logs every 30 s while a probe, first run or whole job waits.

* The farm encodes a video's runs with libx264 at the quality's CRF, not openh264 at a bitrate

openh264's near-blacks stepped into blocks even at --quality master's 37.7 Mbps: raea check's blotching failed every
Dutch cut rendered on the farm, and its agent re-encoded each one with x264 CRF 14 afterwards (a second generation and
minutes a cut). RAEA_MEDIA=ffmpeg makes raea's encode the ffmpeg CLI's libx264 (master CRF 11); the runs still join
by stream copy, and the first run's x264 header tells raea check the darks were kept.

* The farm's GPU wait gives up on a run that ran out of its own time, as .remote() did

Modal's FunctionTimeoutError is a subclass of its TimeoutError, so waited() caught a run's own timeout as "no answer
yet" and asked again forever, logging "waiting" instead of failing the job. It now goes up as before. Test: a run that
timed out fails the job with no wait lines.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-11-30 07:50:06 -08:00
shaneandshinyobjectz 1430731bf3 The box server keeps a quiet stream open past Cloudflare's 100 s, and ends an agent silent both ways for 45 min (#277)
/v1/shell and /v1/run sent no headers until their command printed: raea goal check --json over Dutch's seven cuts
printed nothing for over 100 s, Cloudflare answered 524, and raea cloud's gate sent its Client sign-off stop back as
"raea goal check couldn't run". Their headers now go at once, then an empty line ({}) every 30 s, which readers skip.

An ACP socket whose caller went away without closing it (an API restart, the Sprite's proxy keeping the box's half
open) kept its agent forever: two Gemini agents sat on raea-3 for 2 h, counted as running, so box.sh latest would wait
on them. An agent that has said nothing and been sent nothing for 45 min (RAEA_CLOUD_IDLE_AGENT_MS; raea cloud ends a
turn quiet 30 min) is now ended with its process group.

Checked locally (a 32 s silent command gets {} at 30 s; an idle echo agent's socket is closed at the limit) and on
raea-3 through its public URL's stack.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-30 07:41:35 -08:00
shane d873402ac5 raea goal is the loop, raea make the asset tools (#269)
One loop, raea goal: every rule in TypeScript, held at edit, render, publish and done (goal check, tasks, judge, seen, gates, next); the brief's contract is goal: (one goal or a list, a workflow inline), and its plan is plan:. raea make is making a finished asset: character, clothes, motion, solid, wear, splat, physics, bake, sounds, component, the kit pipeline and shots. Instruments (check, judge, ask, world, scene faults, light check) stay top-level. With it: the montage pack (MK48-MK51), JavaScriptCore fixes raea goal needs (CommonJS named exports, reserved words too, dynamic import of file URLs, process.exit from a promise, stdin for -), raea-cli-goal and raea-cli-refused split out of raea-cli, and skills at raea-skills 105aede.
2026-11-29 18:43:09 -08:00
shaneandshinyobjectz 14cdac0687 Render memory: halcyon r109 from killed at 24-25 GB to a 7.8 GB peak (RM0-RM10) (#273)
* RM0: each App's meshes and images, CPU and GPU bytes, after every RAEA_MEM_MARKS mark (raea-sys-memtally); docs/render-memory.feature RM0-RM4

* RM1-RM10: halcyon r109's sequence from killed at 24-25 GB to a 7.8 GB peak (footprint 5.5 GB), the look within run-to-run noise

- RM1: materials' maps and Solari's traced meshes on the GPU only (RAEA_KEEP_CPU_ASSETS=1: the control)
- RM2: a sequence's first 3D engine let go before a second opens
- RM5: JS solids deduplicated by expression, their Manifolds in a two-generation cache (192 MB each); solid.free
- RM6: a map whose picture changes by frame is one part and one material, its picture swapped as frames show it
  (raea-sys-material swapped.rs): the pool's 96 water maps were 96 meshes and 186 textures
- RM7: Manifold shapes welded into indexed meshes (4.65 corners a vertex in halcyon; RAEA_NO_WELD=1: the control);
  a held frame settles to the same picture, boiling 0.30% against 0.38%
- the shape text kept out of the store and the Edit (the engine spawns from the program's rows)
- RM8: a BufferMesh of 64 KB or more kept on disk by its content (buffer:@NAME, raea's caches/buffers):
  shape text 274 MB -> 11.8 MB
- RM9: material maps as BC7 with their mips (intel_tex_2), cached by content in raea's caches/maps, any size
  resampled to whole blocks (RAEA_NO_BC=1: the control): GPU images 733 MB -> 282 MB
- RM10: raea-sys-contact's solids as bytes, a count and u16 surface points: 1.27 GB -> 0.37 GB mid-render
- memtally names the biggest GPU images; RAEA_MEM_MARKS prints the program's text by column and shape call
- tools/memprobe: memseq, heapwho/heapseq (malloc stack logging, holders.py), abenv/abseq/steadyab (A/B on one binary)

docs/render-memory.feature has each step's numbers and gates.

* raea-sys-memtally in tools/layers.toml: a system, as the layers gate asks

* Size: render-memory's eight over-limit crates and files allowed once at today's sizes (Shane 11-29, for 0.1.13): the folders hold other lanes' uncommitted GI/RT work, so they're split once that lands

* Fold render-memory's copies into what they copied (the dupes gate, 297/60 back to 293/57): one two-generation cache, raea_core_shape::Generations, for core/shape's meshes and runtime/calls' built Manifolds; swapped maps load their pictures with maps.rs's panel_picture; raea_io_home::write_whole for a file written whole or not at all (the BC7 maps first); spawn_sig(it, swapped) one function, its callers saying which; the store's spawn given its columns. Size allowances taken down to the folded sizes (solid.rs is back under 500)

* Split the five crates render-memory took past 2000 lines, each where it parts cleanly, so the next lane has room (the size and rask gates; the one-time allowance is gone):
- raea-core-tables (core/tables): a row's per-frame tables, from raea-sys-frame (re-exported there as tables)
- raea-runtime-ecs (runtime/ecs): raea/ecs on Bevy's ECS, from raea-runtime-calls (ecs.rs re-exports it)
- raea-sys-toon (systems/toon): toon surfaces and outlines, from raea-sys-material; its shaders keep the embedded path compositions name (raea_sys_material/toon.wesl)
- raea-render-plugins (engine/render/plugins): RaeaPlugins, from raea-render (engine.rs re-exports it as raea_plugins; the imports only it used are gone)
- raea-runtime-kinds (runtime/kinds): the rows of models, panels, decals, plates, fog, fire, splats, mesh sequences and grass, with placement and name_column, from raea-runtime-scene
maps.rs's inline and panel pictures move to maps/pictures.rs (re-exported, 422 lines left)

* Engine::open_in: a live engine (re)opened in its slot, the one there let go first (RM2 in one place, docs/render-memory.feature). raea-runtime-export's five opens go through it, so a fed render stepped again in the page's box keeps its AOVs as its first engine did; aov_on takes the engine in place. raea-runtime-export is back under its planned 2000 (LT1 and LX6 hold the rest)

* Drop the dependencies render-memory's splits left behind (cargo shear, CI's unused-dependencies gate): raea-render's eleven systems crates went with RaeaPlugins to raea-render-plugins, raea-runtime-calls's bevy with raea/ecs to raea-runtime-ecs, raea-sys-material's raea-core-shape with toon to raea-sys-toon. raea-render's cargo-shear ignore goes too: spawn.rs reads a mesh buffer through raea_core_shape::buffer_json now

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-11-29 16:40:57 -08:00
shaneandshinyobjectz 036a2ddb5e raea scene faults: a 3D scene's faults judged as a viewer sees them, motion held to what a body does (#272)
* raea scene faults: a 3D scene's faults judged as a viewer would see them, motion held to what a body does, both learning from verdicts and fixes

The scene judge (raea-sys-notice, docs/notice.feature): each lint finding asked of every camera of the shot (in
frame, facing it, not hidden, how many pixels) and scored by a small logistic model over those features and the
words of the parts' names. It learns from verdicts (--real/--fine) and from fixes (a finding gone while its parts
remain); verdicts all one way teach only words, and a held-out check is part of train. 22 verdicts on 18 findings
from 2 projects: 19 right held out, against 16 for the prior. --seed plants faults to measure it; --ask rings the
likeliest on its frame and asks a vision model, given the scene's own words, only whether it's meant. Renders
judge their own frames at the end (runtime/endchecks faults.rs, RAEA_FAULTS_CHECK=0 skips it).

Motion (raea-sys-motionfaults): knees buckling, feet skating, joints past their limits, jolts, fingers bent or
twisted, bones through what the hand holds, and a hand that hasn't closed on it (grip). Lines set from 107 clean
ACCAD takes; 1,039 of 1,051 planted faults caught. --clip reads a clip, --motion a composition's characters with
their hands tested against the scene's triangles; it caught gambit's ladder thumb (68a505a) before its fix and is
silent after. Fixes and looks become verdicts and examples, and a critic (critic.rs) fitted to them by train says
which findings matter; a verdict on a finding's own key at its size outranks it.

The contact lint's touching test made exact-faster (lint/touching.rs, same findings, 30.6 to 8.5 s on a room),
lint_but_clips for a render's end, and core/zfight keeps a fight's patches for where it shows.

* docs/notice.feature: the judge on six gambit interiors it had never seen

41 verdicts from looks at ringed renders (3 real, 38 fine). The judge as it stood called nearly all of them faults;
refitted with each shop left out and then judged, 34 of 41 right. Floats by size and the hidden-seam clip are what it
still misses; three feature changes tried in a replay of the fit and not kept.

* docs/notice.feature: motion checks on gambit's fp labs, and the shin roll they misread

The fp character's shins read 136-165 degrees past their range (twist near 180, its foot taking the roll back);
rendered, nothing shows. Left unverdicted, since a line on limit:calf at that size would hide real broken knees;
next is reading a joint's roll with its child's.

* raea scene faults --motion: a roll its child takes back is no limit

A solve that rolls a shin half a turn and undoes it at the foot read as the shin 136-165 degrees past its range on
every crouching step of gambit's fp character, though nothing shows. Before the limit check, a roll of 15 degrees or
more about a joint's own bone moves to its child when the two are then less past their ranges together (legs.rs
settled; raea-sys-body limits::over). It moves no joint's place; a roll nothing takes back stays. Tested both ways.
Limit findings on the takedown 34 -> 17, the sneak 21 -> 6, the crowd's walkers unchanged.

* raea scene faults train: the judge held out a whole shot at a time

Besides each finding held out, train now fits without each shot and judges it (labels::shots keeps the shot with
each verdict): how it does on a scene it hasn't seen. On the 63 verdicts from 3 projects and 13 shots: 51 right
(the prior 18), where a replay had put it at 50.

* raea scene faults --motion: a roll moves only where it moves nothing else, and a change of checks is no fix

The roll fix (xos) moved a hand's roll onto one finger: that moves the other fingers, and a finger has no limits to
show it, so 77 of the crowd's wrists vanished, and the fix-to-verdict path kept every finding the change hid as a
real fix. Now a roll moves only when the joint's other children sit on its bone's line (a shin's twist joints), to a
child with limits of its own (tested on a hand); and a fix is read only between runs of the same checks
(motionfaults CHECKS, kept in motion.last). The false rows are removed from the critic's examples. Limit findings:
takedown 34 -> 14, sneak 21 -> 6, crowd unchanged, every hand finding kept; two runs each, 0 fixes.

* Fold scene faults' copies into what they copied (the dupes gate: 307/64 groups back to 293/57): one sigmoid in raea-core-ease (splat, notice, motionfaults), solid() in raea-sys-body's JSON readers (grab, motionfaults), the scene's hand stretches onto motionfaults' stretches() and its seeded Rng, one bounds() for least and most, lint_with(clips) in place of lint_but_clips, raea_runtime_bundle::flags for a repeated flag, held_out() for both held-out passes, a fault that stands in one place, the views and their frame numbers in one pass

* flag is the first of flags (raea-runtime-bundle back to 2000 lines, the size gate): one way to read a flag's values

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-11-29 16:40:52 -08:00
shaneandshinyobjectz e5f4743dee LX7's plan: the clipping check in a crate of its own (raea-sys-clip, systems/clip): raea-sys-contact plus a broad phase would pass 2000 lines (rask check failed scene-faults and render-memory on it), and the clipping check moving off the render's thread is its own job; contact's deepest, Hit and solid cache become its public interface (#274)
Co-authored-by: shinyobjectz <[email protected]>
2026-11-29 16:02:21 -08:00
shaneandshinyobjectz 4aff22e31a raea make motion --seeds N: the best of N takes by the body's faults (#271)
* raea motion: clips capped at 10 s (300 frames), Kimodo's documented limit

Past 10 s a clip drifts and breaks up (Kimodo docs, key_concepts/limitations.md). Measured 11-27: a 12.3 s talk
clip's feet spread 47 -> 69 cm, the shoulders rose 9 cm and the last half second glitched. The error says how to go
longer: 10 s clips chained through --keys holding the last frames of the one before.

* raea motion --seeds N: the best of N takes by the body's faults (foot drift while planted, shoulder rise, hip drop, a hand or forearm into the torso or head), each take's score printed and the kept one's written into the clip; examples/motion runs the verb alone

* Fold score.rs's vector helpers onto glam's Vec3 (the dupes gate: sub and dot matched core/grow's and core/sdf's): a point inside a capsule and a foot's sideways drift, the same arithmetic

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-11-29 15:20:10 -08:00
shaneandshinyobjectz c863adef82 raea motion: clips capped at 10 s (300 frames), Kimodo's documented limit (#270)
Past 10 s a clip drifts and breaks up (Kimodo docs, key_concepts/limitations.md). Measured 11-27: a 12.3 s talk
clip's feet spread 47 -> 69 cm, the shoulders rose 9 cm and the last half second glitched. The error says how to go
longer: 10 s clips chained through --keys holding the last frames of the one before.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-29 13:59:49 -08:00
shaneandshinyobjectz 8627ba7ab4 Paint fixes: canvas drawImage, boxed 3D view culling, grey emoji (#260, #261, #262) (#268)
* Three paint fixes: a canvas draws a loaded Image, a boxed 3D view culls by its box, grey bitmap emoji draw (raea #260, #261, #262)

#260: drawImage of a loaded Image onto a canvas made in a composition drew nothing. The canvas is read back off the
page, where there is no project folder to find staticFile's /media/x in. A loaded Image now carries the file the host
found as currentSrc (sdk/raea frame-globals.ts), which drawImage already prefers, and the canvas host takes a src that
is a file as it stands whatever its roots make of it (systems/canvas media_file).

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

#262: Apple Color Emoji keeps 52 glyphs (💬, 🗨) as grey + alpha PNGs. Vello's glyph run asks png for RGBA with a
transformation that leaves grey as it is, logs "Unsupported `output_color_type`" and skips the glyph. The page's
painter (raea-sys-filters) takes those glyphs out of the run and draws them as images placed as Vello places a
bitmap glyph (emoji.rs); skrifa and png at Vello's versions.

* The export crate stays within its 2000 lines: the still's frame-0 branch in four lines (the size gate failed #268 at 2004)

* The emoji decoder widens a PNG's pixels in one loop: its three one-line closures matched closures elsewhere, and the duplicate gate failed #268 by two exact groups and one near

* A .png with no --frame goes through the stills branch as frame 0: the export crate stays at its 1996 lines (with LX6 and LT1's planned four it is at the 2000 limit, and the tasks gate failed #268)

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-11-29 11:49:23 -08:00
shinyobjectz 456fd1e153 An index job reserves 2 cores and 8 GB
It reserved 4 and 16, and from 11-17 to 11-29 raea-ingest's CPU and memory cost more than its GPU ($7.05 against
$5.97). A 52 s clip measured 1.9 cores busy and 4.9 GB across its processes. A job that takes more is billed for what
it takes. Deployed 11-29 and checked: /healthz on both servers, and the same clip indexed through the deployed job
(10 fragments, 9 posters, 23 s). The search server and the frame API keep their sizes, unmeasured.
2026-11-29 09:55:34 -08:00
shinyobjectz 3afc53d45b A raea render's GPU container reserves 2 cores and 8 GB, and each job says what it used
From 11-17 to 11-29 the farm's CPU and memory came to 65% on top of its GPUs: every GPU container reserved 4 cores
and 16 GiB. A 1080p cut measured 1.3 to 1.4 cores busy and 2.7 GB in its biggest process, so raea's containers now
reserve half (farm_plan.RESERVED); a run that takes more is billed for what it takes, as nothing here sets a limit.
The same cut rendered at the same speed after (262 to 268 ms a frame on a T4) for $0.013 against $0.017. Blender's
containers keep 4 and 16, unmeasured. Each job's last line now says the most cores busy and the biggest process of
its runs, so the next change is made from the jobs' own logs. Deployed 11-29.
2026-11-29 09:34:31 -08:00
shinyobjectz 7d79a24f33 Merge branch 'farm-version' 2026-11-29 09:27:03 -08:00
shaneandshinyobjectz 6af8bfa5bb Cut checks a box can fail on: raea sound check, text placement from the farm's scene read, and full render manifests (#267)
Shane on Dutch (11-29): words faded and cut in two, lines too quiet to hear, effects no one hears, and text laid
over the people and the dog the shot is about.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-authored-by: shinyobjectz <[email protected]>
2026-11-27 10:19:31 -08:00
shinyobjectz f4db12c1d0 CI's size and dupes gates on 0.1.11: the mixer's output device (the stream and following the system's output) in its own crate, raea-sys-mix-device, so raea-sys-mix is under 2000 lines and live.rs under 500; one make::Gate in raea-core-brief for a cut's and a goal's gates (cut-plan and goal-plan had the same struct, and status.rs the same closure twice); the CTA's best line found without a copy of hands-audit's fold 2026-11-26 17:26:59 -08:00
shinyobjectz cd159fe0be promoted-from: the layers gate's files (tools/layers.sh, layers.toml, layers.allow) may differ between an rc and its release, as no build reads them (0.1.11-rc2's one-line layers fix would otherwise force a rebuild) 2026-11-26 16:57:39 -08:00
shinyobjectz 316b612d70 layers: raea-runtime-goal-plan is in the runtime layer (MK28's crate had none, and main's CI gates failed on it from c41ec580 on) 2026-11-26 16:57:08 -08:00
shinyobjectz aa40a2fa86 #82: the ARM64 build (it compiles: raea.exe is AA64 and runs) is packed and checked without drawing (release-check.sh RAEA_CHECK_NO_GPU=1 keeps plugins, guides, song map and bin\'s files; the windows-11-arm runner has only WARP, which segfaults in Bevy as on x64, and lavapipe has no ARM64 build), and it uses the release's compile cache 2026-11-26 14:01:28 -08:00
shinyobjectz 48705982b6 windows-arm.yml runs on v* tags too, beside release.yml, and attaches raea-VERSION-windows-arm64.zip to that release (skills-passed from the tag, as release.yml reads it); an ARM64 failure never holds up the release 2026-11-26 14:01:28 -08:00
shinyobjectz 7580433cd2 windows-arm.yml: metis-sys alone on windows-latest's x64 MSVC too, which release.yml builds with 2026-11-26 14:01:28 -08:00
shinyobjectz 28f3fd814b #82: metis-sys vendored with GKlib's stdint.h/inttypes.h stand-ins only before Visual Studio 2013 (Visual Studio 18's stdint.h types int_fast16_t differently, and the windows-11-arm build failed on every GKlib file); its graphs, manual and programs left out 2026-11-26 14:01:28 -08:00
shinyobjectz 1905dc723c #82: a windows-arm64 zip: RAEA_WIN_ARCH=arm64 has onnxruntime.sh and win-bundle.sh take the ARM64 runtime, VC++ CRT, uv and DXC (FFmpeg stays x64, run emulated), release.sh names and packs raea-VERSION-windows-arm64.zip, and windows-arm.yml packs and checks it on WARP 2026-11-26 14:01:28 -08:00
shinyobjectz c41dd64516 #82: raea built natively for Windows on ARM in CI (windows-arm.yml on windows-11-arm: the release's four binaries, raea --version, a 2D still on WARP); rav1d's assembly off there, where MSVC skips its GNU .S files 2026-11-26 14:01:28 -08:00
shinyobjectz 1fc3a07655 Merge branch 'whats-new-0111' 2026-11-26 14:01:28 -08:00
shinyobjectz 986bd33463 whats-new 0.1.11: goals as make jobs, live sound following the output, tall pictures (#245), Windows on ARM (#82), and in the app typed Ideate on your own agent, one Settings, voice with Studio, Codex on Windows (#244) 2026-11-26 14:01:27 -08:00
shane c41ec580a9 Merge pull request #246 from shinyobjectz/skills-0111
skills: CLI reference for 0.1.11
2026-11-26 11:23:26 -08:00
shane 7e25dcc56e skills: the CLI reference as 0.1.11 prints it (raea-skills 98de983: make judge, make status's goal kind) 2026-11-26 11:23:10 -08:00
shinyobjectz 561e7a569c An image larger than Vello's atlas is decoded at a size that fits it (#245: a 1080x18000 site capture drawn 880 wide was refused; fit to the atlas's side, 16384, not the device's 32768); a Snapdragon's Adreno runs on DX12 on Windows, where Vulkan drew Vello's 2D pages striped (#82) 2026-11-26 11:21:27 -08:00
shinyobjectz 0649788f7f MK25: a rotated CTA, cta.also
Dutch's and The Body Shop's briefs each rotate two host CTAs. The cut lands on any one of them. Each also line is held to the brief's text like any other quote. Test: a rotated Dutch line lands, and a line the brief doesn't have holds the job.
2026-11-26 10:36:58 -08:00
shinyobjectz 1a77da4980 box.sh latest: every box in raea cloud's list onto a release, and box.sh up takes the newest release by default
Shane, 11-26: "make sure that release pipeline automatically updates boxes for raea cloud to the latest". Both live boxes were still on 0.1.9, because box.sh's default was a pinned version. box.sh latest [VERSION] waits on the tag's release.yml run (gh run watch) until the Linux archive is attached, then rebuilds each listed box with raea at that version and sdk/cloud's server from the release's own commit. Each box goes only after its running agents finish, as box.sh up already does. A box that can't be rebuilt is named, and the others still go. RAEA_BOX_DRY=1 prints the plan: on 0.1.10 it named raea-2 and raea-3 onto 22834de9b1. tools/agents/release-go.sh (private) starts it after every publish.
2026-11-26 10:29:22 -08:00
shinyobjectz 1a913e6b06 raea frames check on raea cloud boxes: what a cut's pictures get wrong that a viewer sees at once, measured (11-25, Shane on StreetTalk's cuts: "it cuts out faces all the time and also does split frame shots when they make no sense", "it makes text too small on some things, we should have a text/glyph readability check and measurement").
Faces: the export's frames, two a second, go through the farm's new POST /v1/faces (OpenCV's YuNet, 232 KB on CPU, pinned by hash). A box has no vision backend (raea-perceive isn't in raea's Linux build), so raea frame and framing="face" refuse there. A face of someone in the shot touching the frame's edge or a split screen's seam for a second or more is an error; a split screen showing a face in only one half is a warning. Seams are lone lines where the picture jumps across 70% of the frame, held a second, in its middle 60% (a caption's box is two lines close together and doesn't count).

Text: every text's font size from the render's manifest, scaled to a 1080-wide frame: under 40 px is an error, under 48 px a warning.

offload.ts adds --manifest OUT.render.json to a video render that has none and runs the check after the words pass; an error fails the render. OUT.despite.txt says why a face at the edge is meant and turns its errors to warnings. image/raea.sh routes raea frames.

Checked on StreetTalk's delivered cuts: The Body Shop 5 and 6 and Dutch 2, 3 and 4 fail on faces cut at the edge (1 to 6.5 s each), and Dutch 4 on a face cut by a split's seam; a 28 px disclaimer fails a render on raea-2. test/units.ts covers the rules. Farm deployed; the three files copied onto raea-2.
2026-11-26 10:29:22 -08:00
shinyobjectz 7db0e7e149 raea cloud: a render's output outside the project goes back as .raea-cloud-out-N-NAME at the project's top, not inside a .raea-cloud-out folder. The folder is never sent to the farm, and a still's writer (unlike a video's encoder) doesn't make one, so every PNG made outside the project failed with "no frame was written" (11-25, StreetTalk's storyboards: raea render board.html -o out/board.png). Checked through the farm: an HTML storyboard to PNG, written and moved into place; test/units.ts updated. 2026-11-26 10:29:22 -08:00
shinyobjectz ab63120653 raea words: a dip in a word counts as a crossfade only when it comes back up inside the word (Whisper's spans take in the quiet after a word, so a sentence trailing off was flagged on raea-2's first real take); Whisper's joined words ("for $60") split before comparing; edge words flagged only when the sound is at speech level on the first or last 30 ms. Checked on raea-2 (box updated) and on the finished Dutch cut (passes, one warning), the crossfaded and mid-word cuts (still fail). 2026-11-26 10:29:22 -08:00
shinyobjectz 8938819947 raea words on raea cloud boxes: a take's or an export's words by Whisper large-v3 on the farm (POST /v1/words, the model raea cloud's library index transcribes with, OpenRouter's key in Modal secret raea-farm-words), as TAKE.words.json; raea words check VIDEO --expect LINES.txt holds an export to the lines its cut should say: a word missing or cut short is an error, a word heard differently, speech dipping under a crossfade or a word cut by the first or last frame a warning. A box had no transcriber (raea's is parakeet-mlx, Mac only), so agents cut on guessed frames and shipped words clipped by cuts and faded under crossfades (11-25, Shane: "before exporting the audio requires a transcription pass to be sure it matches"). Every video render (offload.ts) now runs the pass on its output, and fails the render when OUT.lines.txt is beside it and a word is missing or clipped. raea transcribe is the same command. Checked: test/words.ts; on StreetTalk's finished Dutch cut (passes), the same cut joined mid-word (fails: vaccines heard as exam, tests missing) and with a 1.5 s crossfade over speech (fails: five words lost). Farm deployed. 2026-11-26 10:29:22 -08:00
shinyobjectz 79cda1dc8c raea cloud boxes keep an agent's socket from going idle, and stop what a stopped agent left running. Between raea cloud and a box a socket is closed after about two minutes without traffic, and an agent waiting on a long render sends nothing: five of StreetTalk's seven "socket closed" ends on 11-25 came 114-125 s into a silence. The box sends a _raea/keepalive notification every 20 s (raea cloud skips notifications it doesn't know; the agent never sees it). An agent now runs in its own process group, stopped whole when its socket closes or it exits: a killed agent's background renders went on as orphans, 4 GB of them on raea-2. 2026-11-26 10:29:22 -08:00
shinyobjectz f0a266718e raea farm: a render that names its own --manifest renders. The probe ran it with two --manifest and raea wrote its own where the render's went, so frame 0 said no length and the job stopped with exit 1 and no reason (StreetTalk's four cuts, 11-25). The render's --manifest is kept from every GPU run and written from frame 0's at the end; a probe with no length says so. A video's sound run finishes before the reload that brings the GPUs' frames (its open files in the job's folder refused it). Farm deployed. 2026-11-26 10:29:22 -08:00
shinyobjectz c8af179033 raea cloud boxes stop a runaway before it takes the box down: StreetTalk's agent rendered two cuts of 4K interviews on raea-2's CPU and the 8 GB box stopped answering, every agent's socket with it (11-25). A box's processes share one cgroup that can't be split, so there's no kernel cap; server/memguard.ts, like earlyoom, looks at free memory each second and below 700 MB (or 8%) kills the largest process the server's agents started over 1 GB (never an agent or the server), and says so in the box's log and each agent's trace. RAEA_CLOUD_MEMGUARD=0 turns it off. Tested offline and on raea-2 (a real 1.5 GB runaway stopped). 2026-11-26 10:29:22 -08:00
shinyobjectz a0f6a95fe7 raea farm: a video's GPU runs find the footage, and two renders at once don't fail each other. The coordinator linked a job's media from the cache but committed only after rendering, so a still (on the coordinator) found the footage and every GPU run of a video said "No such file" (StreetTalk, 11-25: four full cuts refused). It commits right after linking. The web container serves many requests at once, and a volume reload there refused while another request had a file open (GET out: 500, losing a finished render) or took /farm away from one making a job's folder (POST jobs: 500); requests that touch the volume now share it and a reload waits until none is in it (Gate), and a reload that still won't go answers 503, which the box's jobFiles asks again on. A render that fails on a file under out/ says out/ isn't sent and where its inputs go. Farm deployed. 2026-11-26 10:29:22 -08:00
shinyobjectz afaeaa0a7a raea cloud renders know a project's footage by the file, not its path: a thread started again links the same files into a new folder (StreetTalk's restart hard-linked 1.9 GB of interviews), and keyed by path they were hashed again before its first render. media.ts keys its hash cache by device and inode, with size and time 2026-11-26 10:29:22 -08:00
shinyobjectz 65f2a6ae1e box.sh builds a box on raea 0.1.9 unless RAEA_VERSION says otherwise: its default was still 0.1.6, so a plain rebuild of raea-2 (11-25) took it from 0.1.9 back to 0.1.6 2026-11-26 10:29:22 -08:00
shinyobjectz 00deff035c raea cloud renders send a project's footage once: a project not in raea's LFS (every raea cloud project: its repo is on Cloudflare's Git) put all its media in every render's tar, so one frame of StreetTalk's Dutch edit packed and sent 1.9 GB of interviews, read whole into the box's memory (2-4 GB a render); with three agents rendering at once the 15 GB box ran out and every agent's socket dropped. The farm now keeps media by hash (POST /v1/blobs/have, PUT /v1/blobs/OID, streamed and checked against its hash, farm.py); offload.ts sends each footage or large file once (media.ts farmInputs: hashes kept by path, size and time) and names it in the job's .raea-cloud-media.json with no href, and farm_media links it into the job from the cache instead of copying it. Trial on raea-2: the first frame 144 s (hashing and sending 2 GB once), the next 17 s with nothing sent; it had timed out at 60 s. RAEA_CLOUD_GPU_BLOBS=0 puts the media back in the tar; a farm without the cache does too. Tests: test/farm-blobs.ts, test/farm_media.py. Farm deployed (raea-farm). (farm.py and offload.ts also carry the games lane's kits/ fixes that were already on the box.) 11-25, Shane: "if there's an issue with big files ... some kind of r2 streaming thing, I'm happy to have you own the changes" 2026-11-26 10:29:22 -08:00
shinyobjectz 7611a96e34 raea cloud's box sends each agent's stderr along its socket (_raea/stderr), so the run's trace keeps it instead of only the box's disk; box.sh up won't rebuild a box whose server can't say whether agents are running (11-25, Shane: "make sure for cloud runs we are getting all the session traces and logs ... all recoverable") 2026-11-26 10:29:22 -08:00
shinyobjectz 6fb27ef9e8 raea cloud's boxes are stamped and managed: box.sh up stamps every build (BUILD.json: an id from the packed files, the commit, whether the tree was dirty and which files; the tarball kept in ~/.config/raea-cloud/builds so RAEA_CLOUD_BUILD=ID makes another box from exactly it), waits for a box's running agents to finish before rebuilding it (RAEA_BOX_FORCE=1 to cut them off), and promote/list put a box into raea cloud's list (POST /v1/admin/boxes). The box's health says its build and how many agents run. setup.sh installs raea's skills by raea's own agent names (claude-acp had never matched: no box had them), and each client's socket links them into its own config folders. (box.sh's hunks also carry the games lane's raea-games tarball put, which sat beside them.) 11-25, Shane: "make sure this mix up of boxes and versions are all managed effectively" 2026-11-26 10:29:22 -08:00
shinyobjectz 0c0de9b3d6 raea cloud ingest: a fingerprint's model on the GPU: fingerprint_fit trains a linear head per modality on EmbeddingGemma 2's vectors with torch (good against bad and the workspace's files, k-fold AUC) into the volume raea-fingerprints, fingerprint_score scores a file's segments; POST /v1/fingerprints/fit, GET /v1/fingerprints/jobs/{id}, POST /v1/fingerprints/score 2026-11-26 10:29:22 -08:00
shinyobjectz 84f6c59dd0 raea cloud ingest: index jobs transcribe with Whisper large-v3 on OpenRouter when the raea-ingest secret has OPENROUTER_API_KEY (words.ts RAEA_LIBRARY_WORDS=openrouter), and have the secret 2026-11-26 10:29:22 -08:00
shinyobjectz 96adb3ecfb raea cloud ingest: index jobs on Modal (ingest.py index_job, POST/GET /v1/index-jobs) on an L4 (EmbeddingGemma 2 at fp16 on CUDA 13; build/Dockerfile.gpu), the search-words server on the CPU, gpu_probe to check the GPU; docs/cloud-ingest.feature IG8 now raea's indexer into turbopuffer, Enterprise only (raea cloud is Enterprise only, Shane 11-24), with IG6 and IG9 marked built 2026-11-26 10:29:22 -08:00
shinyobjectz 4e12541984 raea cloud ingest: docs/cloud-ingest.feature IG1-IG13 (a synced folder pictured, understood, embedded and organized; Shane 11-24), and raea-ingest on Modal (sdk/cloud/deploy/modal/ingest.py): POST /v1/frame makes a JPEG frame of a video at an address, for synced files with no picture in their tool (IG4). Deployed on profile raea; secret raea-ingest 2026-11-26 10:29:22 -08:00
shinyobjectz 4cc8f58e0a The Google sign-in's screen is handed out once Chrome's window is up (a fresh profile takes about 20 s on the box's CPU, and the viewer showed black till then), and a display left by an X server that's gone (a service restart leaves their sockets) is reclaimed. setup.sh adds xdotool for the window check 2026-11-26 10:29:22 -08:00
shinyobjectz 1873676251 The sign-in's Chrome shows no warning bar across Google's page (--test-type beside --no-sandbox) 2026-11-26 10:29:22 -08:00
shinyobjectz 374426411e raea cloud's Google sign-in can run in a browser on the box, which the person works from the dashboard: Chrome on a virtual display of its own (google-screen.ts), its profile in the sign-in's folder so the Google session goes with it, served over VNC on WS /v1/google-token/ID/screen. Google's last step lands on Antigravity's listener on the box, so the sign-in finishes with nothing pasted; POST /v1/google-token/ID with no address waits for it ({pending} after 25 s). A box without Chrome falls back to the pasted address. setup.sh installs Chrome, Xvfb and x11vnc 2026-11-26 10:29:22 -08:00
shinyobjectz e435bff43e raea cloud's box runs an agent only when it's named, by the request (?agent=) or the box's RAEA_AGENT: no default from whichever is installed first (it had made antigravity-acp the default on raea-1), so a run is never on a model nobody picked. With neither, the socket is refused and says which agents are installed 2026-11-26 10:29:22 -08:00
shinyobjectz 4b2b39edd3 raea cloud's box: with no agent named, Claude when it's installed (antigravity-acp sorts first and became the default on raea-1's refresh) 2026-11-26 10:29:22 -08:00
shinyobjectz 063ae93f30 raea cloud's box signs agents in to a Google AI subscription: Antigravity's Google sign-in runs on the box, the person pastes back the address Google sent them to, and the token file comes back once (POST /v1/google-token, google-token.ts); an agent socket given it (RAEA_GOOGLE_CREDENTIAL) has it written into its own GEMINI_HOME. With the box's Claude sign-in (claude-token.ts, per-socket keys and homes), live on raea-1 since 11-21 and committed here; antigravity-acp joins the box's default agents 2026-11-26 10:29:22 -08:00
shinyobjectz 2a63d75e1b Live sound follows the system's output: a changed default device (headphones, AirPods, a display) or a broken stream reopens the mixer's stream on the one in use 2026-11-26 10:29:12 -08:00
shinyobjectz 2a005e0e30 MK28-MK29: a goal as a fifth kind of make job, held by its commands and a fresh critic, never the agent's word
make: goal({ goal, rules }) on brief.ts: each rule a command that must exit 0 (run, with a timeout), a file that must exist (a deliverable) or words a fresh critic must find true (says). raea make status runs the commands at every status (the Stop hook's too); raea make judge [--by claude|kimi] asks a read-only critic and keeps its verdict in review/goal.judge.json, which clears a says rule only while it is no older than the work's newest file. Make also gets previews (what a job shows but never delivers: review/ and previews/ by default), and status lists files.deliverables and files.previews. runtime/goal-plan holds the gates (raea-app-make was at its size cap).

Test: goal-plan's six (a command passes or says why, a timeout, a stale and a fresh verdict, file rules left to deliverables, the doctor); end to end on a scratch brief, a curt greeting.txt was refused by the critic and a warm one passed, with both commands passing.
2026-11-26 09:41:28 -08:00
shinyobjectz 04098af5af README: the release note says releases are experimental and the app is unstable (Linux and Windows most), with no version or date to go stale 2026-11-26 09:26:36 -08:00
shinyobjectz 22834de9b1 0.1.10 notes: #215 measured fixed on Windows (WebView2, 160-turn chat at the display's rate with and without the GPU), floor3's held interior under Known (rc3 worse, not a regression), overscan is Mac only 2026-11-26 02:10:57 -08:00
shinyobjectz 300e094b9d skills pin: the files reference as 0.1.10's app finds its local cloud (raea-skills #132) 2026-11-26 00:57:47 -08:00
shinyobjectz 7e214fedbb 0.1.10's release notes; the AppImage packer (#226) promotes as a release tool; the contribution series' own checklist stays in its fork 2026-11-26 00:51:45 -08:00
shane 280437c111 Merge pull request #226 from Sarverott/development
release: package and attach a Linux x86_64 AppImage
2026-11-26 00:49:49 -08:00
shane 11f28ffc52 Merge pull request #228 from Sarverott/development-3
docs: propose a code of conduct and safe reporting guidance
2026-11-26 00:37:26 -08:00
shinyobjectz 107b591555 skills pin: bevy, blender and threejs, three engine skills by others beside raea's (raea-skills #118) 2026-11-25 21:33:29 -08:00
shinyobjectz b7cc2694aa skills pin: the CLI reference names raea scene lod (raea-skills #131) 2026-11-25 21:32:04 -08:00
shinyobjectz 2bd30c5fad CI tests raea-bundle in a cargo call of its own: Rolldown's serde_json arbitrary_precision unified into the other crates' test builds, where raea-core-brief's make dials (an untagged enum holding a number) can't be read; main's CI was red on it from 11-23 2026-11-25 21:27:57 -08:00
shinyobjectz d169848689 raea light check measures light whatever else a scene's render finds: its renders pass --despite all, so a contact sheet's cuts, read as a lurching camera since SG13 (11-21), no longer refuse gambit-street and leave every scene after it unmeasured 2026-11-25 21:24:49 -08:00
shinyobjectz 0d92089f7d Overscan's component lives in raea-sys-compose's passes, the facility framepass already reads PrepassRead from, so framepass doesn't depend on viewbox (viewbox re-exports it) 2026-11-25 21:03:10 -08:00
shinyobjectz 5885f86ff3 skills pin: the Solari guide's overscan and the pitch guide (raea-skills #130) 2026-11-25 20:48:37 -08:00
shinyobjectz e02151cf49 Solari overscan (RT40), off by default: <SolariLighting overscan={0.05}> traces the view a twentieth wider on every side and crops the middle back out, so the frame's border has neighbours and history to gather from (a held wall at the edge: jitter's worst square 16% to 5.6%; the same picture with it off). FramePass's depth() and normal() read where the main pass drew, which also corrects them under a render scale below 1, and a camera with a prepass pass keeps PrepassRead, so a raster video with one isn't refused at its third frame. By the Solari session 2026-11-25 20:47:04 -08:00
shinyobjectz 49c2c96a1a The z-fight check's two copies of a plane's frame folded into flat_in 2026-11-25 20:45:46 -08:00
shinyobjectz 346cacd71a The clipping check doesn't test a part in a solid whose cells are over twice its size: a glTF node spanning a whole building has cells over a metre and flagged every prop near its walls. The z-fight check measures the area two faces really share and says where (N cm2 shared, most at a point). By the Solari session 2026-11-25 20:43:32 -08:00
shinyobjectz ad766214e0 name_rows gathers the names in a loop, so it isn't a near copy of a line in systems/page 2026-11-25 20:41:16 -08:00
shinyobjectz 745c5f98c8 A FramePass's and a Compute's uniforms follow their row after a part is dropped: a video's 3D is made live, a dropped row moved the rows after it up while the frame's row names kept the opening order, so a pass read another row from then on and kept the uniforms it opened with (MALL RAT's exposure, lens and tape stood still; a 520-frame run now matches a held frame, ratio 1.04, was 12). name_rows renames the rows where one is dropped or added. Found and fixed by the Solari session 2026-11-25 20:37:45 -08:00
shinyobjectz d36b0604bc skills pin: raea-skills #129 (6afe7c1), the copies for make: cut
pitch.md's "A client's brief is a contract" section, and reference/sdk.md and files.md with raea/brief's cut. #129 merges when 0.1.10-rc4 is cut.
2026-11-25 20:35:59 -08:00
shinyobjectz 03c2e2ee15 MK25: under raea-app-make's 2000 lines and no new duplicate groups
Kind::name moves into core/brief, so apps/make's kind_name goes. The cut gates' small closures are restated; the duplicate check had matched them with code elsewhere.
2026-11-25 20:33:13 -08:00
shinyobjectz 21859a5a31 MK25: the cut gates as their own crate, runtime/cut-plan, reading shape through io/soft's probe
raea-app-make was at its 2000-line crate limit, so the gates now live beside MK24's lod-plan as raea-runtime-cut-plan. status.rs wraps the gates as it does lod-plan's.

A delivered file's size and length now come from io/soft's probe (ftyp and moov only, through re_mp4), not a third box reader. The tests use raea's 3 s 320x180 clip as the delivered file.

Folded the closures the duplicate check flagged: is_name is shared by cut ids and shot names, and quotes is built in loops.

The pitch guide names the cloud's report files, not `raea words` and `raea frames`, which local raea doesn't have. The SDK reference is regenerated for raea/brief.
2026-11-25 20:28:42 -08:00
shinyobjectz f02348c397 MK25-MK27: a client's brief as rules, make: cut({...}), held by raea make status
11-25, Shane, on StreetTalk's street interview ads: "you need to make the process of ingesting the brief more direct, or else it's just context that gets lost. It needs to be written as a brief typescript rule that is then enforced ... I need raea make to be the standard".

A fourth make kind, cut (core/brief cut.rs, typed into brief.gen.ts, `cut()` in raea/brief). It holds:
- the count, lengths and formats, and each cut (out/cuts/ID_WxH.mp4 per format);
- `say` phrases, `never` phrases and the exact CTA;
- `open` items: the brief's [TO CONFIRM] lines and its contradictions.

Every rule quotes the brief (`from`). apps/make cut.rs holds the job:
- quotes: each `from` is found in media/brief.txt;
- count, and open items: each needs the person's answer;
- per delivered file: shape and length from its own MP4 boxes (mp4.rs, no decoder);
- say, never and CTA from FILE.words.json and the render manifest's text. Compounds are joined ("wish list" = Wishlist), a say phrase's words may sit two apart in order, and the CTA needs 85% of its words in order in the last 8 s;
- the frames check, which must be newer than the file.
The Stop hook holds the agent through `raea make status` as for the other kinds.

Checked on Gemini's real Elfster deliveries against a contract written from the real brief. The gates found:
- "free, fun, and easy" missing from 3 of 4 solos;
- the CTA rewritten in one and absent from another;
- no frames check on any file;
- 4 of 10 cuts delivered.
Each finding was confirmed against the transcripts. cargo test -p raea-core-brief -p raea-app-make: 40 pass, 6 new.
2026-11-25 20:06:32 -08:00
shinyobjectz 64d97bac8f The lane's last house checks: two copies in apps/direction's check folded away, and the contact lint's feet, wall and face helpers live in core/scene parts.rs, so raea-sys-contact keeps room for LX7's plan 2026-11-25 16:30:14 -08:00
shinyobjectz b9d1beaa2f skills pin: the scenes guide with floating (raea-skills #128) 2026-11-25 16:15:52 -08:00
shinyobjectz b1a8d57616 A thing left in the air touching nothing is an error in raea scene lint, unless it is marked floating (typed on Mesh3d and Model, taught in the scenes guide) or its own material glows; the z-fight check tells doubled triangles and undersides resting on one floor from real fights. The lane's house checks: dunce for the project's path, the contact lint under its size (glows and unparked live in core/scene parts.rs), copies folded, the manual's pages for SolariLighting's new props and floating 2026-11-25 16:14:43 -08:00
shinyobjectz 9adc87dcd9 skills pin: the Solari guide as 0.1.10 has it (raea-skills #127) 2026-11-25 15:51:36 -08:00
shinyobjectz 3a1cff770b Solari for 0.1.10: raea light steady tells a held frame's movement by kind (settling, boiling, jitter, flicker; engine/light/src/kinds.rs, steady-kinds.png) and raea check reports the newest hold of a composition lit by Solari; SolariLighting gains knee, late (the denoiser after the sky and forward meshes) and firefly (a sample over N times its 8x8 mean cut back); reflected ReSTIR neighbours and a pixel permute at the frame's border; the eased emitter clamp is opt-in (emissiveClamp.stillHold, thin histories only), so the default is 0.1.9's (lightbench window-still-off-def +0.17 stops, inside RT32's 0.19). MALL RAT: 22 of 24 holds STEADY; t3-1320's border needs overscan (RT40, not built), t2-3686 passes on rerun. Work of the Solari session, committed at its stable point 2026-11-25 15:51:08 -08:00
shinyobjectz 09d87cfa1c SolariLighting paths: N initial paths a pixel, merged by RIS, cut the boiling in held sun-lit interiors (MALL RAT's court 3.0 to 1.6-1.9 on raea light steady, at 1.6-2.2x the frame; unbiased on the kitchen); a steady world cache whose query holds still with the camera, and a baked one, when a composition asks. All off by default: paths 1, sky share 0, spatial radius 30. It doesn't yet pass the 1.5 gate there: the world cache's own noise is what's left (docs/solari-efficiency.md). raea light steady says the light boils (the trade's word; the Solari guide says what it is and what to try first) 2026-11-25 15:51:08 -08:00
shinyobjectz afa6702c05 The refusal's reason is read in one place (raea-app-judge's why_refused, which raea make uses): two copies put raea-app-make over its size limit 2026-11-25 15:41:05 -08:00
shinyobjectz 38f49d623f raea make status and raea judge say why a brief was refused: raea spec prints its refusal on stdout and they read only stderr, so a brief with one wrong value gave an empty reason. MK21-MK24 are done: proven on a job (the render's lod-closer from the brief's level, raea scene lod's table, the make gate open then clear when answered in NOTES.md or replanned, the blockout's boxes named with their level) 2026-11-25 15:37:38 -08:00
shinyobjectz 7ded6a7612 raea voice --over: the manual says what a real room gave (never sure of the echo, so it behaved as without the flag); experimental, not used by raea.app 2026-11-25 15:35:37 -08:00
shinyobjectz 6416e4ec1b The release check reads the song's tempo without jq: a person's PC has none, and the check stopped there on the Windows PC 2026-11-25 15:33:33 -08:00
shinyobjectz 2556f42366 The engine's release check on real machines (tools/release-machines.sh): a candidate's archives checked on the Windows PC's own GPU and the Linux box with a hard pass (RAEA_CHECK_HARD=1: a folder with a space and letters outside ASCII, 3D, an MP4, one render forty times with every exit read, two at once). And raea's own Windows programs signed in the release once the repository names its Azure signing identity (tools/release/win-sign.sh, RAEA_WIN_SIGN=1; off and unsigned until then, #221) 2026-11-25 15:33:33 -08:00
shinyobjectz f2351359c8 The repeated-error helper lives once, in io/trace (once.rs): the mixer and raea voice each carried a copy, which put raea-sys-mix over its size limit and added three duplicate groups 2026-11-25 15:32:18 -08:00
shinyobjectz 7595c81782 A failing audio device's error is said once, then only how often it came back: the mixer's and raea voice's stream error callbacks printed a line for every call, and on Linux an ALSA device answering POLLERR filled app.log with 40 GB of one line in two days (#239) 2026-11-25 15:22:17 -08:00
shinyobjectz 1926af81a5 Opus reads back off the Mac's own reader (#242): the software backend's decoders are made from Symphonia's registry with a libopus decoder added (io/soft/src/opusdec.rs). Symphonia's MP4 reader found an Opus track and had no decoder for it, so the MP4s raea writes itself on Windows and Linux (H.264 + Opus) read as silent: raea media probe listed no audio and raea media share wrote a copy without its sound 2026-11-25 15:20:20 -08:00
shinyobjectz 5d5da4f3d8 Two paint bugs, each held to what Chrome draws (bench/paint-order/check.sh). #241: a stacking context's z-index: -1 children go under its own content, so a box behind a word no longer covers it: the element's text was drawn before every child, the negative ones included. #240: a miter join between tangents within a quarter of a degree of one line is a bevel: after an arc, a long line's tangent passed the join's absolute test, and the miter point, taken from two points a fraction of a pixel apart, landed across the page as a bar from x=0 (a rounded rect's stroke under a negative viewBox origin, at some widths) 2026-11-25 13:22:34 -08:00
shinyobjectz 760d8e53c1 skills pin: the LOD plan's copies (raea-skills #124: scenes.md, the file reference, channel_create taught in collaborate.md) 2026-11-25 13:18:16 -08:00
shinyobjectz 40757526f8 plan::composition reads the words in a loop (no closure copied from elsewhere) 2026-11-25 13:18:08 -08:00
shinyobjectz 50a7e94f5e The planned detail's end check finds the render's composition from the command line (plan::composition), so the export crate carries none of it and stays inside its planned size 2026-11-25 13:18:08 -08:00
shinyobjectz 6735bd940f MK21: planned detail held to the frame: lod 0 (the hero) to 4 (far) on a make object and on parts (Mesh3d, Model, a parent Entity or Group), measured as how much of the frame a part's box spans; a render's end checks, raea scene stage and raea check --quick say lod-closer when a shot shows a part finer than planned (a warning one level finer, an error two or more), raea scene lod lists every part's plan beside what the frames show, and raea make status holds a job at it (MK22-MK24; raea-runtime-lod-plan) 2026-11-25 13:18:08 -08:00
shinyobjectz 505103dacb Two plugin descriptions say raealism, the light's name, where they said raea GI 2026-11-25 08:08:29 -08:00
shinyobjectz 8cbf438488 raea render ends on an error when a pipeline's shader didn't compile: the frame came out without that pass (Solari's light) under "0 errors"; said once a pipeline, as the check "shader" 2026-11-25 07:46:24 -08:00
shinyobjectz 4447ff2425 raea light steady refuses a held run whose shaders didn't compile: a Solari pipeline that fails leaves the frame to what's left, and its light was scored as the path's (11-25, a reserved word in a shader made three runs read alike) 2026-11-25 07:44:07 -08:00
shinyobjectz 53f9cba215 raea check's contrast reads a moving text where it is on its middle frame, not where it ends (#236): a run's box on that frame is its last box moved back by how far its letters travel 2026-11-25 04:52:45 -08:00
shinyobjectz 86f9aa310f raea voice say: Pocket's stock voice (alba) when none is named, as a session's, never the clip in the person's voice folder 2026-11-25 01:37:19 -08:00
shinyobjectz 388285cc7d skills pin: raea-skills 2acd362 (#126, reference/cli.md for 0.1.10) 2026-11-25 00:24:02 -08:00
shinyobjectz 5c6f2fd63b Stale frame roots dropped in a loop (the retain's closure was another crate's shape, the dupes check) 2026-11-25 00:22:11 -08:00
shinyobjectz 7e09ad474a A stale frame root is dropped by a comparison of its own (a closure of raea gen's shape, the dupes check) 2026-11-25 00:15:13 -08:00
shinyobjectz 420e753583 A closed iframe's frame root goes with its JS, its document and its entity: a page that opened and closed artifacts kept each one's engine running, and a stale root swapped its document into the next iframe given the same id 2026-11-25 00:12:05 -08:00
shinyobjectz 9471ceb76b raea-page-host drops stylo, which moved with the page's accessibility; a blank text node is told by its element 2026-11-25 00:12:05 -08:00
shinyobjectz 2ff6676cb1 A page's accessibility in a crate of its own (raea-page-ax), one reading of its elements for both its trees; the window's scheme and rest in raea-page-window 2026-11-25 00:12:05 -08:00
shinyobjectz a1c8492e8f sdk/ui: a field's placeholder and the other writable properties can be set; markup read back has no end tag on an input or a break 2026-11-25 00:12:05 -08:00
shinyobjectz 6b12b58ca5 A held pointer leaves the window on its release, so a press isn't dropped when the mouse is outside 2026-11-25 00:12:05 -08:00
shinyobjectz fb19fa48a6 raea's window is light, dark or the system's; a page's elements can be replaced by outerHTML
window.scheme picks the scheme (the system's until then), prefers-color-scheme and matchMedia follow it.
2026-11-25 00:12:05 -08:00
shinyobjectz f321704e77 A stylesheet added during a press, a hover or a focus no longer crashes the page
stylo's stylesheet invalidation asked a state-only snapshot for the class and id it had, and Servo's panicked.
2026-11-25 00:12:05 -08:00
shinyobjectz efac2ad5e0 A name spaces what's laid out as blocks, and a press from an assistive client scrolls to its element and never lands on what covers it 2026-11-25 00:12:05 -08:00
shinyobjectz 3081ab72c6 The page's dialogs open in raea's window, and macOS lists overlays and takes typed values
sdk/ui had no <dialog> API: showModal threw, so raea cloud's sheets (the rail's +, every flow on sheet.js) never
opened in raea.app. Now open, show, showModal (focusing its autofocus or first control), close (returnValue, close
after as a task), requestClose, and Escape's cancel on the topmost modal one.

The window's tree leaves hidden nodes out: AccessKit's filtered walk (accesskit_consumer 0.38) stops at a hidden node
that follows an empty container, and raea cloud's body has one (an empty layer, then the closed side panel), so
macOS listed nothing after them: the welcome and every sheet were reachable only by hit test. A test reproduces the
walk's stop and fails once AccessKit fixes it. Editable fields declare SetValue (macOS sends setAccessibilityValue
only to a node that has it). The idle gate is as it was: Bevy's low-power mode already wakes for user events.
2026-11-25 00:12:05 -08:00
shinyobjectz 13cc0d7eb5 raea's window publishes the page's accessibility tree to the OS
VoiceOver and macOS accessibility clients read every element of the page through Bevy's winit AccessKit adapter:
the Blitz document walked from its root (markup set as HTML included, which has no wire ids), each node's role, name
and states by raea-sys-a11y's computation, with its box in physical pixels. Bevy's own tree is turned off while a
client listens; the tree is sent at most every 250 ms, on frames that drew. A press from a client (AXPress, Click) is
a pointer down and up at the element's middle, and SetValue types over the field; controls declare Click so macOS
sends it. A window behind others at rest wakes for a client's actions. A text node is never asked for its box (Blitz
panics on it), and white-space-only text is no node.
2026-11-25 00:12:05 -08:00
shinyobjectz fb37428ddf sdk/ui: a root mounted on another element takes its clicks, and a link's press follows its href
A React root mounted at an element other than the host's root (raea.app's welcome and pages over raea cloud's
dashboard) drew and took no press: its container never got React's listeners, as a portal's does. And a link's
default action wasn't there: a press on <a href="#/projects"> dispatched click and moved nowhere, so the dashboard's
rail went to none of its pages with a pointer. Now its fragment becomes location's hash (hashchange follows), another
page of the origin is assigned, and a target or another origin opens a window, unless a listener prevents it.
2026-11-25 00:12:05 -08:00
shinyobjectz 3b24037ceb raea cloud's box on Windows: the shell's own cat, ls and grep are on its PATH 2026-11-25 00:09:02 -08:00
shinyobjectz 13092a5cfc raea cloud's box: its shell on Windows (RAEA_CLOUD_BASH, taskkill), for raea.app's local cloud
/v1/shell ran bash and stopped its process group, and RAEA_AGENT_CMD ran in /bin/sh:
neither is there on Windows, where raea.app runs this server as a person's own local
cloud. shell-os.ts: the bash is RAEA_CLOUD_BASH (the app names the one beside Git),
else bash on PATH; an agent's command line runs in /bin/sh, or that bash on Windows; a
run is stopped with what it started by taskkill /T there, by its process group
elsewhere (and isn't detached on Windows, where that opens a console). Linux and macOS
run exactly as before.
2026-11-25 00:09:02 -08:00
shinyobjectz b491a27771 The meshes folder's error without a closure (the dupes check's near copy) 2026-11-25 00:06:53 -08:00
shinyobjectz 38bd094357 The meshes folder named once where it's made (a closure of the game export's shape, the dupes check) 2026-11-25 00:06:53 -08:00
shinyobjectz 8c868f23c5 raea scene export / blender open: make meshes/ where the first mesh is written (it was emptied and never remade)
export() removed DIR/meshes and recreated only DIR, so every solid in a fresh export failed to write; the atelier
agent worked around it by locking a meshes/.keep with chflags uchg. shape() now makes meshes/ itself, and its test no
longer makes the folder beforehand, which is why it passed. Not yet tested: waits for disk (parked on its branch).
2026-11-25 00:06:53 -08:00
shinyobjectz 8f4f3648c8 The window's clipboard stub without a window isn't the shape of another crate's stub (the dupes check) 2026-11-25 00:06:53 -08:00
shinyobjectz fdf58ffa16 The window's open on Linux and Windows is raea_io_os's open_url itself, and its stub the clipboard's (two functions of one shape, the dupes check) 2026-11-25 00:04:58 -08:00
shinyobjectz 1f17872816 Linux and Windows window: links and Copy reach the system (sign-in opened nothing)
raea's window answered app.open and clipboard.write with AppKit on the Mac and with stubs everywhere
else, which answered true. So in the Linux and Windows apps, signing in (Google, Apple, GitHub's
device page), Continue on raea.io and every other link opened nothing, and Copy (the GitHub code
among them) copied nothing, with no error. Reported from Ubuntu 26.

Off the Mac the window now opens links and uses the clipboard through raea-io-os (opener: xdg-open,
or opener's own copy where the system has none, Windows' shell; arboard), which the page host
already links for paste. app.open and clipboard.write answer an error when the system refuses, on
the Mac too (NSWorkspace openURL's answer), so the page can say so. The off-Mac calls move to
other.rs (native.rs at the 500-line limit). tools/linux-check.sh also checks raea-page-window
--features window, the window the Linux app ships.
2026-11-25 00:04:58 -08:00
shinyobjectz ea96626433 The export crate back at its 2000 lines: the note on a missing sound file beside its line 2026-11-25 00:04:58 -08:00
shinyobjectz f95b9072e7 raea-runtime-sound exports there(), which the render calls: the lane did not compile without it 2026-11-25 00:02:04 -08:00
shinyobjectz 28cc2eb72b staticFile from compositions/ finds the project's assets/: an edit in one of the layout's folders (compositions/, components/, artifacts/) or under a .raea/project had only its own folder searched, so a picture failed as missing and an <Audio> was dropped without a word and the render refused as silent ("the edit has <Audio> but no sound reached the render", "makes no sound"; reported three times on 0.1.8 and 0.1.9 as a Windows bug, the same on the Mac). A sound file that isn't there is now named, once 2026-11-25 00:02:04 -08:00
shinyobjectzandSarverott 8152c9cfb7 Issue forms for a bug and a feature request, and a pull request template: what was run, what happened, what was expected (from #230 and #232, shortened)
Co-authored-by: Sarverott <[email protected]>
2026-11-25 00:00:58 -08:00
shinyobjectz cefb0e36a8 docs/components.md: an item says which wgpu backends its fixture was drawn on 2026-11-24 23:57:12 -08:00
shinyobjectz d55a74c472 Components first: raea guide components, and the registry design
sdk/guides/craft/components.md (raea guide components): the component-first order of work, what a
raea component is (frame-pure, JSON props, its name on what it draws) and the contracts it keeps for
time, space, look and sound, who owns what in a composition, where each kind gets made (TSX, solids,
sdf/grow, a generator, Blender through a saved script, Godot, Rust rows) and why Godot and Blender are
workshops rather than runtimes, materials and shaders as components, a fixture and checks per kind,
shadcn's components on screens and panels, and promotion from a project to shared/ to a registry.
tools/skills.sh copies it to the skill's root; raea guide lists it; the router, scenes, godot,
materials and parts guides link it.

docs/components.md: raea's registry as shadcn's format (every item a valid registry-item.json, raea's
kinds and assets, contracts, fixture, checks, stills and engine range in meta.raea), components.json
namespaces, the theme and story bridges, and the build order CP1-CP10.
2026-11-24 23:57:12 -08:00
shinyobjectz 2c3bcfa0eb raea light steady --run M: the frame cold against the same frame after M frames played up to it (a cache gaining or losing energy over minutes), the render's output kept in render.log, and a failure names the three things on Solari that build light over frames, not the world cache alone 2026-11-24 23:57:12 -08:00
shinyobjectz ba65d342a5 raea light steady's picture is drawn at the frame's size, so it lays over the frame 2026-11-24 23:53:45 -08:00
shinyobjectz d0d283ecaf skills pin: raea-skills d50dd83 (#119 components and raea fix, #122 projects by client, #123 denoisers, #125 raea media share and the 0.1.10 references) 2026-11-24 23:50:47 -08:00
shinyobjectz 487e62c97b raea light check holds each scene's first still on the traced paths (solari, gi), reports it under steady and fails when the light moved; steady's hold, report and line as functions the check calls 2026-11-24 23:50:46 -08:00
shinyobjectz a22b940a97 raea light steady also fails a light whose level drifts over the held frames (a world cache gaining or losing energy the longer it runs), raea light check renders despite a set's clips (found uncommitted in the shared tree, 11-24, FLOOR3's check), and the mix's slope written without a copied closure 2026-11-24 23:46:55 -08:00
shinyobjectz 12f8521003 raea light steady: a frame held (raea render --hold FRAME:FRAMES) and whether its light holds still. Blotches tens of pixels wide that drift over lit floors and reflections, Solari's world cache lit by too few rays, are told from grain by size, and a run over --max fails with a picture of where 2026-11-24 23:46:55 -08:00
shinyobjectz 95d8236e71 A material or a shape whose props say the same thing isn't rebuilt: memo compares their values, so an array or a colour written inline no longer reads as a change every frame, and usePlace3d keeps its matrix while its numbers are the same (3000 parts: 103 to 78 ms a frame, the same pixels; #160) 2026-11-24 23:46:55 -08:00
shinyobjectz 675aa18daf raea-runtime-pid: the process check out of raea-runtime-bundle into a crate of its own (the bundle crate was at its 2000 lines), the manifest reads GIVEN where it called given(), and two lines the dupes check counted as copies written their own way 2026-11-24 23:46:55 -08:00
shinyobjectz b034e31a61 A song's bars are the same on every decoder: a downbeat or two the model marks mid-bar, between downbeats whole bars apart, are counted from the beats, so a 12 ms decoder offset no longer gives the Mac 78 bars and the rest 75 (#49) 2026-11-24 23:46:55 -08:00
shinyobjectz c0417d91ab raea render --props and --scale, getInputProps() and a composition's calculateMetadata: input props over defaultProps, a size or length worked out from them, and a render at S times the composition's size (#176, #175) 2026-11-24 23:46:55 -08:00
shinyobjectz c0d94f8f0c raea media share FILE -o OUT.mp4: a copy to send, held to a bitrate (2600 kbps unless --kbps), and raea ffmpeg reads the skill's -maxrate line as it (#219) 2026-11-24 23:46:55 -08:00
shinyobjectz 8345d76223 The mix reaches its loudness: make-up gain is found by a secant over up to 8 passes, so a dense beat the leveller holds back lands on the target and not 2 LU under it (#220) 2026-11-24 23:46:55 -08:00
shinyobjectz e9a7b9fd16 An <R3F> in a box of the page shows what the page paints under it: the camera clears to nothing there, where it took the nearest ancestor's colour and cut a sibling layer out (#235) 2026-11-24 23:46:55 -08:00
shinyobjectz 477b14a0ae A VP9 WebM keeps its alpha after ffmpeg -c copy: the muxer writes the tag as ALPHA_MODE, and only alpha_mode was read (#224) 2026-11-24 23:46:55 -08:00
shinyobjectz 407dbc5bec raea sounds get -o DIR: a folder that already holds another instrument keeps it, and this one goes in DIR/PACK-INSTRUMENT (two instruments share note names, so the second replaced the first and its licence, #217) 2026-11-24 23:46:55 -08:00
shinyobjectz c1eaaa37f1 raea media: one argument holding several file names is those files, so a shell that does not split a variable gets its sheet instead of "File name too long" (#218) 2026-11-24 23:46:55 -08:00
shinyobjectz 538bc30f37 A project's client in its own file (apps/workspace client.rs): workspace.rs was 512 lines, over the 500 a file may be 2026-11-24 23:46:50 -08:00
shinyobjectz 5d411345ef The manual's raea project page: --client and --no-client described, and its usage as the binary gives it 2026-11-24 23:46:50 -08:00
shinyobjectz 16abfb08b7 A project names its client, raea cloud's tag, instead of sitting inside another project: raea project new NAME --client C, raea project tag [NAME] --client C | --no-client; raea project and raea workspace --json say it (and the workspace's clients). raea.app files every card raea show makes from the folder under it 2026-11-24 23:46:50 -08:00
shinyobjectz 27b70f7366 raea voice: the trace reads the echo's delay and gain as fields (a method for it copied another, the dupes check), and the skills coverage check knows raea voice is run by raea.app's Ideate, never by an agent 2026-11-24 23:46:49 -08:00
shinyobjectz 8b774295e1 raea voice: Pocket's own voice by default (never a clip from the person's voice folder), a help line and a manual page, a silent microphone said as an error, and --over: its own voice taken out of the microphone's sound so the person can talk over it through speakers (echo.rs: an adaptive filter, a second one behind it that always learns; opt-in, checked in a simulated room with --room GAIN, not yet across real rooms) 2026-11-24 23:46:49 -08:00
shinyobjectz 04cd051788 raea voice: speech to speech on this computer, for raea.app's Ideate. A session of JSON lines (say, end, stop, mute in; ready, speech began/ended, heard, saying, word, said out): Silero VAD finds the person's turns, Parakeet TDT 0.6b v3 writes their words, Pocket TTS speaks the agent's as they stream, all on ONNX Runtime with cpal for the microphone and speakers, so it runs on any OS with no cloud voice. While it speaks it doesn't listen unless --duplex (a laptop hears its own speakers); words begun before it started are still heard. raea voice hear FILE.wav and raea voice say "WORDS" -o OUT.wav do one of each; --from/--to put a recording and a file in place of the microphone and speakers for checks. Measured on an M5 Pro: 8.9 s heard in 266 ms, first sound 44 to 81 ms after the words (crate raea-app-voice, bin raea-voice; the raea CLI's voice arm is not yet compiled into a release binary) 2026-11-24 23:46:49 -08:00
shinyobjectz ce46f5151f DN12: done; raea-skills #123 carries the skill copy for the landing to merge with the pin bump 2026-11-24 15:43:42 -08:00
shinyobjectz 1386761981 DN0: raea bench denoise draws each case on each denoiser (off, MetalFX; raea's own and DLSS-RR say why they can't run yet) and scores it against the same frames path-traced: LDR-FLIP written from the paper, RMSE, bias in stops, blotches (a mid band's error), flicker as the error's second difference against the truth's shot, a whole-frame spike, lag after a disocclusion or a light going out, a still's and a live frame's cost, and how many of MetalFX's numbers each meets
It runs on raea light check's runner, which gains pub render_with, live_with, frames_with, list_flag, spp, cell and Scene::shot_frames with light check unchanged. The cases are bench/denoise: nine small rooms (a dark room under gain, a waxed floor, a door opening, a whip pan, neon, leaves, a sunbeam in fog, a mirror, a light going out), a full-HD cost case, and a real take's doorway. The manual gets raea bench's page, in the Check group.
2026-11-24 15:42:56 -08:00
shinyobjectz 898a7f8b0e DN12: the Bevy guide's Solari page says which denoisers, upscalers and neural passes raea has, where each runs and what each can't do or isn't allowed (MetalFX, none, raea's own, DLSS-RR, OIDN, steady AA, motion blur, FSR Ray Regeneration, NRD, mlxdlss), and to measure a denoiser with raea bench denoise rather than by eye 2026-11-24 15:42:49 -08:00
shinyobjectz 6f6362040b DN0: docs/denoise.feature (DN0-DN12) and docs/denoise-upscale-research.md: raea's own WGSL denoiser and upscaler on every OS, MetalFX and DLSS-RR as optional backends held to one bench 2026-11-24 09:31:23 -08:00
shinyobjectz 66eb15448f skills: pin raea-skills 0e01a14 (#121, instruments cast from the free libraries) 2026-11-23 18:22:23 -08:00
shinyobjectz 153fbc6267 motion guides: cast each part's instrument from the thousands of free libraries, not the same four packs
Shane, 11-23: "when i say midi it just picks the same ones there thousands of insturments out there to go use".
Every worked example and the first routing line sent agents to raea sounds' four packs (Salamander, FluidR3 GM,
tonejs-instruments, VCSL), so every score sounded alike. music.md gains "Cast the instruments for this piece"
(a casting line per part, search the libraries, MIDI means notes not General MIDI, the cast in the notes) and reads
SFZ/Decent Sampler maps into a Sampler. sources.md routes instruments to casting and adds Karoryfer (all CC0 now),
Pianobook, Decent Samples, Versilian's other free libraries, hilbricht.net's list and musical-artifacts, with their
licences checked 11-23, plus a rule for samples that can't be passed on (gitignored, with a SOURCE.txt).
2026-11-23 18:17:35 -08:00
shinyobjectz 0575660417 BK3: the trace on the GPU (sky, emission, bounces), and BK2's origins off their triangles' edges
raea-sys-lightbake's trace: cosine-weighted paths through a BLAS and TLAS the bake builds from the meshes it bakes, by
wgpu ray queries on raea-gpu-device, with no Bevy render world (docs/bake.feature BK3 says why). wgsl/diffuse.wgsl
is a module systems/rt can include as it is. A device without ray queries is refused with the reason; a GPU error is
the bake's error, never a black map. In progress: not the <Environment>, baked lights, the sun's first hit, textures
or the drawn albedo of procmat, wear and sdk/wear. Only Metal has run it.

Tests with known answers: a white furnace at all 2834 open texels, a black wall's form factor within 0.002, a closed box
glowing 1 with albedo a half reading 2.004 for 2, a red wall's bleed, the same bytes twice. Breaking the cosine, the
bounce offset, the roulette, its weight, the emission or their order each fails one of them. The trace alone at 512
samples: table 0.8 s, Cornell 0.3 s, window room 0.9 s (grey 0.7, white sky), linear in samples.

It found a leak BK2 landed with: origins in a chart's edge band sat in the neighbouring wall's plane, and half their
rays left a closed room (1.16 for 2.0 on the box's edges). They're now four offsets in from their triangle's edges,
half a texel at most. raea_sys_atlas::laid returns the ray mesh numbered as the texels number it, so the layout's
model isn't read back. BK2's table is measured again (the atelier's row is from before).
2026-11-23 18:14:54 -08:00
shinyobjectz 0b8ec429cb BK2: one lay() for both bakes, so the same request gives the same atlas by construction
raea_sys_atlas::lay lays a request's model out (its triangles, their ray mesh, the atlas); layout() and
raea-sys-weathering's bake both start from it, where the split had left two near copies. The light bake's
triangle-mode filter is a plain check, not a closure shaped like another crate's. Weathering's 11 tests and the
light bake's 4 pass.
2026-11-23 18:01:40 -08:00
shinyobjectz 0bdc8714a6 BK2: done: each texel's place in the world, and the atlas split out as raea-sys-atlas
docs/bake.feature BK2 @done. raea-sys-lightbake starts: texels(glb, request) lays the model out over the atlas
raea/wear's cause maps share (BK1's layout, no second raster), reads the layout's model back as world triangles
into a parry3d BVH, moves each point off its surface by 1e-5 of the model's size (at least 10 microns), and marks
the texels inside other geometry: 16 cosine-weighted rays each, inside when at least half meet a back face and more
meet back than front. Tests: a slab with a block sunk 10 cm in and a box set by its node's translation (points on
the world surface, the sunk part and the floor under the block marked, the open not); the same texels twice; a
worn model's request gives its wear atlas.

Measured at 64 texels a metre, debug build: table 1.55 M texels, 0.67% inside, 3.4 s with its layout; Cornell
232 k, 7.5%; window room 980 k, 9.8% (the bands where each wall box runs into the next wall and the slabs, the floor
under the furniture's feet, the walls behind the window's piers); atelier 4.1 M, 4.9%, 70 s (41 s of it the layout,
which a release raea does in 1.6 s).

raea-sys-atlas (a facility) holds the atlas now: scene.rs, charts.rs and merge.rs moved from raea-sys-weathering
as they were, its hidden-triangle step and shared samples from rays.rs, and Ask, the env fields an atlas is laid out
for, parsed once for both. The light bake builds on it instead of sideways on another system, and weathering, at
1999 of 2000 lines, has room again. Weathering's bakes are the same: the table and window sets baked before and
after the move gave the same keys and the same 12 files byte for byte, so no cached wear bake rebakes. Its 11 tests
and raea-runtime-wear's pass; docs/wear.feature WR1's crate table says where each file is now.
2026-11-23 17:57:24 -08:00
shinyobjectz ac009cb5c5 BK1: done: one second UV set for the lightmap and the cause maps, weathering's charts measured against xatlas
docs/bake.feature BK1 @done. raea_sys_weathering::layout(glb, request) returns charts.rs's atlas alone (the model
with TEXCOORD_1, the atlas's size and density, every texel's world point, normal and triangle), with no causes
traced; given a wear bake's request it is that bake's atlas byte for byte (the test says so), so a lightmap and
raea/wear's cause maps read one TEXCOORD_1 instead of colliding. bake() now starts from the same lay() step;
its outputs and keys are unchanged.

Measured at 64 texels a metre over each set's world triangles, weathering's charts against xatlas (vendored and
built, then dropped): atelier (655k triangles) 1.6 s against 255 s, 15.6k islands against 28.9k, 546k seam texels
against 708k, stretch 0.021 against 0.042, both 51% used. xatlas is a little better on the small sets (table:
54 islands against 196; window: 85% used against 75%), but 255 s for UVs alone spends the bar's 60 s four times.

BK2's plan reads the layout's texels instead of a second raster; BK3 bounces the albedo raea draws, procedural
and wear extensions included, from one shared WGSL module; BK5's test set gains a worn set. docs/wear.feature
WR1 says its atlas is shared.
2026-11-23 17:40:42 -08:00
shinyobjectz 0cd00209bf BK0: done: the test set's Cycles references at 1024 samples and the numbers before any bake
docs/bake.feature BK0 @done, with its table. Table set: raea unbaked 0.0964 RMSE (0.355 stops) against the Cycles still,
raea with Cycles' maps 0.0445 (0.090); lightbake.py 242 s and 851 MB, so the bar's time is 60 s. Cornell box: black in
raster raea (0.708), 0.0758 with the maps. Window room: 0.188 unbaked, 0.145 even with Cycles' own maps (the maps are
cooler than the still's light; not the environment, not the clamp), so its frame numbers wait on that.

The manual's raea bake page; the verb skipped in the skills' coverage until BK5 teaches <LightBake>.
2026-11-23 17:14:09 -08:00
shinyobjectz 356dacd53f BK0: raea bake light --compare, and the bake's test set
apps/lightbake (raea-app-lightbake): `raea bake light --compare DIR [--sets FILE] [--set NAME] [--samples N] [--fresh]`
runs each set in apps/lightbake/sets.json through Cycles (blender/look.py's still, blender/lightbake.py's bake, both
at --samples, 1024 by default, kept in DIR/NAME until the set's .tsx files, flags or samples change) and through raea
(the set unbaked, the set with Cycles' maps), and writes DIR/report.json and a table: each frame's RMSE and stops
against the Cycles still, lightbake.py's time and peak memory (wait4's rusage on unix), the bar's verdict on the
table set. map_stops compares two lightmaps on the same UVs in stops, for BK5's per-mesh numbers. `raea bake light
EDIT.tsx` says the bake itself is BK1-BK5.

bench/bake: the table set (bevy/realism's example), a Cornell box lit only by an emissive panel, a room lit through
one window; each has a raea composition and a -cycles one that draws lightbake.py's maps (media/baked/, ignored).
The atelier is listed, reference false with why: its Manifold solids stop `raea blender open`.
2026-11-23 16:22:50 -08:00
shinyobjectz 3532c93e4c docs/bake.feature: light baked by raea on its own ray tracer, no Blender (BK0-BK5) 2026-11-23 16:02:05 -08:00
shinyobjectz 5f252f9c13 MK20: done: retry-safe projects by their inputs, and Chats' live view with a heartbeat (platform #40) 2026-11-23 14:18:29 -08:00
shinyobjectz 7fe204fe0e MK19: done: three make skills on raea cloud (platform #40) 2026-11-23 14:18:28 -08:00
shinyobjectz b8a78ece86 MK18: done: raea make plan draws the floor plan, grey box and comparison 2026-11-23 14:18:27 -08:00
shinyobjectz 0be19d9c5e MK17: done: shots from words and from a floor plan path 2026-11-23 14:18:27 -08:00
shinyobjectz ee9400fcfd MK16: done: clearance on every frame (raea scene stage --clearance) 2026-11-23 14:18:26 -08:00
shinyobjectz 0a73d6f72f MK15: done: framing sheets and a lens chart 2026-11-23 14:18:26 -08:00
shinyobjectz fa705757ed MK14: done: camera moves, focus and the handheld walk in raea/camera 2026-11-23 14:18:25 -08:00
shinyobjectz e3d681b645 MK13: done: a kit lands as a component set with a lineup and kit.json 2026-11-23 14:18:25 -08:00
shinyobjectz 0735b03adc MK12: done: prep fits, licenses and makes LOD1 2026-11-23 14:18:24 -08:00
shinyobjectz fc8b2198a1 MK11: done: Tripo and Meshy, picked on a clay sheet 2026-11-23 14:18:23 -08:00
shinyobjectz 9f5b00f0b5 MK10: done: references in one style on one sheet 2026-11-23 14:18:23 -08:00
shinyobjectz 16687e6d8b MK9: done: a clip fix that moves sideways re-drops onto what is under it 2026-11-23 14:18:22 -08:00
shinyobjectz ec0e9f0c37 MK8: done: z-fighting found between parts and inside one model 2026-11-23 14:18:22 -08:00
shinyobjectz 735b11054e MK7: done: grounding at contact points, from feet rays 2026-11-23 14:18:21 -08:00
shinyobjectz 2da197a2f7 MK6: done: the critic's score gates only once raea judge calibrate --kind agrees 2026-11-23 14:18:21 -08:00
shinyobjectz 9b3ad124f8 MK5: done: a rubric per kind for the fresh critic 2026-11-23 14:18:20 -08:00
shinyobjectz 02cd40eb5f MK4: done: the make questions in raea ask, advice until calibrated 2026-11-23 14:18:20 -08:00
shinyobjectz 15bd90ff62 MK3: done: gates as check lines in plan.org 2026-11-23 14:18:19 -08:00
shinyobjectz 2b36c21264 MK2: done: the Stop hook blocks until raea make status is done, with the loop guard 2026-11-23 14:18:19 -08:00
shinyobjectz 20f07dd93f MK1: done: raea make status decides missing, gates and done in code 2026-11-23 14:18:14 -08:00
shinyobjectz 05decaa4c9 MK0: done: make on brief.ts (scene, kit, shot), resolved and doctored 2026-11-23 14:18:03 -08:00
shinyobjectz 7450537a46 raea make: plan.org replaced through one helper; modelbox's forget reads its cache as contact's doesn't (copied code) 2026-11-23 14:15:07 -08:00
shinyobjectz 02a1050580 raea-core-modelbox: a glTF model's triangles, box and seat facing, out of raea-sys-contact
raea-sys-contact was 1923 lines and LX7's plan (docs/linux.feature) adds 163; at 1801 it has room. The cache of
each file's triangles moves with them; contact's forget lets both go, as before.
2026-11-23 14:11:21 -08:00
shinyobjectz ab5f4cd138 skills pin: raea-skills #120 (kits and shots guides, scenes and references for raea make) 2026-11-23 14:05:39 -08:00
shinyobjectz cf369a45aa Manual: raea make in the CLI reference index (the pages after it move down one) 2026-11-23 14:01:27 -08:00
shinyobjectz 66a190ff46 raea make: L1 fixes (crate sizes, copied code, layers)
- z-fighting moves into its own crate, raea-core-zfight (raea-sys-contact was over 2000 lines).
- Camera clearance moves into raea scene (apps/scene), with raea-sys-stage's boxes and part names public
  (raea-sys-stage was over 2000 lines).
- The bundle's .glb import test is one assert in the sources test (raea-runtime-bundle stays at 2000).
- Copied code folded: status lists in one loop, --only through one helper, the lens's field of view from
  core/review, and helpers rewritten where they matched other crates'.
- raea-app-make and raea-app-check-make get their layer.
2026-11-23 14:01:00 -08:00
shinyobjectz 0deac6fe0a MK3-MK18: raea make's gates, kits, shots and plan (docs/make.feature), checked end to end
- Gates: the make question set in raea ask (core/ask library make.json), advice until calibrated;
  raea judge --kind scene|kit|shot with per-kind rubrics; the critic's score gates only once
  `raea judge calibrate --kind` agrees (MK6); gates as check lines in plan.org (--plan).
- Placement: z-fighting in scene lint (raea-sys-contact), feet-ray grounding, clip fixes that re-drop.
- Kits: raea make refs (style images, one sheet), gen (Tripo H3.1 + Meshy, each capped at its quote,
  resumable, progress streamed), pick-sheet (fitted by height, turned so the long side lies front to
  back, colour + clay), pick, prep (gen check fit, licence sidecar, LOD1), kit (components importing
  their .glb, lineup with a scale bar, thumbs, kit.json). Bundles import .glb/.gltf as a path.
- Shots: walkPath and gradeLook in raea/camera and raea/post_process; raea make framing and lenschart;
  raea scene stage --clearance M.
- Plan: raea make plan draws the floor plan, the blockout from the entrance and comparison.png.
- core/review: a thin slab at the bottom of a scene is a ground slab, left out of the views' framing.
- Guides: bevy/scenes (the job, gates, stopping), bevy/kits, bevy/shots; MIT credit in bevy/NOTICE.

Checked on a three-piece kit (refs, both generators, picks, prep, landed, two critic rounds; status
done and the Stop hook blocking until it was), a walkthrough (framing, lens chart, clearance caught a
path through a pillar) and a scene plan.
2026-11-23 13:30:56 -08:00
shinyobjectz cedf2607c6 MK0-MK2: raea make, the review loop the agent can't skip (AnyScene/AnyKit/AnyShot, docs/make.feature)
A scene, kit or shot is now a job made to a frozen plan and held to it in code:

- core/brief make.rs: `make` on brief.ts (scene(), kit(), shot() from raea/brief): kind, references, one
  style paragraph, dials with value/source/means per kind, objects with real size, route, reference or
  invented and crop, shots, compositions, deliverables, a round cap. doctor() names what the plan lacks.
  TS types generated as Make* (brief.gen.ts).
- apps/make: `raea make status [DIR] [--json]`: the kind's deliverables, NOTES.md's "What the skill got
  wrong", each composition's last render or check newer than it and clean (the record), a critic round
  newer than the newest deliverable with each blocking defect fixed or answered in NOTES, and once the
  judge is calibrated two passes in a row. Done also at the round cap or AnyKit's stall, delivered short.
- apps/check/make: the Stop hook blocks a turn's end while the job isn't done, three times at most on the
  same open items; a project without `make` is never held. Claude's Stop hook timeout 10 s -> 30 s.
- docs/make.feature MK0-MK20: the whole adoption plan (gate tiers through raea ask, grounding, kits, shots,
  plan drawing, raea cloud).

Tested: raea-core-brief 11, raea-app-make 8, raea-app-check-make 3. Not built here (disk at 13 GB):
apps/solid, apps/check and engine/cli's one-line wiring; L1 builds them.
2026-11-23 11:39:18 -08:00
shinyobjectz bfd69cc2eb raea fix: domain words as a match (a find over a pair table was a copy of weathering's Class::of) 2026-11-23 10:27:38 -08:00
shinyobjectz 0af5da5879 raea fix: raea-cli back under its 2000-line budget; raea-sys-fixes in the systems layer
The fix verb's dispatch and usage lines, and the next and doctor dispatches beside them, each on one
line, as check and notes already are.
2026-11-23 10:24:00 -08:00
shinyobjectz cb8b06ff7b raea fix: a problem looked up before it's guessed at
raea fix SYMPTOM... searches raea's own fixes (sdk/guides/fixes/raea.tsv: 31 problems found and fixed
in raea work, each with where and when) and a library of ~46,500 problem -> fix entries from community
skills and docs whose licences allow it (MIT, Apache-2.0, BSD, CC0, ClawHub's MIT-0), ranked by BM25
over problem and error text. systems/fixes (raea-sys-fixes) holds it; about 50 ms a lookup, offline.

The library is a read-only SQLite FTS5 file pinned in tools/release/models.tsv (models-1 asset
fixes-library-202b3fec.db) and packed by tools/release.sh into share/raea/models/fixes; its sources and
licences are in its meta notice (raea fix --notice). The manual's CLI reference gains raea fix.
2026-11-23 10:15:20 -08:00
Sett Sarverott b250367b6c docs(devlog): synchronize all seven contribution PRs and evidence
Carry the same completed helperboard across independent branches, linking upstream PRs 226 through 232, their source proposals, validation limits and verified reporting routes. This records publication, not upstream adoption.
2026-11-23 16:59:36 +01:00
Sett Sarverott 813bc24097 docs(devlog): synchronize all seven contribution PRs and evidence
Carry the same completed helperboard across independent branches, linking upstream PRs 226 through 232, their source proposals, validation limits and verified reporting routes. This records publication, not upstream adoption.
2026-11-23 16:59:31 +01:00
Sett Sarverott 2127b369d3 docs(community): propose respectful participation and moderation guidance
According to the conduct-policy suggestion in upstream PR 226, define behavior, proportionate moderation and safe reporting without inventing an inbox, confidentiality promise or enforcement deadline. Document GitHub reporting availability and its limits.
2026-11-23 16:57:07 +01:00
Sett Sarverott 5650d65c65 docs(devlog): carry the contribution helperboard into development-3
Start this independent proposal from original main, preserving completed AppImage and agent-guide PR references and the phased plan shared by the contribution series.
2026-11-23 16:57:07 +01:00
Sett Sarverott 974148442e docs(devlog): record AppImage PR 226 and its validation
Link the published contribution and record completed branch, commit and publication steps so subsequent independent PRs can refer to their source proposal.
2026-11-23 16:50:15 +01:00
Sett Sarverott 89fd926258 docs(install): introduce the Linux AppImage distribution
Point users to the engine AppImage command, checksum and detailed release recipe without hardcoding a fork-only download path.
2026-11-23 16:48:55 +01:00
Sett Sarverott dd9be82976 ci(release): attach checked Linux AppImages to GitHub releases
Package the Linux archive in source and candidate-promotion runs, attest and upload the image and checksum, retain failure logs, and preserve dry-run artifacts without publishing.
2026-11-23 16:48:55 +01:00
Sett Sarverott 784e156895 docs(release): explain AppImage builds and runtime requirements
Document local packaging, offline tool overrides, release attachment behavior and host requirements. Distinguish the engine distribution from the separately distributed desktop editor.
2026-11-23 16:48:55 +01:00
Sett Sarverott 2161fa0ba0 feat(release): package the checked Linux archive as an AppImage
Reuse the verified release archive, preserve runtime resources and the dlopen bundler, and pin linuxdeploy and the AppImage runtime by version and checksum. Run the release checks before producing the image checksum.
2026-11-23 16:48:55 +01:00
Sett Sarverott e745f91ae4 test(release): check AppImage payloads through AppRun
Extract an AppImage without FUSE and run the existing SDK, render and host checks through its launcher so packaging cannot rely on the build checkout.
2026-11-23 16:48:55 +01:00
Sett Sarverott a0f685b043 feat(appimage): describe the engine terminal launcher
Provide the desktop metadata and icon name needed by linuxdeploy. Terminal=true reflects the public CLI packaged here; the desktop editor source is absent.
2026-11-23 16:48:55 +01:00
Sett Sarverott 5c4ddb6989 feat(appimage): add a launcher for the packaged engine
Resolve the SDK, bundler and companion executables within the AppImage while preserving the caller working directory and arguments.
2026-11-23 16:48:55 +01:00
Sett Sarverott 17518a3ac1 docs(devlog): plan the AppImage and repository guidance series
Record phases and verifiable steps before publishing. Carry this helperboard in each independent PR and distinguish existing policies from proposed improvements.
2026-11-23 16:48:55 +01:00
shinyobjectz a4898b764f L2: a refused build stops at once, the plugin build goes last and needs 45 GB free, and a resumed run reuses its binaries
11-22 on 6d6e81d7: lane refused the host build under its 8 GB floor and L2 retried eight times in a second, each
reported as "lane hold ended". Once disk was freed, the plugin build started with 8 GB free and filled the disk
(120 MB left, other sessions' jobs running), and its failure stopped L2 before ui-parity, conformance and the
bench checks.

- a "lane build: refused" line is reported as REFUSED and not retried
- the plugin build and its P26 rows run after the bench checks; a failed or skipped plugin build says how many
  compositions weren't compared and holds up nothing
- the plugin build runs only with 45 GB free (it compiles every crate again with the plugins' features)
- a resumed run whose binaries are already in $OUT/bin for this commit doesn't build them again
2026-11-22 20:18:01 -08:00
shinyobjectz 6d6e81d7f4 SG17: a CSS animation in a frame rendered alone is where the render has it; L2 holds the frame-order benches
A frame alone (`render --frame N`, or `--at` that doesn't start at 0) mounts every element in one pass. The page
resolved them all at the earliest <Sequence> start, so an animation outside any Sequence began there
(sdk/react/bench/css/anim.tsx: A at x 100, not 300, at frame 15 alone, on 0.1.9 too), and on a page with no
<Sequence> every animation began on the frame itself (frame 15 alone: x 0, not 300). engine/page motion.rs now
resolves at the earliest start, an element outside any Sequence starting at the composition's 0, and moves each later
element's animations to its own start (blitz-dom BaseDocument::delay_animations). A render of every frame, and P26's
`--at` from frame 0, mount each element on its own frame and are unchanged.

P26 couldn't see it: it compares with 0.1.9's baseline. tools/l2.sh now runs the benches in bench/l2-checks.txt, which
check what is right (at-0, at-time, at-3d, compute-frames, css), each with the candidate's raea: 5/5 on this build.
css/check.sh takes RAEA_BIN as the other benches do.
2026-11-22 19:20:30 -08:00
shinyobjectz 6cd3a2f29f A comment that says "import" no longer takes the edit's real import
The rewriter skipped a match that started in a comment, but went on searching after the match's end. A header line
such as "its @import and nesting" therefore swallowed the `import { ... } from "raea"` below it, which stayed
unrewritten and threw "Can't find variable: raea" before the first frame (sdk/react/bench/css/edit.tsx on 0.1.9,
P26's one failure). It now looks again right after the comment or string the match began in.

Test: an_import_written_in_a_string_template_or_comment_is_left_as_text gains the case (it fails without the fix). sdk/react/bench/css/check.sh's CSS part passes; its
CSS-animation part (a frame rendered alone, A at x 100 not 300) fails the same on 0.1.9 and is separate.

check.sh finds the repo's target/release/raea by default (it looked under sdk/react, where it cds first) and takes a relative RAEA path.
2026-11-22 18:31:19 -08:00
shinyobjectz a616f42b7c UI conformance runs again: 0/19 to 18 pass + 1 slow on 0.1.9's page. Each world starts the app's own host (host/node.ts, or an installed app's host.mjs) beside raea-page-host and points the page's /host/* at it (RAEA_PAGE_HOST), as raea.app does; without it the page waited on "raea is starting" and every case failed at its first step. The app is built with its demo world (RAEA_FIXTURES=1, since 11-14 a plain build has none) into blitz/out-conformance. --app takes an installed raea.app's feed folder. Three cases follow 0.1.9's UI: the feed opens on i-set then i-ideas, the card menu's hide is menu-feed-item-hide, and the rail's project rows replace the feed rows (rail-project-select). 2026-11-22 18:17:12 -08:00
shinyobjectz 2aabccbda3 ST7a, ST8a, ST9a, ST10a, ST10b @done (rask listed them at the stack's land; ST9b stays open: its claims wait on the paused story models) 2026-11-22 18:09:52 -08:00
shinyobjectz 873179a540 ST10b: measured against plain prompts. Eight prompts written five ways by one writer, judged blind by two models of other families: raea/story as the editor of a draft (read back into story data, checked, fixed by beat) ties a hard editing prompt and beats plain 26 of 32 votes (p = 0.001); a script drafted straight into story data reads worst (7 of 32 over plain). docs/story.md 'Measured' has the numbers and the caveats; the write and score guides lead with draft, read back, check, fix by beat (raea-skills #117, pin to 9e535c8). bench: the extractor's mechanical slips tidied, every arm reusable, the fuzzer counts a clear RangeError as a refusal. 2026-11-22 18:03:23 -08:00
shinyobjectz 69c631b662 ST10a: raea/story under edge cases, fuzzing and an A/B against plain prompts. Fixes what they found: fromData holds a story to storySchema() (shapeErrors), so a wrong-typed field or one in the wrong place is refused with where (a beat's turns, believes as text: 270 of 1,572 corpus stories carried one, silently dropped before) instead of crashing a reader (21 crash sites fuzzed to 0); unsets takes a fact back from those in the event and from the audience, and a claim can't rest on an undone fact; two beats with one id are an error (fromData and checks); seconds can't be negative; a telling that shows nothing is a finding; asker says when a beat isn't there. bench/: edges.ts (29 cases), fuzz.ts, ab.ts + ab-report.ts. direction: file_index without the closure cargo-dupes matched (293 exact again). 2026-11-22 18:03:23 -08:00
shinyobjectz a572288148 ST8a: the skill carries craft/story (raea-skills #115, pin to 4a77a0b): the launch page, typed questions and the launch lens in score, meant in check, any length and story lines in write. The story models are paused (Shane, 11-22); docs say where things stand. 2026-11-22 18:03:23 -08:00
shinyobjectz 5879f67686 ST7b: the launch lens: trouble in the viewer's words, the name, the product doing its job, a named proof, how to start; LAUNCH_PRIORS measured on 156 pairs (length by bucket, a voice), said as notes, never as causes 2026-11-22 18:03:23 -08:00
shinyobjectz fcbdd55282 ST7a: the launch findings: 156 pairs, length the one feature that holds (104/155, p < 0.001), a voice and a weaker beat don't survive correction, nothing in the cut separates; the blind read 23/30 (p = 0.003) but the longer film alone gets 25/30. Craft doesn't show here; the size of the news does. 2026-11-22 18:03:23 -08:00
shinyobjectz 23220fa002 ST6c: story as decisions. src/questions.ts: a beat's window (story lines or a plain script) as a decision model's state and typed questions about it in the Jev / Clef format (11 checks as noul, the event shown, the turn, continues, learns, opens, tension, three lens stages), each answered exactly by the checks, systems and lenses. models/decide-rows.ts (corpus, cuts, swaps and mutants: 15,154 train windows), models/clef.ts (Clef and Clef-flash zero-shot), models/decide.py (Qwen3-0.6B frozen, LoRA, an option head, one prefill pass, cross-entropy plus Brier), models/decide-score.ts. scriptOf moves into raea/story; split into models/lib.ts. 2026-11-22 18:03:23 -08:00
shinyobjectz aa9dc07369 ST9: docs: any length (state, story lines, windowed generator and extractor, hierarchy next) and its plan rows 2026-11-22 18:03:23 -08:00
shinyobjectz db596714ab ST9b: any length. src/state.ts: stateAt (what the systems hold just before a beat: knows, open, suspense, levels, tension, unpaid setups, unsettled wants, events ahead) and windowAt (that state, the events still usable and the beats around one, as story lines). The generator now writes a beat from its window; the extractor reads a script six beats at a time with what earlier steps found (models/lib.ts chunkSteps, merge exact on all 1,571 corpus stories), chained end to end by story_models.py chain through models/known.ts. 2026-11-22 18:03:23 -08:00
shinyobjectz 16c9932b2a ST9a: story lines (src/lines.ts): a story as one keyword-led line per value, fact, agent, event and beat, reading back exactly (every valid corpus story round-trips); what people skim and models stream a line at a time. A beat's scene groups shots; fromData refuses lenses that aren't names. 2026-11-22 18:03:23 -08:00
shinyobjectz b8eee1249d ST6a: the corpus's --long slice: films told a beat a shot (20 to 40 beats over 12 to 30 events, an event across several shots), the length held as a checked rule, reasoning off so the answer fits 2026-11-22 18:03:23 -08:00
shinyobjectz 212186d907 ST6b: models/validate.ts: a held-out story (another author's, for a film of their own) through the checks, every lens, and rows in the models' format for predict, frontier, onnx and score. ST3b: a beat's meant: [checks] takes those findings about it out of what checks and lenses report (a breather the journey wants, where McKee would flag it); models/lib.ts holds what rows.ts and validate.ts share. 2026-11-22 18:03:23 -08:00
shinyobjectz caabca1d90 ST3b: field-tested on a 55-shot film. A beat's stage label pins its lens's stage before the lens reads (and any lens's inciting or climax label pins the anchors every lens reads); stages nobody labelled are held between the labelled ones; the inciting incident is the first shown, non-routine event that changes anything; the crisis is the last dilemma after it; a refusal can be a dilemma; shots that continue the beat before's event count its turn once (no false rhythm or no-turn findings); McKee doesn't call danger rising on another value easing off; resolution events aren't dead ends. ST6b: speech-only extractor rows, scored apart; ONNX int4 export and prediction under the same schema. 2026-11-22 18:03:23 -08:00
shinyobjectz 0fec51f6d9 ST8a: craft/story, stories as data in the guides: a router (which page, which lens), how to write, check, sample and score a story with raea/story, and a page per framework in our own words with its sources (McKee, the story spine, Storynomics, PAS, Campbell, Vogler, Harmon, Save the Cat, Kishotenketsu, Propp, Bernays). raea guide lists them as story/NAME; tools/skills.sh copies them into the skill's craft/story/. 2026-11-22 18:03:23 -08:00
shinyobjectz f6af08fd69 ST3b: the rest of the frameworks as lenses: Campbell (call, aid, threshold, the ordeal as the lowest point before the boon, the boon lifting above it), Vogler (twelve stages; masks checked by what they do: a herald brings the call, a shadow acts against the hero), Harmon (the price after the getting, the change), Save the Cat (positions as shares of the telling, so an ad and a feature hold the same shape), Kishotenketsu (a late turn, no conflict asked for), Propp (lack, the donor's test, struggle, the lack made good) and Bernays (proof the audience has seen by the claim, a witness besides the brand, the customer's want; invented proof is an error). Read over 619 corpus stories with none failing to read. 2026-11-22 18:03:23 -08:00
shinyobjectz dcb0cf8f49 ST5a: one helper finds or adds a check file for both runs (no copied block); the manual's brief and check pages for Scene.beat and over 2026-11-22 18:03:23 -08:00
shinyobjectz f0372580bb ST0c, ST5a: raea check reads stories. brief({ story }) is kept as written (Brief.story, opaque to Rust); a script's scene names its beat (Scene.beat, compileScript writes it); a .ts check declares over: "frames" | "story" | "both", and raea check NAME.story.ts runs the story checks once with no frames, before anything is drawn. raea/story/raea/checks gives storyCheck (the story's exact and lens findings, then every beat on screen in order with its lines spoken inside its shot) and raea/story/raea/compose gives beatTimes and <Beat>. Beats take an optional id. data.ts reads a story from JSON with every bad reference named, and gives the schemas the story models decode under (a beat's schema holds the story's own keys). models/: the corpus writer, the training rows, MLX training with constrained decoding, and the scorer.
Skills: SKILL.md section 3 names core/brief/src: checked, still true (two optional fields, nothing a reader does changes).
2026-11-22 18:03:23 -08:00
shinyobjectz 79e8ac7af9 ST3a: lenses (McKee, the Pixar spine, Storynomics, PAS), seeded sampling with a theme matrix, and compilers to Script, storylets, Ink and Yarn
ST4a, ST5b. A lens maps its stages onto beats from the shared structure (hero, brand, inciting event, crisis, climax),
checks its framework and proposes beats for missing stages; readThrough reads one telling through many. A telling may
hold choice points over beats (null drops one) and whole tellings; sample() walks seeds until a story passes the exact
checks and every lens given, samples() gives several different ones, and matrix() runs one pattern across premises.
compileScript gives raea/brief's Script, compileStorylets and dramaManager play the world in causal order toward a
target curve, toInk and toYarn write the lines. Mutation now works on resolved stories (RStory).
2026-11-22 18:03:23 -08:00
shinyobjectz 22dffb4170 ST0a: raea/story: stories as typed data in an ECS, with derived curves, exact checks and labelled mutation
A new TypeScript package, sdk/story (@raea/story, "raea/story"). A story is a world of facts and caused events, and
tellings of it as beats. story() infers each key where it's declared and checks it where it's used, so tsc refuses an
unknown agent, fact, value, cause, shown event or payoff (test/types.ts). load() puts one telling into a small ECS.
Systems derive value curves and their shapes, the audience's and agents' knowledge (suspense, open questions,
unearned surprise, belief breaks), the cause graph (uncaused events, 'and then' beats) and tension. checkStory() reads
only what's derived. mutants() breaks a valid story in nine labelled ways; every break with an expected check is
found by it (test/mutate.test.ts). Plan: docs/story.md; tasks: docs/story.feature (ST0-ST8).
2026-11-22 18:03:23 -08:00
shinyobjectz b6dd19a649 P26a: the baseline is the published 0.1.9's (212 frames, 69 compositions)
The last Blitz build and its frames were lost after 11-16, so P26 had nothing to compare against. The baseline is
re-taken from the 0.1.9 release tarball (unpacked at ~/Library/Caches/raea/p26-baseline/bin-v0.1.9, sha256 in
binary.json), in L2's v0.1.9 checkout as l2.sh renders. capture.sh lets the checks through as compare.sh does: three
scenes that clip (broll, bevy/lights, arena3d) had kept no frames. sdk/react/bench/css/edit.tsx throws on 0.1.9 before
its first frame (failures.txt). 0.1.9 held to it: 212 of 212 at SSIM >= 0.98.
2026-11-22 18:03:23 -08:00
shinyobjectz 0d853cff8e SG10: Text3D in its own file (sdk/render/src/3d/text3d.tsx, re-exported from shapes.tsx, which was 515 lines); the stage checks' two new one-line copies folded (a part's opacity is a named fn, a Label's points parse through serde) 2026-11-22 18:03:23 -08:00
shinyobjectz cab9f4bb28 SG10, SG14: 3D type behind a part and Text3D are checked; a part a Label names is the shot's subject
SG10. A Text3D is held to the type checks a RichText meets (its words and em read from its mesh's text3d shape; read={false}
on the Text3D or its mesh makes it scenery). New, cover.rs: words more than half hidden behind another part for half a
second are a type-hidden error naming the part (a 3x3 grid through the letters, each point's line to the eye against
the part's own box; words, see-through parts, a part round the camera and models never hide words). Measured with raea
scene stage: no finding added or lost on the 48 clean scenes; on 14 scenes with 3D type only the heros game's moving
26 px caption words; on the essay film 26 type-hidden errors, three of them looked at and real.

SG14. A Label writes its point (data-points), the manifest carries it on its words, and the named part nearest it is the
shot's subject: cut by the frame's edge for more than 10 frames, an error (the guessed subject stays a warning).

SG11: raea scene stage lays out no page, so a frame it reads empty is a warning there and it says the page's checks
run in raea render. SG1: the 48-box Ribbon repro (frame-pure, and 7.5% over the whole curve). SG16: floor.md refuses a
3D film rendered a shot at a time; solari.md drops its 0.1.2 cautions, none of which 0.1.9 shows. Spec: SG1, SG2, SG8,
SG9-SG14, SG16 done.
2026-11-22 17:41:50 -08:00
shinyobjectz 7e2df514de SG9: a part a scene leaves leaves Solari's traced scene, so a film rendered whole matches each frame alone
A part a frame leaves out is hidden, not despawned: a render's rows are every part any of its frames has. Solari traced
hidden parts unless <SolariLighting dynamic> (RT5's trial) was on, so every place's parts, gone and still to come, stayed
in the traced scene unseen and shaded what was on screen: Stay rendered whole drew its later shots far darker than each
rendered alone (12 frame-pure errors). raea-render-raytrace solari.rs `hidden` now runs on every traced render, on the
parts whose visibility changed or that were just traced; the skinned twin stays the trial. And a reset (a cut) empties
Solari's world cache whole, as a render's first frame finds it: it reset only the cells it picked to update that frame.

Repros (engine/render/tests/diag): kept-scenes.tsx (a black open, a yard, a room) 0.923-0.933 SSIM to the frame alone on
0.1.9, 0.996-0.997 with hidden parts untraced; kept-light.tsx solari-gone (a box unmounted at frame 15) 0.987, 0.998; every
single change of a light or the look follows the frame. tools/frame-pure-3d.sh checks each composition a repro names at
the bar it names (Solari's noise: 0.99).
2026-11-22 16:53:20 -08:00
2339 changed files with 515553 additions and 4476 deletions

No files matched your search

+54
View File
@@ -0,0 +1,54 @@
name: Bug report
description: Something raea did wrong, with a way to see it happen.
body:
- type: markdown
attributes:
value: |
For a security problem, use the Security tab, not a public issue. Leave out keys and anything private.
- type: input
id: version
attributes:
label: Version
description: What `raea --version` prints, or the app's version from its About screen.
validations:
required: true
- type: dropdown
id: where
attributes:
label: Where
options:
- raea CLI (render, play, check, media, ...)
- SDK (TypeScript, React)
- raea app (desktop)
- Install or update
- Not sure
validations:
required: true
- type: input
id: machine
attributes:
label: Machine
description: OS and version, CPU, and for a picture problem the GPU.
placeholder: macOS 27.2, Apple Silicon
validations:
required: true
- type: textarea
id: ran
attributes:
label: What you ran
description: The command, and the smallest composition that shows it (paste the TSX).
validations:
required: true
- type: textarea
id: happened
attributes:
label: What happened
description: The output as printed. For a picture or sound problem, the frame or time and a screenshot.
validations:
required: true
- type: textarea
id: expected
attributes:
label: What you expected
validations:
required: true
+8
View File
@@ -0,0 +1,8 @@
blank_issues_enabled: true
contact_links:
- name: Security problem
url: https://github.com/shinyobjectz/raea/security/advisories/new
about: Report it privately, not in an issue.
- name: Documentation
url: https://raea.io/docs
about: The CLI and SDK reference and the guides.
@@ -0,0 +1,23 @@
name: Feature request
description: Something you want to make that raea can't do yet, or makes hard.
body:
- type: textarea
id: making
attributes:
label: What you're trying to make
validations:
required: true
- type: textarea
id: today
attributes:
label: What you do today
description: The command, SDK part or app screen you use now, and where it falls short.
validations:
required: true
- type: textarea
id: want
attributes:
label: What you'd like
description: An example of how you'd use it helps most.
validations:
required: true
+11
View File
@@ -0,0 +1,11 @@
## What changes
<!-- What triggered it, what raea did before, and what it does now. Link the issue. -->
## How it was checked
<!-- The commands you ran and what they printed. For a picture or sound change: the composition, the frame, your OS and GPU. -->
## What wasn't checked
<!-- Platforms or paths you couldn't try, and anything a reviewer should look at closely. -->
+9 -1
View File
@@ -68,6 +68,9 @@ jobs:
run: bash tools/layers.sh
- name: names
run: bash tools/names.sh
- name: legacy names
# nothing names what raea's one loop replaced (docs/goal.feature MK41)
run: bash tools/legacy-names.sh
- name: size
run: bash tools/size.sh
- name: one-version
@@ -118,7 +121,12 @@ jobs:
# 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-runtime-plugins -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
# raea-bundle in a call of its own: Rolldown's crates turn on serde_json's arbitrary_precision, features unify
# across one cargo call, and with it on an untagged enum can't read a number (raea-core-brief's make dials failed
# here from 11-23 while passing alone). raea itself never links Rolldown: it loads it as a library at run time
run: |
cargo test --locked -p raea-runtime-plugins -p raea-io-media -p raea-core-fonts -p raea-native -p raea-core-brief -p raea-core-k -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
cargo test --locked -p raea-bundle
- name: Windows' and Linux's own (#169)
# what a Windows or Linux user meets that no other step ran: QuickJS's Intl (raea-runtime-jsengine's
# quickjs_formats_as_javascriptcore_does, on Linux), openh264 at --quality master (raea-io-soft), git found or
+36 -1
View File
@@ -2,6 +2,7 @@
# Apple Silicon, Linux on x86_64 and Windows on x86_64 are built from the tag on GitHub's runners, packed by
# tools/release.sh, checked by tools/release-check.sh, attested (anyone can check a download with
# `gh attestation verify raea-VERSION-macos-arm64.tar.gz -R shinyobjectz/raea`) and attached to the tag's release.
# Linux also packages and checks an AppImage from the same verified archive (tools/release-appimage.sh).
# The skills gate reads the feed app, which is private, so it runs in a maintainer's checkout first
# (tools/skills.sh check), and the tag names the commit it passed on; tools/release.sh checks the gate's inputs haven't
# changed since (tools/release/skills-passed.sh):
@@ -181,6 +182,11 @@ jobs:
v=${TAG#v}
if [ "$RUNNER_OS" = Linux ]; then xvfb-run -a -s "-screen 0 1280x1024x24" bash tools/release.sh "$v" ship HEAD
else bash tools/release.sh "$v" ship HEAD; fi
- name: Package and check the Linux AppImage
if: runner.os == 'Linux'
env:
RAEA_CHECK_DIR: ${{ runner.temp }}/appimage-check
run: xvfb-run -a -s "-screen 0 1280x1024x24" bash tools/release-appimage.sh "${TAG#v}" "dist/raea-${TAG#v}-linux-x86_64.tar.gz"
# a failed check's own files (the app check's frames, every step's log), not the unpacked release
- uses: actions/upload-artifact@v4
if: failure()
@@ -189,6 +195,8 @@ jobs:
path: |
${{ runner.temp }}/release-check/app
${{ runner.temp }}/release-check/**/*.log
${{ runner.temp }}/appimage-check/app
${{ runner.temp }}/appimage-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
@@ -202,6 +210,10 @@ jobs:
if: ${{ !inputs.dry_run }}
with:
subject-path: dist/raea-*.tar.gz
- uses: actions/attest-build-provenance@v2
if: ${{ runner.os == 'Linux' && !inputs.dry_run }}
with:
subject-path: dist/raea-*.AppImage
- name: Attach to the release
if: ${{ !inputs.dry_run }}
env:
@@ -209,11 +221,16 @@ jobs:
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
if [ "$RUNNER_OS" = Linux ]; then
gh release upload "$TAG" dist/raea-*.AppImage dist/raea-*.AppImage.sha256 --clobber
fi
- uses: actions/upload-artifact@v4
if: ${{ inputs.dry_run }}
with:
name: dry-run-${{ runner.os }}
path: dist/raea-*.tar.gz*
path: |
dist/raea-*.tar.gz*
dist/raea-*.AppImage*
retention-days: 3
compression-level: 0
@@ -223,6 +240,9 @@ jobs:
# (tools/release/win-bundle.sh), as Microsoft documents for app-local deployment.
windows:
runs-on: ${{ (vars.RELEASE_WINDOWS_RUNNER && fromJSON(vars.RELEASE_WINDOWS_RUNNER)) || 'windows-latest' }}
# the signing identity's federated credential trusts this repository's environment "signing" and nothing else
# (Azure app raea-release-signing); with no identity set there is no environment, and the zip is unsigned
environment: ${{ vars.AZURE_SIGN_CLIENT_ID != '' && 'signing' || '' }}
timeout-minutes: 350
env:
# the compile cache, as build's
@@ -352,9 +372,24 @@ jobs:
run: bash tools/release/lavapipe.sh
- name: Where the skills gate passed
run: bash tools/release/skills-passed.sh "$TAG" "${{ inputs.skills_passed }}"
# raea's own Windows programs signed (#221), once the repository has the signing identity: the variables
# AZURE_SIGN_CLIENT_ID, AZURE_SIGN_TENANT_ID and AZURE_SIGN_SUBSCRIPTION_ID name an Azure app whose federated
# credential trusts this workflow and which holds the Artifact Signing Certificate Profile Signer role on the
# account (no secret is stored: the job's own token is exchanged). Without them the zip is unsigned, as before
- name: Sign in to Azure for signing
if: ${{ vars.AZURE_SIGN_CLIENT_ID != '' }}
uses: azure/login@v2
with:
client-id: ${{ vars.AZURE_SIGN_CLIENT_ID }}
tenant-id: ${{ vars.AZURE_SIGN_TENANT_ID }}
subscription-id: ${{ vars.AZURE_SIGN_SUBSCRIPTION_ID }}
- name: jsign (signs raea's programs)
if: ${{ vars.AZURE_SIGN_CLIENT_ID != '' }}
run: choco install jsign -y --no-progress
- name: Pack and check (tools/release.sh)
env:
RAEA_CHECK_DIR: ${{ runner.temp }}/release-check
RAEA_WIN_SIGN: ${{ vars.AZURE_SIGN_CLIENT_ID != '' && '1' || '' }}
run: bash tools/release.sh "${TAG#v}" target/dist HEAD
# live play on Windows (PT20 left it unproven): bevy-ts's play cases, `play --offscreen` with an input script and
# a snapshot's pixels probed, run by the raea just built; check.sh reads the pixels with ImageMagick, which the
+175
View File
@@ -0,0 +1,175 @@
# raea built natively for Windows on ARM (#82: a Snapdragon X runs the x64 build under emulation, and asked for its
# own). GitHub's windows-11-arm runner builds what release.yml's windows job builds, for aarch64-pc-windows-msvc, runs
# `raea --version`, packs and checks raea-VERSION-windows-arm64.zip with tools/release.sh (RAEA_WIN_ARCH=arm64)
# without drawing (RAEA_CHECK_NO_GPU=1: WARP segfaults in Bevy's compute shaders here as on x64, and Mesa's lavapipe has
# no ARM64 build; a Snapdragon PC is what draws, #82), and on a v* tag attaches it to that
# release. It runs beside release.yml, not in it, so a release never waits on or fails with the ARM64 build; a
# promoted release (release-go.sh) builds it again from the tag. install.ps1 takes it on an ARM64 PC when it's there.
name: windows-arm
on:
workflow_dispatch:
inputs:
ref:
description: "commit, branch or tag to build"
required: false
version:
description: "the version the zip is named for (raea-VERSION-windows-arm64.zip)"
required: false
push:
branches: [windows-arm64]
tags: ["v*"]
permissions:
contents: write
jobs:
build:
runs-on: windows-11-arm
timeout-minutes: 350
env:
# the release builds' compile cache (tools/release/compile-cache.sh), under this OS and architecture's own prefix
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
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.ref || github.sha }}
submodules: true
lfs: false
- name: Toolchain (rust-toolchain.toml's pin)
run: |
if ! command -v rustup >/dev/null; then
curl -fsSL --retry 3 -o "$RUNNER_TEMP/rustup-init.exe" https://static.rust-lang.org/rustup/dist/aarch64-pc-windows-msvc/rustup-init.exe
"$RUNNER_TEMP/rustup-init.exe" -y --default-toolchain none --profile minimal
echo "$USERPROFILE/.cargo/bin" >> "$GITHUB_PATH"
export PATH="$USERPROFILE/.cargo/bin:$PATH"
fi
rustup show active-toolchain || rustup toolchain install
rustc -vV
# ring builds its aarch64 assembly with clang (and only clang) on Windows
- name: clang (ring's assembly)
run: |
if ! command -v clang >/dev/null; then
for d in "/c/Program Files/LLVM/bin" "/c/Program Files/Microsoft Visual Studio"/*/*/VC/Tools/Llvm/ARM64/bin; do
[ -x "$d/clang.exe" ] && { echo "$d" >> "$GITHUB_PATH"; export PATH="$d:$PATH"; break; }
done
fi
command -v clang >/dev/null || { winget install -e --id LLVM.LLVM --accept-source-agreements --accept-package-agreements --silent; echo "/c/Program Files/LLVM/bin" >> "$GITHUB_PATH"; export PATH="/c/Program Files/LLVM/bin:$PATH"; }
clang --version
- name: jq that writes LF
run: |
mkdir -p "$RUNNER_TEMP/jq"
printf '#!/bin/bash\nexec "%s" -b "$@"\n' "$(command -v jq)" > "$RUNNER_TEMP/jq/jq"
chmod +x "$RUNNER_TEMP/jq/jq"
echo "$RUNNER_TEMP/jq" >> "$GITHUB_PATH"
- uses: oven-sh/setup-bun@v2
with:
bun-version: 1.4.2
- name: The runtime's packages
run: for d in sdk/react/js sdk/react/tw; do (cd "$d" && bun install --frozen-lockfile); done
# (an sccache the action can't fetch for ARM64 Windows leaves the build uncached, as compile-cache.sh does)
- name: Compile cache (sccache, as release.yml's)
if: env.AWS_ACCESS_KEY_ID != ''
continue-on-error: true
uses: mozilla-actions/[email protected]
- name: Use the compile cache
if: env.AWS_ACCESS_KEY_ID != ''
run: bash tools/release/compile-cache.sh
- name: Build
run: |
feat=$(bash tools/bevy-plugins.sh features sdk/raea/bench/bevy-plugins)
t() { s=$SECONDS; "$@"; echo "::notice::Windows ARM64 $(( (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
- name: What raea.exe is and imports
run: |
file target/dist/raea.exe || true
dumpbin=$(ls "/c/Program Files/Microsoft Visual Studio"/*/*/VC/Tools/MSVC/*/bin/Hostarm64/arm64/dumpbin.exe 2>/dev/null | head -1)
[ -n "$dumpbin" ] && "$dumpbin" -nologo -headers -dependents target/dist/raea.exe | grep -iE 'machine|\.dll$' | sed 's/^ *//' | tee -a "$GITHUB_STEP_SUMMARY" || true
target/dist/raea.exe --version | tee -a "$GITHUB_STEP_SUMMARY"
- name: Models (pinned by URL and sha256 in tools/release/models.tsv)
run: |
while IFS=$'\t' read -r path url sha; do
case $path in ''|'#'*) continue ;; esac
mkdir -p "$HOME/.local/share/raea-models/$(dirname "$path")"
curl -fsSL "$url" -o "$HOME/.local/share/raea-models/$path"
echo "$sha $HOME/.local/share/raea-models/$path" | sha256sum -c -
done < <(tr -d '\r' < tools/release/models.tsv)
# bin\ as release.yml's windows job fills it, with the ARM64 runtime, uv and DXC (RAEA_WIN_ARCH=arm64), then the
# zip packed and checked by tools/release.sh as raea-VERSION-windows-arm64.zip. The skills gate is this commit's
# (public raea has no feed app; cli.md is still checked against this build's help); nothing is drawn
- name: Pack and check (tools/release.sh)
env:
RAEA_WIN_ARCH: arm64
RAEA_CHECK_DIR: ${{ runner.temp }}/release-check
RAEA_CHECK_NO_GPU: "1"
run: |
bash tools/release/onnxruntime.sh target/dist
bash tools/release/win-bundle.sh target/dist
v="${{ inputs.version }}"
case $GITHUB_REF in
refs/tags/v*)
v=${v:-${GITHUB_REF_NAME#v}}
# where the skills gate passed, as release.yml reads it (the tag's skills-passed line)
eval "$(GITHUB_ENV= bash tools/release/skills-passed.sh "$GITHUB_REF_NAME" | grep '^RAEA_SKILLS_PASSED=')" ;;
*) RAEA_SKILLS_PASSED=$(git rev-parse HEAD) ;;
esac
export RAEA_SKILLS_PASSED
bash tools/release.sh "${v:-0.0.0-arm64}" target/dist HEAD
# on a v* tag, beside release.yml's archives (the release made here if release.yml hasn't yet)
- name: Attach to the release
if: startsWith(github.ref, 'refs/tags/v')
env:
GH_TOKEN: ${{ github.token }}
run: |
pre=; case $GITHUB_REF_NAME in *-*) pre=--prerelease ;; esac
gh release view "$GITHUB_REF_NAME" -R "$GITHUB_REPOSITORY" >/dev/null 2>&1 ||
gh release create "$GITHUB_REF_NAME" -R "$GITHUB_REPOSITORY" $pre --title "raea ${GITHUB_REF_NAME#v}" --notes "Built by .github/workflows/release.yml; notes follow." ||
gh release view "$GITHUB_REF_NAME" -R "$GITHUB_REPOSITORY" >/dev/null
gh release upload "$GITHUB_REF_NAME" -R "$GITHUB_REPOSITORY" dist/raea-*-windows-arm64.zip dist/raea-*-windows-arm64.zip.sha256 --clobber
- uses: actions/upload-artifact@v4
if: always()
with:
name: windows-arm64-zip
path: dist/raea-*-windows-arm64.zip*
retention-days: 7
compression-level: 0
if-no-files-found: ignore
- uses: actions/upload-artifact@v4
if: always()
with:
name: windows-arm64-bins
path: |
target/dist/raea.exe
target/dist/raea_bundle.dll
target/dist/raea-rune-host.exe
target/dist/raea-page-host.exe
target/dist/raea-perceive.exe
retention-days: 7
if-no-files-found: ignore
# vendor/metis-sys's header change reaches release.yml's x64 build too (windows-latest's Visual Studio): metis-sys
# alone, in a scratch crate, compiled there
metis-x64:
runs-on: windows-latest
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.ref || github.sha }}
sparse-checkout: vendor/metis-sys
- name: metis-sys on x64 MSVC
run: |
c="$RUNNER_TEMP/metis-x64"; mkdir -p "$c/src" && : > "$c/src/lib.rs"
printf '[package]\nname = "metis-x64"\nversion = "0.0.0"\nedition = "2021"\n[dependencies]\nmetis-sys = { path = "%s" }\n[workspace]\n' "$(cygpath -m "$GITHUB_WORKSPACE/vendor/metis-sys")" > "$c/Cargo.toml"
cl 2>&1 | head -1 || true
cd "$c" && cargo build
+55
View File
@@ -0,0 +1,55 @@
# Code of conduct
raea's issues, pull requests, reviews and other project-managed community spaces
should let people discuss and improve the work without harassment. This applies
to maintainers, contributors and people using automated or AI-assisted tools.
Participants remain responsible for the material they submit through those tools.
## Expected behavior
- Discuss the code, evidence and ideas respectfully. Technical disagreement is
welcome; personal attacks and assumptions about another person's motives are not.
- Give actionable feedback, accept corrections and respect requests to stop a
conversation or move it out of a thread.
- Make room for different experience levels, backgrounds and communication styles.
- Respect privacy. Share only logs, screenshots and other information you have
permission to publish, with credentials and personal information removed.
Harassment, discriminatory insults, threats, sexual harassment, unwanted repeated
contact, disclosure of private information, deliberate disruption and retaliation
against someone raising a concern are unacceptable.
## Reporting a concern
For content on GitHub, use the content menu's **Report content** action where it
is available. Choose **Report to repository admins** if GitHub offers it.
Maintainer reporting depends on repository settings and the reporter's access.
For abuse covered by GitHub's rules, use **Report abuse to GitHub Support** or
[GitHub's abuse-reporting route](https://docs.github.com/en/communities/maintaining-your-safety-on-github/reporting-abuse-or-spam).
GitHub handles those reports under its own policies; it is not the project's
appeal body for every technical or moderation disagreement.
A separate private maintainer inbox for conduct reports has not been designated
in this repository. If GitHub's maintainer-reporting option is unavailable, ask
for a private contact without posting the incident, personal information or
accusations in a public issue. Maintainers can document an additional contact
after confirming who will handle it. Use [the security policy](SECURITY.md) for vulnerabilities,
not as a general conduct-report channel.
Include links, the relevant context and your preferred way to be contacted when
reporting privately. Do not retaliate, publicly investigate the reporter or
pressure someone to disclose an incident.
## Moderation
Repository maintainers may clarify expectations, ask participants to change
behavior, close or remove disruptive content, restrict interactions, or block
continued participation as appropriate to severity and repetition. A technical
disagreement or a rejected contribution alone is not misconduct.
Maintainers should consider context and available evidence, protect sensitive
information, explain decisions when doing so does not compromise privacy, and
allow a participant to provide relevant additional context privately through the
same reporting route. A maintainer involved in a concern should seek an uninvolved
reviewer where one is available. This policy does not promise a response deadline
or confidentiality beyond what the chosen reporting service and process provide.
Generated
+386 -22
View File
@@ -8490,6 +8490,15 @@ dependencies = [
"generic-array",
]
[[package]]
name = "intel_tex_2"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7980d359170e7da4bc2421aa74c49d338a3153313e006d732a3430f1af375a60"
dependencies = [
"ispc_rt",
]
[[package]]
name = "interpolate_name"
version = "0.2.4"
@@ -8573,6 +8582,16 @@ version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]
name = "ispc_rt"
version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a396f76fd253fab9945bb4c6080f515d0c4036bc30219462d199b58886fd37b4"
dependencies = [
"libc",
"num_cpus",
]
[[package]]
name = "itertools"
version = "0.10.5"
@@ -10263,8 +10282,6 @@ dependencies = [
[[package]]
name = "metis-sys"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "769ee6be814b21c52afcc631f07051f578487d642f3e89a45f2a086fd94fffa9"
dependencies = [
"cc",
]
@@ -13669,6 +13686,7 @@ dependencies = [
"raea-app-check-cause",
"raea-app-check-flash",
"raea-app-check-inbox",
"raea-app-check-make",
"raea-app-check-read",
"raea-app-check-text",
"raea-core-brief",
@@ -13701,6 +13719,16 @@ dependencies = [
"serde_json",
]
[[package]]
name = "raea-app-check-make"
version = "0.1.0"
dependencies = [
"dunce",
"raea-core-facts",
"raea-io-home",
"serde_json",
]
[[package]]
name = "raea-app-check-read"
version = "0.1.0"
@@ -13860,6 +13888,36 @@ dependencies = [
"serde_json",
]
[[package]]
name = "raea-app-lightbake"
version = "0.1.0"
dependencies = [
"image",
"libc",
"raea-io-home",
"raea-light",
"raea-runtime-bundle",
"serde_json",
"sha2 0.10.9",
]
[[package]]
name = "raea-app-make"
version = "0.1.0"
dependencies = [
"dunce",
"image",
"raea-app-judge",
"raea-core-ask",
"raea-core-brief",
"raea-core-facts",
"raea-core-review",
"raea-io-home",
"raea-runtime-lod-plan",
"resvg 0.48.1",
"serde_json",
]
[[package]]
name = "raea-app-media"
version = "0.1.0"
@@ -13878,6 +13936,7 @@ dependencies = [
name = "raea-app-motion"
version = "0.1.0"
dependencies = [
"glam 0.33.12",
"raea-io-home",
"raea-runtime-bundle",
"raea-sys-kimodo",
@@ -13915,6 +13974,18 @@ dependencies = [
"winit",
]
[[package]]
name = "raea-app-playable"
version = "0.1.0"
dependencies = [
"dunce",
"raea-io-home",
"raea-runtime-bundle",
"regex",
"serde_json",
"zip",
]
[[package]]
name = "raea-app-registry"
version = "0.1.0"
@@ -13930,12 +14001,19 @@ dependencies = [
name = "raea-app-scene"
version = "0.1.0"
dependencies = [
"bevy",
"dunce",
"image",
"raea-core-facts",
"raea-core-scene",
"raea-runtime-bundle",
"raea-runtime-export",
"raea-runtime-lod-plan",
"raea-sys-body",
"raea-sys-contact",
"raea-sys-light-meter",
"raea-sys-motionfaults",
"raea-sys-notice",
"raea-sys-stage",
"serde_json",
]
@@ -13947,6 +14025,7 @@ dependencies = [
"dunce",
"raea-app-ask",
"raea-app-judge",
"raea-app-make",
"raea-core-facts",
"raea-core-meshcheck",
"raea-core-shape",
@@ -13992,6 +14071,19 @@ dependencies = [
"serde_json",
]
[[package]]
name = "raea-app-voice"
version = "0.1.0"
dependencies = [
"anyhow",
"cpal 0.15.3",
"ort",
"raea-io-trace",
"raea-sys-ml",
"raea-sys-speech",
"serde_json",
]
[[package]]
name = "raea-app-workspace"
version = "0.1.0"
@@ -14182,6 +14274,7 @@ name = "raea-bundle"
version = "0.1.0"
dependencies = [
"anyhow",
"base64 0.22.1",
"dunce",
"lightningcss",
"oxc",
@@ -14229,20 +14322,27 @@ dependencies = [
"raea-app-game",
"raea-app-judge",
"raea-app-layers",
"raea-app-lightbake",
"raea-app-make",
"raea-app-media",
"raea-app-notes",
"raea-app-play",
"raea-app-playable",
"raea-app-scene",
"raea-app-solid",
"raea-app-sound",
"raea-app-targets",
"raea-app-tools",
"raea-app-voice",
"raea-app-workspace",
"raea-bevy-plugins",
"raea-cli-goal",
"raea-cli-refused",
"raea-core-alloc",
"raea-core-animate",
"raea-core-brief",
"raea-core-program",
"raea-denoise-bench",
"raea-io-home",
"raea-io-media",
"raea-io-npm",
@@ -14258,6 +14358,7 @@ dependencies = [
"raea-runtime-react",
"raea-runtime-sound",
"raea-runtime-wear",
"raea-sys-fixes",
"raea-sys-index",
"regex",
"serde",
@@ -14265,6 +14366,26 @@ dependencies = [
"wsx",
]
[[package]]
name = "raea-cli-goal"
version = "0.1.0"
dependencies = [
"raea-app-make",
"raea-core-brief",
"raea-io-home",
"raea-native",
"serde_json",
]
[[package]]
name = "raea-cli-refused"
version = "0.1.0"
dependencies = [
"dunce",
"raea-io-home",
"serde_json",
]
[[package]]
name = "raea-core-alloc"
version = "0.1.0"
@@ -14285,6 +14406,7 @@ version = "0.1.0"
dependencies = [
"serde",
"serde_json",
"sha2 0.10.9",
"ts-rs",
]
@@ -14345,6 +14467,15 @@ dependencies = [
"serde_json",
]
[[package]]
name = "raea-core-modelbox"
version = "0.1.0"
dependencies = [
"bevy",
"raea-core-scene",
"serde_json",
]
[[package]]
name = "raea-core-place"
version = "0.1.0"
@@ -14382,6 +14513,7 @@ version = "0.1.0"
name = "raea-core-shape"
version = "0.1.0"
dependencies = [
"blake3",
"manifold-rust",
"raea-core-fonts",
"raea-core-grow",
@@ -14400,6 +14532,15 @@ dependencies = [
"serde_json",
]
[[package]]
name = "raea-core-tables"
version = "0.1.0"
dependencies = [
"bevy",
"raea-core-program",
"serde_json",
]
[[package]]
name = "raea-core-wire"
version = "0.1.0"
@@ -14408,6 +14549,23 @@ dependencies = [
"serde_json",
]
[[package]]
name = "raea-core-zfight"
version = "0.1.0"
dependencies = [
"bevy",
]
[[package]]
name = "raea-denoise-bench"
version = "0.1.0"
dependencies = [
"image",
"raea-light",
"raea-runtime-bundle",
"serde_json",
]
[[package]]
name = "raea-gpu-device"
version = "0.1.0"
@@ -14717,7 +14875,9 @@ name = "raea-light"
version = "0.1.0"
dependencies = [
"image",
"raea-core-facts",
"raea-io-home",
"raea-io-trace",
"raea-runtime-bundle",
"serde_json",
]
@@ -14798,6 +14958,20 @@ dependencies = [
"wgpu",
]
[[package]]
name = "raea-page-ax"
version = "0.1.0"
dependencies = [
"accesskit 0.24.1",
"bevy",
"blitz-dom",
"raea-runtime-dom",
"raea-sys-a11y",
"raea-sys-page",
"serde_json",
"stylo",
]
[[package]]
name = "raea-page-host"
version = "0.1.0"
@@ -14815,6 +14989,7 @@ dependencies = [
"raea-io-os",
"raea-io-trace",
"raea-page",
"raea-page-ax",
"raea-page-sound",
"raea-page-stage",
"raea-page-window",
@@ -14824,11 +14999,9 @@ dependencies = [
"raea-runtime-js",
"raea-runtime-plugins",
"raea-runtime-view",
"raea-sys-a11y",
"raea-sys-fonts",
"raea-sys-page",
"serde_json",
"stylo",
"tiny_http",
]
@@ -14868,11 +15041,14 @@ name = "raea-page-window"
version = "0.1.0"
dependencies = [
"bevy",
"blitz-traits",
"block2 0.6.2",
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"raea-io-os",
"raea-runtime-js",
"raea-sys-page",
"raw-window-handle",
"serde_json",
"windows 0.62.2",
@@ -14900,34 +15076,68 @@ dependencies = [
"bytemuck",
"dunce",
"image",
"raea-core-facts",
"raea-core-program",
"raea-core-shape",
"raea-gpu-device",
"raea-io-media",
"raea-io-trace",
"raea-render-plugins",
"raea-render-raytrace",
"raea-runtime-gpuframe",
"raea-runtime-plugins",
"raea-runtime-scene3d",
"raea-runtime-view",
"raea-sys-compose",
"raea-sys-compute",
"raea-sys-engine-shaders",
"raea-sys-environment",
"raea-sys-fog",
"raea-sys-frame",
"raea-sys-grass",
"raea-sys-grid",
"raea-sys-hold",
"raea-sys-look",
"raea-sys-matchmove",
"raea-sys-material",
"raea-sys-memtally",
"raea-sys-meshseq",
"raea-sys-page",
"raea-sys-post",
"raea-sys-procmat",
"raea-sys-screen",
"raea-sys-shader",
"raea-sys-splat",
"raea-sys-sprite",
"raea-sys-text3d",
"raea-sys-three-shader",
"raea-sys-toon",
"raea-sys-viewbox",
"serde_json",
"wgpu",
]
[[package]]
name = "raea-render-plugins"
version = "0.1.0"
dependencies = [
"bevy",
"raea-core-program",
"raea-runtime-plugins",
"raea-runtime-scene3d",
"raea-sys-compose",
"raea-sys-compute",
"raea-sys-environment",
"raea-sys-fog",
"raea-sys-fog-half",
"raea-sys-frame",
"raea-sys-framepass",
"raea-sys-gi",
"raea-sys-grass",
"raea-sys-grid",
"raea-sys-hold",
"raea-sys-lod",
"raea-sys-look",
"raea-sys-matchmove",
"raea-sys-material",
"raea-sys-meshseq",
"raea-sys-page",
"raea-sys-parity",
"raea-sys-phase",
"raea-sys-post",
@@ -14941,10 +15151,8 @@ dependencies = [
"raea-sys-sprite",
"raea-sys-text3d",
"raea-sys-three-shader",
"raea-sys-viewbox",
"raea-sys-toon",
"raea-sys-volume",
"serde_json",
"wgpu",
]
[[package]]
@@ -14959,6 +15167,7 @@ dependencies = [
"raea-sys-engine-shaders",
"raea-sys-post",
"raea-sys-rt",
"raea-sys-viewbox",
"serde_json",
"wgpu",
]
@@ -15117,7 +15326,6 @@ version = "0.1.0"
dependencies = [
"dunce",
"junction",
"libc",
"raea-core-scene",
"raea-io-home",
"raea-io-media",
@@ -15125,10 +15333,10 @@ dependencies = [
"raea-native",
"raea-runtime-bundle-lib",
"raea-runtime-cssurls",
"raea-runtime-pid",
"raea-sys-layers",
"regex",
"serde_json",
"windows-sys 0.61.2",
]
[[package]]
@@ -15146,7 +15354,6 @@ name = "raea-runtime-calls"
version = "0.1.0"
dependencies = [
"base64 0.22.1",
"bevy",
"image",
"manifold-rust",
"parley",
@@ -15157,6 +15364,7 @@ dependencies = [
"raea-io-net",
"raea-io-trace",
"raea-native",
"raea-runtime-ecs",
"raea-runtime-plugins",
"raea-runtime-wear",
"raea-sys-fonts",
@@ -15222,6 +15430,14 @@ dependencies = [
"vello",
]
[[package]]
name = "raea-runtime-ecs"
version = "0.1.0"
dependencies = [
"bevy",
"serde_json",
]
[[package]]
name = "raea-runtime-edit"
version = "0.1.0"
@@ -15261,7 +15477,9 @@ version = "0.1.0"
dependencies = [
"raea-core-facts",
"raea-core-scene",
"raea-runtime-lod-plan",
"raea-sys-contact",
"raea-sys-notice",
"raea-sys-stage",
"serde_json",
]
@@ -15291,6 +15509,7 @@ dependencies = [
"raea-runtime-page",
"raea-runtime-pagestore",
"raea-runtime-react",
"raea-runtime-review",
"raea-runtime-scene",
"raea-runtime-scene3d",
"raea-runtime-sound",
@@ -15373,6 +15592,17 @@ dependencies = [
"rquickjs",
]
[[package]]
name = "raea-runtime-kinds"
version = "0.1.0"
dependencies = [
"bevy",
"raea-core-program",
"raea-core-scene",
"raea-runtime-look",
"serde_json",
]
[[package]]
name = "raea-runtime-live"
version = "0.1.0"
@@ -15401,6 +15631,18 @@ dependencies = [
"winit",
]
[[package]]
name = "raea-runtime-lod-plan"
version = "0.1.0"
dependencies = [
"bevy",
"dunce",
"raea-core-facts",
"raea-core-scene",
"raea-sys-stage",
"serde_json",
]
[[package]]
name = "raea-runtime-look"
version = "0.1.0"
@@ -15417,12 +15659,9 @@ version = "0.1.0"
dependencies = [
"base64 0.22.1",
"bevy",
"image",
"raea-core-scene",
"raea-core-wire",
"raea-io-assets",
"raea-io-home",
"raea-io-media",
"raea-io-net",
"raea-page",
"raea-render",
@@ -15431,8 +15670,8 @@ dependencies = [
"raea-runtime-react",
"raea-runtime-twins",
"raea-runtime-view",
"raea-sys-facetrack",
"raea-sys-fonts",
"raea-sys-frame",
"raea-sys-image",
"raea-sys-page",
"raea-sys-screen",
@@ -15449,6 +15688,14 @@ dependencies = [
"twox-hash",
]
[[package]]
name = "raea-runtime-pid"
version = "0.1.0"
dependencies = [
"libc",
"windows-sys 0.61.2",
]
[[package]]
name = "raea-runtime-plugins"
version = "0.1.0"
@@ -15476,6 +15723,7 @@ dependencies = [
"raea-core-alloc",
"raea-core-animate",
"raea-core-scene",
"raea-core-shape",
"raea-core-wire",
"raea-io-assets",
"raea-io-media",
@@ -15500,6 +15748,18 @@ dependencies = [
"raea-sys-light-meter",
"raea-sys-page",
"serde_json",
"xxhash-rust",
]
[[package]]
name = "raea-runtime-review"
version = "0.1.0"
dependencies = [
"image",
"raea-core-facts",
"raea-core-review",
"raea-sys-light-meter",
"serde_json",
]
[[package]]
@@ -15510,6 +15770,7 @@ dependencies = [
"raea-core-program",
"raea-core-review",
"raea-core-scene",
"raea-runtime-kinds",
"raea-runtime-look",
"raea-runtime-scene2d",
"raea-sys-frame",
@@ -15548,6 +15809,7 @@ dependencies = [
"raea-sys-sampler",
"raea-sys-shader",
"raea-sys-share",
"raea-sys-toon",
"serde_json",
]
@@ -15730,6 +15992,17 @@ dependencies = [
"raea-core-animate",
]
[[package]]
name = "raea-sys-atlas"
version = "0.1.0"
dependencies = [
"parry3d",
"raea-core-meshcheck",
"raea-sys-glb",
"rayon",
"serde_json",
]
[[package]]
name = "raea-sys-bake"
version = "0.1.0"
@@ -15819,8 +16092,10 @@ dependencies = [
"bevy",
"raea-core-facts",
"raea-core-meshcheck",
"raea-core-modelbox",
"raea-core-scene",
"raea-core-shape",
"raea-core-zfight",
"raea-io-trace",
"serde_json",
]
@@ -15873,6 +16148,17 @@ dependencies = [
"parry3d",
]
[[package]]
name = "raea-sys-facetrack"
version = "0.1.0"
dependencies = [
"image",
"raea-io-assets",
"raea-io-media",
"raea-sys-frame",
"serde_json",
]
[[package]]
name = "raea-sys-filters"
version = "0.1.0"
@@ -15880,7 +16166,9 @@ dependencies = [
"anyrender",
"anyrender_vello",
"blitz-paint",
"png 0.18.1",
"rustc-hash 2.1.3",
"skrifa 0.44.0",
"vello",
"wgpu",
]
@@ -15924,6 +16212,14 @@ dependencies = [
"serde_json",
]
[[package]]
name = "raea-sys-fixes"
version = "0.1.0"
dependencies = [
"raea-io-home",
"rusqlite",
]
[[package]]
name = "raea-sys-fog"
version = "0.1.0"
@@ -16001,6 +16297,7 @@ dependencies = [
"bevy",
"raea-core-program",
"raea-core-scene",
"raea-core-tables",
"raea-io-media",
"raea-sys-layers",
"raea-sys-shots",
@@ -16013,6 +16310,7 @@ name = "raea-sys-framepass"
version = "0.1.0"
dependencies = [
"bevy",
"raea-sys-compose",
"raea-sys-frame",
"raea-sys-material",
"raea-sys-sampler",
@@ -16170,6 +16468,20 @@ dependencies = [
"serde_json",
]
[[package]]
name = "raea-sys-lightbake"
version = "0.1.0"
dependencies = [
"bytemuck",
"parry3d",
"pollster 0.4.0",
"raea-gpu-device",
"raea-sys-atlas",
"rayon",
"serde_json",
"wgpu",
]
[[package]]
name = "raea-sys-lod"
version = "0.1.0"
@@ -16207,9 +16519,11 @@ version = "0.1.0"
dependencies = [
"base64 0.22.1",
"bevy",
"blake3",
"image",
"intel_tex_2",
"raea-core-program",
"raea-core-shape",
"raea-io-home",
"raea-io-net",
"raea-io-trace",
"raea-sys-frame",
@@ -16223,6 +16537,13 @@ dependencies = [
name = "raea-sys-measure"
version = "0.1.0"
[[package]]
name = "raea-sys-memtally"
version = "0.1.0"
dependencies = [
"bevy",
]
[[package]]
name = "raea-sys-mesh"
version = "0.1.0"
@@ -16253,11 +16574,22 @@ dependencies = [
"raea-io-home",
"raea-io-media",
"raea-io-trace",
"raea-sys-mix-device",
"raea-sys-mix-level",
"raea-sys-tone",
"serde_json",
]
[[package]]
name = "raea-sys-mix-device"
version = "0.1.0"
dependencies = [
"audioadapter-buffers",
"cpal 0.15.3",
"firewheel",
"raea-io-trace",
]
[[package]]
name = "raea-sys-mix-level"
version = "0.1.0"
@@ -16285,6 +16617,27 @@ dependencies = [
"mlx-rs",
]
[[package]]
name = "raea-sys-motionfaults"
version = "0.1.0"
dependencies = [
"glam 0.33.12",
"raea-core-ease",
"raea-sys-body",
"serde_json",
]
[[package]]
name = "raea-sys-notice"
version = "0.1.0"
dependencies = [
"bevy",
"raea-core-ease",
"raea-core-scene",
"raea-io-home",
"serde_json",
]
[[package]]
name = "raea-sys-page"
version = "0.1.0"
@@ -16505,6 +16858,7 @@ name = "raea-sys-splat"
version = "0.1.0"
dependencies = [
"bevy",
"raea-core-ease",
"raea-core-program",
"raea-sys-frame",
"serde_json",
@@ -16570,6 +16924,17 @@ dependencies = [
"serde_json",
]
[[package]]
name = "raea-sys-toon"
version = "0.1.0"
dependencies = [
"bevy",
"raea-core-program",
"raea-core-shape",
"raea-sys-frame",
"serde_json",
]
[[package]]
name = "raea-sys-touch"
version = "0.1.0"
@@ -16590,6 +16955,7 @@ name = "raea-sys-viewbox"
version = "0.1.0"
dependencies = [
"bevy",
"raea-sys-compose",
"raea-sys-frame",
]
@@ -16629,7 +16995,7 @@ version = "0.1.0"
dependencies = [
"image",
"parry3d",
"raea-core-meshcheck",
"raea-sys-atlas",
"raea-sys-damage",
"raea-sys-exposure",
"raea-sys-glb",
@@ -20232,8 +20598,6 @@ dependencies = [
[[package]]
name = "taffy"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c8480887e8803986d96a7173729565520d4bbb721ad6b7ad6941a22897207aa"
dependencies = [
"serde",
"slotmap",
+35
View File
@@ -6,10 +6,13 @@ members = [
"core/animate",
"core/ask",
"core/brief",
"core/zfight",
"core/modelbox",
"core/facts",
"core/ease",
"core/fonts",
"core/program",
"core/tables",
"core/scene",
"core/shape",
"core/meshcheck",
@@ -28,6 +31,7 @@ members = [
"systems/phase",
"systems/shader/wgsl",
"systems/sampler",
"systems/memtally",
"systems/parity",
"systems/shader",
"systems/three-shader",
@@ -39,12 +43,15 @@ members = [
"engine/bevy-world",
"engine/bundle",
"engine/cli",
"engine/cli/goal",
"engine/cli/refused",
"engine/neural",
"engine/light",
"engine/modules",
"engine/native",
"io/npm",
"engine/page",
"engine/page/ax",
"engine/page/host",
"engine/rune",
"engine/rune/page",
@@ -83,6 +90,7 @@ members = [
"systems/tone",
"systems/mix",
"systems/mix/level",
"systems/mix/device",
"systems/ml",
"systems/mlx",
"systems/kimodo",
@@ -91,6 +99,7 @@ members = [
"systems/vision",
"systems/columns",
"systems/index",
"systems/fixes",
"systems/fingerprint",
"systems/fingerprint-use",
"systems/fingerprint-things",
@@ -100,6 +109,8 @@ members = [
"systems/a11y",
"systems/bake",
"systems/contact",
"systems/notice",
"systems/motionfaults",
"systems/light-meter",
"systems/measure",
"systems/canvas",
@@ -116,6 +127,7 @@ members = [
"systems/page-net",
"systems/page-ops",
"systems/frame",
"systems/facetrack",
"systems/engine-shaders",
"systems/shots",
"systems/hold",
@@ -144,6 +156,7 @@ members = [
"systems/look",
"systems/compose",
"systems/material",
"systems/toon",
"systems/mesh",
"systems/post",
"systems/fog",
@@ -165,12 +178,16 @@ members = [
"tools/perceive",
"engine/render",
"engine/render/raytrace",
"engine/render/plugins",
"engine/render/denoise/bench",
"engine/seedling",
"engine/web",
"runtime/react",
"runtime/track",
"runtime/pagestore",
"runtime/review",
"runtime/cssurls",
"runtime/pid",
"bench/bridge",
"bench/bevy-parity",
"bench/lightbench",
@@ -182,25 +199,32 @@ members = [
"runtime/bundle/lib",
"engine/shape-web",
"runtime/calls",
"runtime/ecs",
"runtime/shots",
"runtime/wear",
"runtime/canvas",
"runtime/export",
"runtime/endchecks",
"runtime/lod-plan",
"runtime/live",
"runtime/page",
"runtime/appscreen",
"runtime/sound",
"runtime/look",
"runtime/scene",
"runtime/kinds",
"runtime/scene2d",
"runtime/shared",
"apps/ask",
"apps/lightbake",
"systems/lightbake",
"systems/atlas",
"apps/double",
"apps/check",
"apps/check/cause",
"apps/check/flash",
"apps/check/inbox",
"apps/check/make",
"apps/check/read",
"apps/check/text",
"apps/direction",
@@ -215,14 +239,17 @@ members = [
"apps/engines",
"apps/interchange",
"apps/judge",
"apps/make",
"apps/solid",
"apps/scene",
"apps/voice",
"apps/media",
"apps/targets",
"apps/game",
"apps/capcut",
"apps/layers",
"apps/play",
"apps/playable",
"tools/sdk-props",
"tools/hands-audit",
]
@@ -331,6 +358,10 @@ split-debuginfo = "packed"
[patch.crates-io]
# the MP4 muxer, vendored
muxide = { path = "vendor/muxide" }
# metis-sys 0.3.2 (bevy_pbr's meshlets) with GKlib's own stdint.h and inttypes.h stand-ins used only before Visual
# Studio 2013: Visual Studio 18's stdint.h types int_fast16_t differently, and every C file failed (raea#82; the change
# is marked "raea:" in vendor/GKlib/gk_arch.h). Its test graphs, manual and programs are left out
metis-sys = { path = "vendor/metis-sys" }
# 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:")
@@ -387,6 +418,10 @@ vello_encoding = { path = "vendor/vello_encoding" }
# (changes marked "raea:"): raea-page blends a bevy_ui page as Bevy does (bevy_ui on Blitz). No upstream
# equivalent yet (linebender/vello blends the encoded values).
vello_shaders = { path = "vendor/vello_shaders" }
# taffy 0.15.0 (Blitz's, Bevy UI's, rune-taffy's) with a flex line whose items overflow its container by less than
# Chrome's layout unit, 1/64 px, kept on one line: f32 rounding wrapped items that add up to the container's width
# (changes marked "raea:", raea #252). Back to upstream once Taffy breaks flex lines with a tolerance.
taffy = { path = "vendor/taffy" }
# Firewheel 0.12 on Bevy 0.20: bevy_reflect 0.20 and a glam-33 feature (BillyDM/Firewheel#144; changes marked "raea:")
firewheel = { path = "vendor/firewheel" }
firewheel-core = { path = "vendor/firewheel-core" }
+12 -5
View File
@@ -32,10 +32,10 @@
---
> **0.1.6** (17 November 2026) is the latest release: the engine and the desktop app on macOS (Apple Silicon), Linux
> (x86_64) and, newest and least tested, Windows 10 and 11 (x86_64). raea is young and moves fast, with a release most
> days since 0.1.1 on 11 November: expect rough edges, and tell us what you hit in an
> [issue](https://github.com/shinyobjectz/raea/issues), or from your agent with `raea bug`.
> raea releases experimentally and often, so the newest release is always on
> [Releases](https://github.com/shinyobjectz/raea/releases). The app is unstable for now, especially on Linux and
> Windows: expect rough edges, and tell us what you hit in an [issue](https://github.com/shinyobjectz/raea/issues), or
> from your agent with `raea bug`.
## The app
@@ -80,6 +80,13 @@ The installer puts the `raea` command under `~/.raea`, links it into `~/.local/b
work. Run it again to update. The engine is free and needs no account. Tarballs and checksums are on the
[releases page](https://github.com/shinyobjectz/raea/releases).
Linux release builds also package an x86_64 AppImage of the engine command and
attach it and its SHA256 checksum beside the release archives.
Make it executable with `chmod +x raea-*.AppImage`, then run
`./raea-VERSION-linux-x86_64.AppImage --help` or pass the usual `raea` arguments.
See [the AppImage release recipe](tools/release/README.md#linux-appimage) for build
instructions, runtime requirements and running without FUSE.
On Windows 10 or 11, in PowerShell:
```powershell
@@ -123,7 +130,7 @@ floor (`raea check hello.mp4`). `raea init` starts a project, and `raea --help`
Gaussian splats, and Bevy plugins compiled into the engine. three.js work runs as it's written: a React Three Fiber
scene inside `<R3F>`, or a three.js page's script inside `<Three program>`.
- **Sound.** One mixer for live play and offline render, instruments and effects, and local models for foley and
instrument notes (`raea sao`, `raea tokensynth`).
instrument notes (`raea make sao`, `raea make tokensynth`).
- **Built for agents.** Everything it draws stays queryable as data, so an agent can render a frame, look at it, and
fix what's wrong without a person in the loop.
+2 -23
View File
@@ -6,7 +6,6 @@
//! question, so a verdict reads in its terms and `raea ask try` can reword it.
use std::io::Write as _;
use std::io::{Read as _, Seek as _, SeekFrom};
use std::path::{Path, PathBuf};
use raea_core_ask::{Question, Reading};
@@ -50,28 +49,8 @@ fn hex(digest: &[u8]) -> String {
digest.iter().take(16).map(|b| format!("{b:02x}")).collect()
}
/// What a file is, cheaply: its size and a hash of its first and last MB. A render is known again by its copy in the
/// feed, and a later render to the same path isn't taken for it.
pub fn ident(path: &Path) -> Option<String> {
const MB: u64 = 1 << 20;
let mut f = std::fs::File::open(path).ok()?;
let len = f.metadata().ok()?.len();
let mut h = Sha256::new();
let mut part = vec![0u8; len.min(MB) as usize];
f.read_exact(&mut part).ok()?;
h.update(&part);
if len > 2 * MB {
f.seek(SeekFrom::Start(len - MB)).ok()?;
f.read_exact(&mut part).ok()?;
h.update(&part);
}
Some(format!("{len}-{}", hex(&h.finalize())))
}
/// The size an ident names, to pass over files that can't be it without reading them.
pub fn ident_len(ident: &str) -> Option<u64> {
ident.split_once('-')?.0.parse().ok()
}
/// What a file is, cheaply, and the size an ident names (raea-core-ask, so `raea goal gates` reads the same).
pub use raea_core_ask::ident::{ident, ident_len};
/// One of the record's files written whole, through a temporary file, so a reader never sees half of it.
pub fn write_whole(file: &str, text: &str) -> Result<(), String> {
+1 -1
View File
@@ -18,7 +18,7 @@ use crate::prepare::{self, Piece};
use crate::runner::{self, Entry, Event, Opts};
use crate::{calibrate, record};
pub const USAGE: &str = "raea ask FILE [QUESTION...] [--choose A,B,C] [--grade] [--rate N] [--flag ANSWERS] [--set NAME] [--std ID] [--from S] [--to S] [--at S] [--with FILE2] [--brief brief.ts|none] [--words words.json] [--voice yes|no] [--state TEXT] [--dry] [--json] [--gate [any]] [--jobs N] | ask --batch FILE [--dry] [--json] [--gate [any]] [--jobs N] | ask list [SET] [--json] | ask verdict ANSWER WORD [--eye NAME] | ask calibrate [ID] [--json] | ask try WORDS --like ID [--dry] [--json] [--jobs N] (questions about a piece's picture and sound, answered by clef-omni and paid from your raea plan's pool when the app is signed in, else RAEA_AGENT_KEY's, else your own Cloudflare keys: your own words, or the standard sets (rubric, av, defects, platform, decide); every question about one clip goes in one call, --batch (a JSON list or JSON lines, - for stdin) asks many clips in parallel; --dry says what would be sent and spends nothing; answers are advice until a question is calibrated: verdict labels an answer, calibrate holds each question to your verdicts, notes and approvals, try asks new words of its labelled clips)";
pub const USAGE: &str = "raea ask FILE [QUESTION...] [--choose A,B,C] [--grade] [--rate N] [--flag ANSWERS] [--set NAME] [--std ID] [--from S] [--to S] [--at S] [--with FILE2] [--brief brief.ts|none] [--words words.json] [--voice yes|no] [--state TEXT] [--dry] [--json] [--gate [any]] [--jobs N] | ask --batch FILE [--dry] [--json] [--gate [any]] [--jobs N] | ask list [SET] [--json] | ask verdict ANSWER WORD [--eye NAME] | ask calibrate [ID] [--json] | ask try WORDS --like ID [--dry] [--json] [--jobs N] (questions about a piece's picture and sound, answered by clef-omni and paid from your raea plan's pool when the app is signed in, else RAEA_AGENT_KEY's, else your own Cloudflare keys: your own words, or the standard sets (rubric, av, defects, platform, decide, make); every question about one clip goes in one call, --batch (a JSON list or JSON lines, - for stdin) asks many clips in parallel; --dry says what would be sent and spends nothing; answers are advice until a question is calibrated: verdict labels an answer, calibrate holds each question to your verdicts, notes and approvals, try asks new words of its labelled clips)";
const VALUED: [&str; 17] = ["--choose", "--rate", "--flag", "--set", "--std", "--from", "--to", "--at", "--with", "--brief", "--words", "--voice", "--state", "--jobs", "--batch", "--eye", "--like"];
const BARE: [&str; 4] = ["--grade", "--dry", "--json", "--gate"];
+2
View File
@@ -28,4 +28,6 @@ raea-app-check-text = { path = "text" }
raea-app-check-flash = { path = "flash" }
# what the person sent from the raea app, handed to the agent (split out to keep this crate small)
raea-app-check-inbox = { path = "inbox" }
# the Stop gate for a `make` job (docs/goal.feature MK2; split out to keep this crate small)
raea-app-check-make = { path = "make" }
serde_json = "1"
+44 -3
View File
@@ -55,6 +55,11 @@ fn said(l: &Value) -> String {
"result" => format!("a result{on}: {text}"),
"correction" => format!("a correction{on}: {text}"),
"sign" => format!("a sign-off{on} (ask {})", l["ask"]),
// a show only to be looked at (raea show --fyi), looked at: Got it, with a word or none
"seen" => {
let word = text.strip_prefix("Seen").unwrap_or(&text).trim_start_matches(':').trim();
if word.is_empty() { format!("seen{on}") } else { format!("seen{on}: {word}") }
}
k => format!("{}{on}: {text}", if k.is_empty() { "something" } else { k }),
};
format!("- {what}")
@@ -68,6 +73,17 @@ pub fn told(agent: &str, v: &Value) -> Option<String> {
return None;
}
let list = lines.iter().map(said).collect::<Vec<_>>().join("\n");
// only Got it on what was shown to look at: nothing to take up
if !lines.iter().any(|l| l["kind"] != "seen") {
return Some(format!("raea: the person has looked at what you showed them (your inbox, ~/.raea/inbox/{inbox}.jsonl):\n{list}\nNothing to do about it; carry on."));
}
// a session started again (resumed) after the person wrote to it while it was closed (Shane 11-28: "notes reach
// closed sessions"): what waited is handed over before anything else
if v["hook_event_name"].as_str() == Some("SessionStart") {
return Some(format!(
"raea: while this session was closed, the person sent this from the raea app (your inbox, ~/.raea/inbox/{inbox}.jsonl; marked read, so the app shows it as read):\n{list}\nTake it up first, before anything else. Answer an item with raea show --on ITEM --note LINE, or post the next version with raea show FILE --replaces ITEM."
));
}
Some(format!(
"raea: the person just sent this from the raea app (your inbox, ~/.raea/inbox/{inbox}.jsonl; marked read, so the app shows it as read):\n{list}\nTake it up now, before going on: it may change what you're doing. What you say next shows under your session in their feed; answer an item with raea show --on ITEM --note LINE, or post the next version with raea show FILE --replaces ITEM."
))
@@ -78,11 +94,17 @@ mod tests {
use super::*;
use serde_json::json;
#[test]
fn each_line_is_handed_over_once_and_a_half_written_one_waits() {
let d = std::env::temp_dir().join(format!("raea-inbox-{}", std::process::id()));
/// an empty inbox folder of the test's own
fn scratch(tag: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("raea-inbox-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
#[test]
fn each_line_is_handed_over_once_and_a_half_written_one_waits() {
let d = scratch("once");
let f = d.join("claude-code-abcd1234.jsonl");
std::fs::write(&f, "{\"kind\":\"message\",\"text\":\"more epic\"}\n{\"kind\":\"no").unwrap();
let first = unread(&d, "claude-code-abcd1234");
@@ -97,6 +119,25 @@ mod tests {
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn seen_is_said_as_seen_and_asks_nothing() {
assert_eq!(said(&json!({"kind": "seen", "item": "i-2", "title": "Lobby", "text": "Seen"})), "- seen on item i-2 \"Lobby\"");
assert_eq!(said(&json!({"kind": "seen", "item": "i-2", "title": "Lobby", "text": "Seen: lovely"})), "- seen on item i-2 \"Lobby\": lovely");
}
#[test]
fn what_waited_while_it_was_closed_is_handed_over_as_it_starts_again() {
let d = scratch("start");
std::fs::write(d.join("claude-code-5e55a0ff.jsonl"), "{\"kind\":\"edits\",\"item\":\"i-9\",\"title\":\"Cut\",\"text\":\"tighter open\"}\n").unwrap();
// SAFETY: tests in this crate don't read RAEA_INBOX_DIR concurrently
unsafe { std::env::set_var("RAEA_INBOX_DIR", &d) };
let start = told("claude", &json!({"hook_event_name": "SessionStart", "source": "resume", "session_id": "5e55a0ff-1"})).unwrap();
assert!(start.starts_with("raea: while this session was closed") && start.contains("- edits on item i-9 \"Cut\":\ntighter open"), "{start}");
assert_eq!(told("claude", &json!({"hook_event_name": "UserPromptSubmit", "session_id": "5e55a0ff-1"})), None, "handed over once");
unsafe { std::env::remove_var("RAEA_INBOX_DIR") };
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn the_inbox_is_named_as_raea_show_names_it() {
assert_eq!(name("claude", &json!({"session_id": "15cd6bb0-8829-466f-a28a-bbca3d35be92"})).as_deref(), Some("claude-code-15cd6bb0"));
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "raea-app-check-make"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "`raea hook`'s Stop gate for a `make` job (docs/goal.feature MK36): an agent can't end its turn until `raea goal check --at done` passes"
[dependencies]
serde_json = "1"
# brief.ts found as raea finds a project (plain paths on Windows)
dunce = "1"
# the project's folder (record.rs `up`)
raea-core-facts = { path = "../../../core/facts" }
# the guard's counts, under the home folder
raea-io-home = { path = "../../../io/home" }
+125
View File
@@ -0,0 +1,125 @@
//! raea-app-check-make: the Stop hook's moment of the loop (docs/goal.feature MK36): an agent working in a project with a
//! brief.ts can't end its turn until `raea goal check --at done` passes: every goal the brief holds (or, with none, the
//! floor) and every raea file reached from the brief (`registered`). Run by `raea goal check`, a child process, so this
//! crate carries none of the rules. A session blocked three times with the same open items goes through: it's going in
//! circles, and the person is better told than the agent looped.
use std::hash::{DefaultHasher, Hash, Hasher};
use std::path::{Path, PathBuf};
use serde_json::Value;
/// How many times the same open items may block one session before the stop goes through.
pub const SAME_BLOCKS: u32 = 3;
/// The project's brief.ts, at or above `cwd` inside its raea project: every brief is held, none is an outlier.
pub fn brief_with_job(cwd: &Path) -> Option<PathBuf> {
let project = raea_core_facts::record::up(cwd, ".raea/project");
for d in dunce::canonicalize(cwd).ok()?.ancestors() {
let p = d.join("brief.ts");
if p.is_file() {
return Some(p);
}
if project.as_deref() == Some(d) {
return None;
}
}
None
}
fn hash(parts: &[&str]) -> u64 {
let mut h = DefaultHasher::new();
parts.hash(&mut h);
h.finish()
}
/// Counts this session's blocks on the same open items in `guard` ("<items hash> <count>"); true while it may block.
pub fn may_block(guard: &Path, items: &str) -> bool {
let key = hash(&[items]).to_string();
let count = std::fs::read_to_string(guard).ok().and_then(|t| {
let (k, n) = t.trim().split_once(' ')?;
(k == key).then(|| n.parse::<u32>().ok()).flatten()
});
let next = count.unwrap_or(0) + 1;
let _ = std::fs::create_dir_all(guard.parent().unwrap_or(Path::new(".")));
let _ = std::fs::write(guard, format!("{key} {next}"));
next <= SAME_BLOCKS
}
/// What the agent is told when its turn may not end, or None to let it end: no job here, the job passes, the runner
/// didn't run (never block on raea's own failure), or the same items have blocked it three times already.
pub fn stop(v: &Value) -> Option<String> {
let cwd = PathBuf::from(v["cwd"].as_str()?);
let brief = brief_with_job(&cwd)?;
let exe = std::env::current_exe().ok()?;
let out = std::process::Command::new(exe).args(["goal", "check", "--at", "done", "--json"]).current_dir(brief.parent()?).env("RAEA_RECORD", "off").output().ok()?;
let r: Value = serde_json::from_slice(&out.stdout).ok()?;
let home = raea_io_home::user_home()?;
let session = v["session_id"].as_str().unwrap_or("");
let guard = home.join(".raea/hooks/goal").join(format!("{:x}", hash(&[session, &brief.display().to_string()])));
if r["passed"] == true {
let _ = std::fs::remove_file(&guard);
return None;
}
let items = open_items(&r);
if !may_block(&guard, &items) {
return None;
}
let goals: Vec<String> = r["goals"].as_array().into_iter().flatten().filter(|g| g["passed"] != true).filter_map(|g| g["name"].as_str().map(String::from)).collect();
let open = if goals.is_empty() { String::new() } else { format!("goal {}, ", goals.join(", ")) };
Some(format!("Not done ({open}{}): {items}. Keep going: `raea goal check` lists each with its fix; review/goal.json holds them all.", brief.display()))
}
/// The open items, one line each: each error-level finding (its check and file), then each check that broke.
pub fn open_items(r: &Value) -> String {
let mut items: Vec<String> = r["findings"]
.as_array()
.into_iter()
.flatten()
.filter(|x| x["level"] == "error")
.map(|x| format!("{}{}: {}", x["check"].as_str().unwrap_or(""), x["file"].as_str().map(|f| format!(" {f}")).unwrap_or_default(), x["says"].as_str().unwrap_or("")))
.collect();
for b in r["broke"].as_array().into_iter().flatten() {
items.push(format!("{} broke: {}", b["check"].as_str().unwrap_or(""), b["says"].as_str().unwrap_or("")));
}
items.join("; ")
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn tmp(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("raea-goal-gate-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(d.join("compositions")).unwrap();
d
}
#[test]
fn every_brief_is_held_with_or_without_a_goal() {
let d = tmp("job");
assert_eq!(brief_with_job(&d.join("compositions")), None, "no brief, nothing held");
std::fs::write(d.join("brief.ts"), "export default brief({ title: \"x\" })").unwrap();
assert_eq!(brief_with_job(&d.join("compositions")).map(|p| p.file_name().unwrap().to_owned()), Some("brief.ts".into()), "a brief without a goal is held to the floor and registered");
}
#[test]
fn the_same_open_items_block_three_times_then_go_through() {
let g = tmp("guard").join("g");
assert!(may_block(&g, "a") && may_block(&g, "a") && may_block(&g, "a"));
assert!(!may_block(&g, "a"), "a fourth stop on the same items goes through");
assert!(may_block(&g, "a; b"), "new items start the count again");
}
#[test]
fn open_items_list_each_error_then_each_broken_check() {
let r = json!({"findings": [
{"check": "deliverables", "level": "error", "file": null, "says": "missing: out/kit/lineup.png"},
{"check": "cta", "level": "error", "file": "out/cuts/a_9x16.mp4", "says": "no CTA in its last 8 s"},
{"check": "place", "level": "warn", "file": "out/cuts/a_9x16.mp4", "says": "a warning holds nothing"}],
"broke": [{"check": "mine", "says": "x is undefined"}]});
assert_eq!(open_items(&r), "deliverables: missing: out/kit/lineup.png; cta out/cuts/a_9x16.mp4: no CTA in its last 8 s; mine broke: x is undefined");
}
}
+31 -10
View File
@@ -3,9 +3,10 @@
//! --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. After any tool, and as a turn ends: what the person sent from the raea
//! app (inbox.rs). 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.
//! file is saved: `raea goal check --at edit` on a composition, or on a file under a brief. As a turn ends: `raea
//! goal check --at done` on the brief's goals (apps/check/make). After any tool, and as a turn ends: what the person sent from
//! the raea app (inbox.rs). A stop is exit 2 with the reason on stderr, which every harness hands its agent; the edit
//! moment's findings go back in the shape each one reads.
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
@@ -124,6 +125,12 @@ fn saved(v: &Value) -> Vec<String> {
patch.lines().filter_map(|l| ["*** Add File: ", "*** Update File: "].iter().find_map(|head| l.strip_prefix(head))).map(str::trim).map(String::from).collect()
}
/// Whether a saved file is held at the edit moment: a composition (a .tsx that registers a root), or any file under a
/// brief.ts
fn held_at_edit(p: &Path) -> bool {
(p.extension().is_some_and(|e| e == "tsx") && std::fs::read_to_string(p).is_ok_and(|t| t.contains("registerRoot"))) || p.parent().is_some_and(|d| raea_app_check_make::brief_with_job(d).is_some())
}
/// 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 {
@@ -148,9 +155,17 @@ pub fn hook(args: &[String]) -> R<String> {
let event = v["hook_event_name"].as_str().unwrap_or("");
// what the person sent from the raea app since the last look (inbox.rs): handed over after any tool, and a turn about
// to end goes on to take it up
let sent = if matches!(event, "PostToolUse" | "AfterTool" | "Stop") { crate::inbox::told(agent, &v) } else { None };
let sent = if matches!(event, "PostToolUse" | "AfterTool" | "Stop" | "SessionStart" | "UserPromptSubmit") { crate::inbox::told(agent, &v) } else { None };
// a session starting again, or the person writing to it in its terminal: what they sent from raea while it was
// closed or idle goes in as context first (Claude Code's and Codex's SessionStart and UserPromptSubmit read
// hookSpecificOutput.additionalContext)
if matches!(event, "SessionStart" | "UserPromptSubmit") {
return Ok(sent.map(|t| json!({"hookSpecificOutput": {"hookEventName": event, "additionalContext": t}}).to_string()).unwrap_or_default());
}
if event == "Stop" {
return Ok(sent.map(|s| json!({"decision": "block", "reason": s}).to_string()).unwrap_or_default());
// what the person sent, and a brief whose goals don't pass at done (docs/goal.feature MK36): either keeps the turn going
let reasons: Vec<String> = [sent, raea_app_check_make::stop(&v)].into_iter().flatten().collect();
return Ok(if reasons.is_empty() { String::new() } else { json!({"decision": "block", "reason": reasons.join("\n\n")}).to_string() });
}
let after_tool = matches!(event, "PostToolUse" | "AfterTool");
if let Some(cmd) = shell_command(&v).filter(|_| !after_tool) {
@@ -163,13 +178,19 @@ pub fn hook(args: &[String]) -> R<String> {
}
return Ok(String::new());
}
// the edit moment of the loop (docs/goal.feature MK33): `raea goal check FILE --at edit` on a saved composition, or
// on any file under a brief; a save that passes says nothing
let me = std::env::current_exe().map_err(|e| e.to_string())?;
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));
for path in saved(&v).iter().filter(|p| held_at_edit(Path::new(p))) {
let dir = Path::new(path).parent().filter(|d| d.is_dir()).map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from(v["cwd"].as_str().unwrap_or(".")));
let Ok(out) = std::process::Command::new(&me).args(["goal", "check", "--at", "edit"]).arg(path).current_dir(dir).env("RAEA_RECORD", "off").output() else { continue };
if out.status.code() == Some(1) {
found.extend(String::from_utf8_lossy(&out.stdout).lines().filter(|l| !l.starts_with("PASSED")).map(String::from));
}
}
let quick = (!found.is_empty()).then(|| format!("raea check --quick after this save:\n{}", found.join("\n")));
let text = [sent, quick].into_iter().flatten().collect::<Vec<_>>().join("\n\n");
let edit = (!found.is_empty()).then(|| format!("raea goal check --at edit after this save:\n{}", found.join("\n")));
let text = [sent, edit].into_iter().flatten().collect::<Vec<_>>().join("\n\n");
Ok(if text.is_empty() { String::new() } else { after(agent, &text) })
}
+1 -1
View File
@@ -218,7 +218,7 @@ fn report(video: &str, issues: Vec<Issue>, more: Vec<Finding>, passed: Vec<Strin
std::fs::write(out, serde_json::to_string_pretty(&j).unwrap()).map_err(|e| format!("{out}: {e}"))?;
}
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
// kept in its project's record beside its renders (DR3), what `raea findings` and `raea goal 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) {
+3 -3
View File
@@ -199,19 +199,19 @@ pub(crate) fn blotching_from(video: &str, probe: &Probe, scores: &[Option<f64>],
}
}
/// Caption contrast: at each text's middle frame, the pixels behind it against its colour, at least 3:1. The pixels
/// Caption contrast: at each text's middle frame, the pixels behind it where it is on that frame 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>) {
let (sx, sy) = (probe.w / w, probe.h / h);
let mut low = 0;
let mut measured = 0;
for r in runs.iter().filter(|r| r.size >= 20.0).take(80) {
let [x, y, bw, bh] = r.box_;
let (t, [x, y, bw, bh]) = r.middle(probe.fps);
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;
// the same measure `raea world` joins to a text from its render (raea-sys-measure, DR2)
let ratio = if crate::read::native() { crate::read::contrast(video, t, crop, &r.color) } else { raea_sys_measure::contrast(std::path::Path::new(video), t, crop, &r.color) };
let Some(ratio) = ratio else { continue };
+12
View File
@@ -420,3 +420,15 @@ fn things_found_are_findings_and_an_unknown_rule_is_not() {
let _ = std::fs::remove_file(&p);
assert_eq!(passed.len(), 1, "nothing found is a pass");
}
/// #236: a text that moves is read where it is on its middle frame, not where it ends.
#[test]
fn a_moving_text_is_read_where_it_is() {
let ink = |f: usize| [56.7 + 4.0 * f as f64, 1000.0, 26.7, 40.0];
let run = Run { text: "E".into(), from: 0.0, to: 8.0, box_: [996.0, 1000.0, 60.0, 40.0], boxes: (0..240).map(ink).collect(), color: String::new(), size: 40.0 };
let (t, b) = run.middle(30.0);
assert_eq!(t, 4.0);
assert!((b[0] - 520.0).abs() < 1e-9 && b[1..] == [1000.0, 60.0, 40.0], "{b:?}");
let still = Run { boxes: vec![ink(0); 240], box_: [40.0, 1000.0, 60.0, 40.0], ..run };
assert_eq!(still.middle(30.0), (4.0, [40.0, 1000.0, 60.0, 40.0]));
}
+12
View File
@@ -47,6 +47,18 @@ pub struct Run {
pub size: f64,
}
impl Run {
/// The frame midway through those that show its whole text, and its box on that frame: `box_` (the last frame's)
/// moved back by how far its letters travel from there to where they end. A text that moves was read at its last
/// place on its middle frame (#236).
pub fn middle(&self, fps: f64) -> (f64, [f64; 4]) {
let n = self.boxes.len();
let (Some(last), true) = (self.boxes.last(), fps > 0.0 && n > 1) else { return ((self.from + self.to) / 2.0, self.box_) };
let (at, [x, y, w, h]) = (self.boxes[n / 2], self.box_);
(self.to - (n - n / 2) as f64 / fps, [x + at[0] - last[0], y + at[1] - last[1], w, h])
}
}
/// The brand kit the cut was styled from (brand/ at or above the manifest's or the video's folder, as render finds
/// brand.css): a kit `raea brand` read from a thin fetch that nobody corrected by hand is a placeholder, P1; a brand.css
/// with no brand.json beside it wasn't read from the brand at all, P2
+98 -5
View File
@@ -240,6 +240,16 @@ fn check_one(tsx: &Path, id: Option<String>, rules: &[Rule], args: &[String], wh
None => hows.iter().filter(|(_, h)| matches!(h, How::Named(n) if n.render && n.name != "text-read")).for_each(|(r, _)| needs(&mut waits, r)),
}
}
// traced light held still (raea light steady): with the floor, a composition lit by Solari carries what its newest
// hold of each frame found, kept in the project's record; with none yet, it waits for one
if floor && traced(tsx) {
let held = light_held(tsx, id.as_deref());
if held.is_empty() {
let c = id.as_ref().map(|i| format!(" --composition {i}")).unwrap_or_default();
waits.push(("light-steady".into(), format!("a held frame of its traced light (raea light steady {}{c} --frame N -o DIR)", tsx.display())));
}
found.extend(held.into_iter().filter(|f| f.level != Level::Note));
}
// the project's own checks, in one run
let mut files: Vec<PathBuf> = Vec::new();
let mut plan = Vec::new();
@@ -249,10 +259,7 @@ fn check_one(tsx: &Path, id: Option<String>, rules: &[Rule], args: &[String], wh
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 k = file_index(&mut files, &m.file);
let mut on = m.frames.pick(&worlds);
if let (true, Some(j)) = (m.render, &join_on_of(&worlds)) {
on.retain(|f| j.contains(f));
@@ -272,6 +279,55 @@ fn check_one(tsx: &Path, id: Option<String>, rules: &[Rule], args: &[String], wh
Ok(Checked { file: tsx.to_path_buf(), id, found: finding::ranked(found), waits, render, shots, fps })
}
/// Whether a composition is lit by traced light: its file, or a .tsx beside it or a folder down, names SolariLighting.
fn traced(tsx: &Path) -> bool {
let mut files = vec![tsx.to_path_buf()];
let tsxs = |d: &Path| -> Vec<PathBuf> { std::fs::read_dir(d).into_iter().flatten().flatten().map(|e| e.path()).collect() };
if let Some(dir) = tsx.parent() {
files.extend(tsxs(dir).into_iter().flat_map(|p| if p.is_dir() { tsxs(&p) } else { vec![p] }).filter(|p| p.extension().is_some_and(|x| x == "tsx")));
}
for f in files {
if let Ok(text) = std::fs::read_to_string(&f) {
if text.contains("SolariLighting") {
return true;
}
}
}
false
}
/// The findings of the newest hold of each frame of a composition (`raea light steady`), from its project's record.
fn light_held(tsx: &Path, id: Option<&str>) -> Vec<Finding> {
let Some(project) = dunce::canonicalize(tsx).ok().and_then(|t| record::up(t.parent()?, ".raea/project")) else { return Vec::new() };
let of = record::rel(&project, tsx);
let mut newest: std::collections::BTreeMap<i64, Vec<Finding>> = std::collections::BTreeMap::new();
for e in record::read(&project) {
if e.by != "raea light steady" || e.of != of {
continue;
}
let mut mine = Vec::new();
for f in e.findings {
let mut about = f.about.iter().map(|a| a.name.as_str());
if id.is_none_or(|id| about.any(|n| n == id)) {
mine.push(f);
}
}
if let Some(frame) = mine.first().and_then(|f| f.frames) {
newest.insert(frame[0], mine);
}
}
newest.into_values().flatten().collect()
}
/// Where `f` is in `files`, added at the end when it isn't yet: the one run's checks, each file once.
fn file_index(files: &mut Vec<PathBuf>, f: &Path) -> usize {
if let Some(at) = files.iter().position(|x| x == f) {
return at;
}
files.push(f.to_path_buf());
files.len() - 1
}
/// 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 {
@@ -325,6 +381,9 @@ pub fn check(args: &[String], host: &Host) -> R<(String, bool)> {
return Err(format!("--only {only}: no rule here has that id"));
}
}
if target.is_file() && target.to_string_lossy().ends_with(".story.ts") {
return check_story(&target, &rules, unread, args, host);
}
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();
@@ -351,7 +410,7 @@ pub fn check(args: &[String], host: &Host) -> R<(String, bool)> {
// 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
// kept in its project's record (DR3), what raea findings and raea goal 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));
}
@@ -363,6 +422,40 @@ pub fn check(args: &[String], host: &Host) -> R<(String, bool)> {
Ok((out.join("\n"), bad))
}
/// `raea check NAME.story.ts` (docs/story.feature ST5a): a story checked before anything is drawn. Every rule whose .ts
/// check reads stories (`over: "story"` or `"both"`) runs once with no frames, so only its `after` speaks; the check
/// imports the story it holds (raea/story's storyCheck), and the file named says which project and that no composition
/// is wanted.
fn check_story(file: &Path, rules: &[Rule], unread: Vec<Finding>, args: &[String], host: &Host) -> R<(String, bool)> {
let (mut found, mut files, mut plan) = (Vec::new(), Vec::<PathBuf>::new(), Vec::new());
for r in rules {
let Some(f) = r.file() else { continue };
match ts::meta(f, &host.ts) {
Ok(m) if m.story => {
let k = file_index(&mut files, &m.file);
plan.push(ts::Planned { check: k, frames: Vec::new(), values: r.values.clone(), level: r.level, by: r.by.clone() });
}
Ok(_) => {}
Err(e) => found.push(Finding::new(&r.id, Level::Error, e, &r.by)),
}
}
if plan.is_empty() {
found.push(Finding::new("story", Level::Note, "no check here reads a story: a .ts check over \"story\" or \"both\" (raea/story's storyCheck is one) named in taste.ts", "raea check"));
}
found.extend(ts::run(&files, &plan, &[], &host.ts)?);
let found = finding::ranked(found);
let bad = unread.iter().chain(&found).any(|f| f.level == Level::Error);
if args.iter().any(|a| a == "--json") {
return Ok((serde_json::to_string_pretty(&json!({"unread": unread, "story": file, "findings": found})).unwrap_or_default(), bad));
}
let mut out: Vec<String> = unread.iter().map(Finding::line).collect();
out.push(format!("raea check {} (a story: no frames)", file.display()));
out.extend(found.iter().map(Finding::line));
let every: Vec<Finding> = unread.into_iter().chain(found).collect();
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: ")
+1 -1
View File
@@ -28,7 +28,7 @@ const LEVELS: f32 = 96.0;
const SHARE: f64 = 1e-4;
const LEAST: usize = 64;
/// The flags of the render the stills repeat (each takes a value, then the bare ones): what it draws and at what size
const KEEP: [&str; 9] = ["--composition", "--w", "--h", "--fps", "--frames", "--words", "--perception", "--input", "--stage"];
const KEEP: [&str; 12] = ["--composition", "--w", "--h", "--fps", "--frames", "--words", "--perception", "--input", "--stage", "--props", "--scale", "--hold"];
const KEEP_BARE: [&str; 2] = ["--clay", "--lite"];
const BY: &str = "raea render (frame-pure)";
+8 -1
View File
@@ -27,6 +27,8 @@ pub struct Meta {
pub render: bool,
pub level: Level,
pub frames: Frames,
/// it runs on a story with no frames (`over: "story" | "both"`): what `raea check NAME.story.ts` runs
pub story: bool,
}
/// The declaration of the check `file`'s default export is.
@@ -46,7 +48,12 @@ pub fn meta(file: &Path, host: &Host) -> R<Meta> {
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 })
let story = match s("over").as_deref() {
None | Some("frames") => false,
Some("story" | "both") => true,
Some(o) => return Err(format!("{name}: a check is over \"frames\", \"story\" or \"both\", not \"{o}\"")),
};
Ok(Meta { file: file.to_path_buf(), id, text: s("text").unwrap_or_default(), render, level, frames, story })
}
/// One planned run: the check (its index in `files`), its frames, and its rule's values, level (None: the check's
+8 -2
View File
@@ -99,13 +99,18 @@ fn shape(expr: &str, out: &Path, meshes: &mut BTreeMap<String, String>) -> R<Val
Some(f) => f.clone(),
None => {
let f = format!("meshes/mesh{k}.glb");
// export() empties meshes/ before the parts are walked, so the folder is made here, where a file first needs it
let dir = out.join("meshes");
if let Err(e) = std::fs::create_dir_all(&dir) {
return Err(format!("{}: {e}", dir.display()));
}
// and as an .obj, which Godot imports as a mesh of its own (a .glb comes in as a scene)
let (glb, obj) = (out.join(&f).to_string_lossy().into_owned(), out.join(f.replace(".glb", ".obj")).to_string_lossy().into_owned());
match expr.strip_prefix("buffer:") {
// a mesh given by its own vertices (a <BufferMesh>, a three.js geometry through raea/r3f): written as it
// is, with its normals and texture coordinates, since it needn't be a closed solid
Some(b) => {
let (t, uv) = raea_core_shape::buffer_tris(b)?;
let (t, uv) = raea_core_shape::buffer_tris(&raea_core_shape::buffer_json(b)?)?;
raea_core_shape::export_tris(&t, uv.as_deref(), &glb, "glb")?;
raea_core_shape::export_tris(&t, uv.as_deref(), &obj, "obj")?;
}
@@ -312,7 +317,8 @@ mod tests {
#[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();
// no meshes/ beforehand, as export() leaves it: shape() makes it (it once failed every solid in a fresh export)
std::fs::create_dir_all(&out).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");
+57 -12
View File
@@ -9,13 +9,58 @@ use std::path::Path;
use serde_json::{Map, Value, json};
use crate::rubric::SCORES;
use crate::rubric::{BAR, scores};
pub const BY: [&str; 2] = ["kimi", "claude"];
/// The judge prompt: the sheets by name, the brief's words, and the JSON to answer.
pub fn prompt(dir: &Path, brief: &Value, target: Option<&Path>) -> String {
let words = ["look", "logline", "notDoing"].iter().filter_map(|k| brief.get(*k).map(|v| format!("{k}: {}", v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())))).collect::<Vec<_>>().join("; ");
/// The judge prompt: the sheets by name, the brief's words, and the JSON to answer. A `raea make` job's kind asks its
/// own categories and the bar (docs/goal.feature MK5); none asks the rubric raea judge has always asked.
pub fn prompt(kind: Option<&str>, dir: &Path, brief: &Value, target: Option<&Path>) -> String {
match kind {
None => prompt_default(dir, brief, target),
Some(k) => prompt_kind(k, dir, brief, target),
}
}
fn brief_words(brief: &Value) -> String {
["look", "logline", "notDoing"].iter().filter_map(|k| brief.get(*k).map(|v| format!("{k}: {}", v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())))).collect::<Vec<_>>().join("; ")
}
fn prompt_kind(kind: &str, dir: &Path, brief: &Value, target: Option<&Path>) -> String {
let words = brief_words(brief);
let target = target.map(|t| format!(" The reference, what it must read as, is {}.", t.display())).unwrap_or_default();
let d = dir.display();
let sheets = match kind {
"shot" => format!("This round's sheet: {d}/framing.png. Each row is one shot: its first, middle and last frame, left to right, each stamped with its name and time. Open it."),
_ => format!(
"This round's sheets: {d}/colour.png and {d}/clay.png, each six tiles, left to right, top to bottom: hero, front, right, top, iso, low (0.3 m off the floor). Clay is every surface light grey and matte. Open both{}.",
if kind == "kit" { "; the scene is the kit's lineup, its props side by side with a scale bar" } else { "" }
),
};
let blind = if kind == "shot" {
String::new()
} else {
format!("PART 1, BLIND: open {d}/hero-colour.png first, one frame. In one sentence: what is this, what era? List five objects you can name. Is it a photograph or a render, and which three tells decided it?\n\n")
};
let cats: String = scores(Some(kind)).iter().map(|(k, on, ask)| format!("- {k}{}: {}\n", if *on == "clay" { " (judged on CLAY)" } else { "" }, ask.split_once(": ").map(|(_, r)| r).unwrap_or(ask))).collect();
let json_scores = scores(Some(kind)).iter().map(|(k, _, _)| format!("\"{k}\": 0")).collect::<Vec<_>>().join(", ");
format!(
"You review a {kind} from images only, as the person who will use it would. You have never seen how it was built and you never will. \
Judge what is in the pixels; do not guess at intentions. Only look at images; change no file.\n\n{blind}\
PART 2, SCORED. The brief: \"{words}\".{target} {sheets}\n\n\
Score each 0-10 (5 = a believable draft; 7 = a production base an artist would accept; 9 = indistinguishable from real). Halves are allowed.\n{cats}\n\
{BAR} Each defect field is one short sentence; \"blocking\" means someone using this would notice it where it will be seen. \
Name exactly what gives it away (not \"the phone looks fake\" but \"the handset is fused to the cradle with no gap\").\n\n\
End your answer with only this JSON, nothing after it:\n\
{{\"blind\": {{\"place\": \"\", \"objects\": [], \"photo\": \"yes|no\", \"tells\": []}}, \
\"scores\": {{{json_scores}}}, \
\"defects\": [{{\"tile\": \"\", \"where\": \"\", \"wrong\": \"\", \"real\": \"\", \"fix\": \"\", \"level\": \"blocking|detail\"}}], \
\"show_as_is\": \"\"}}"
)
}
fn prompt_default(dir: &Path, brief: &Value, target: Option<&Path>) -> String {
let words = brief_words(brief);
let target = target.map(|t| format!(" The target picture, what it must read as, is {}.", t.display())).unwrap_or_default();
format!(
"You review a 3D scene from images only, as the person who will use it would. You have never seen how it was built and you never will. \
@@ -57,13 +102,13 @@ pub fn last_verdict(text: &str) -> Option<Value> {
None
}
/// The verdict read into the judge's own shape: scores (0-10, the seven categories), defects (present, level, named
/// The verdict read into the judge's own shape: scores (0-10, the kind's categories), defects (present, level, named
/// by what is wrong), the blind read's photo (1 a photo, 0 a render) and the agent's own words.
pub fn read(v: &Value) -> (Map<String, Value>, Vec<Value>, Value) {
let mut scores = Map::new();
for (k, _, _) in SCORES {
pub fn read(kind: Option<&str>, v: &Value) -> (Map<String, Value>, Vec<Value>, Value) {
let mut out = Map::new();
for &(k, _, _) in scores(kind) {
if let Some(x) = v["scores"][k].as_f64().filter(|x| (0.0..=10.0).contains(x)) {
scores.insert(k.into(), json!(x));
out.insert(k.into(), json!(x));
}
}
let defects = v["defects"].as_array().into_iter().flatten().filter(|d| d["wrong"].as_str().is_some_and(|w| !w.trim().is_empty())).map(|d| {
@@ -77,15 +122,15 @@ pub fn read(v: &Value) -> (Map<String, Value>, Vec<Value>, Value) {
Some(p) if p.starts_with('n') => json!(0.0),
_ => Value::Null,
};
(scores, defects, photo)
(out, defects, photo)
}
/// One fresh judging session by `by` over DIR's sheets: its verdict JSON. Its steps stream (kimi's stream-json), each
/// said on stderr as it comes, so a watcher sees it working through a judgement that can take minutes.
pub fn ask(by: &str, dir: &Path, brief: &Value, target: Option<&Path>) -> Result<Value, String> {
pub fn ask(kind: Option<&str>, by: &str, dir: &Path, brief: &Value, target: Option<&Path>) -> Result<Value, String> {
use std::io::BufRead as _;
let dir = dunce::canonicalize(&dir).map_err(|e| format!("judge: {}: {e}", dir.display()))?;
let p = prompt(&dir, brief, target);
let p = prompt(kind, &dir, brief, target);
let mut cmd = match by {
"kimi" => {
let mut c = std::process::Command::new("kimi");
+40 -22
View File
@@ -10,15 +10,26 @@ use std::path::PathBuf;
use serde_json::{Map, Value, json};
use crate::rubric::{SCORES, pass};
use crate::rubric::{pass_for, scores};
fn home() -> PathBuf {
raea_io_home::env_path("RAEA_JUDGE_DIR", ".raea/judge")
}
/// The calibration in force, if one was made.
pub fn calibration() -> Option<Value> {
serde_json::from_str(&std::fs::read_to_string(home().join("calibration.json")).ok()?).ok()
/// A kind's calibration file: calibration.json for the default rubric, calibration.KIND.json for a `raea make` kind's
/// (docs/goal.feature MK6), each fitted on that kind's rounds alone.
fn file_of(kind: Option<&str>) -> PathBuf {
home().join(kind.map_or_else(|| "calibration.json".to_string(), |k| format!("calibration.{k}.json")))
}
/// The calibration in force for a kind, if one was made.
pub fn calibration(kind: Option<&str>) -> Option<Value> {
serde_json::from_str(&std::fs::read_to_string(file_of(kind)).ok()?).ok()
}
/// A row's or a verdict's kind: none for the default rubric.
fn kind_in(v: &Value) -> Option<&str> {
v["kind"].as_str()
}
/// The judge's scores mapped through the calibration's lines, kept to 0-10.
@@ -33,15 +44,17 @@ pub fn apply(c: &Value, scores: &mut Map<String, Value>) {
pub fn record(args: &[String]) -> Result<String, String> {
let dir = args.get(2).map(PathBuf::from).ok_or("raea judge eye DIR CATEGORY=SCORE... [--pass yes|no]")?;
let verdict: Value = serde_json::from_str(&std::fs::read_to_string(dir.join("judge.json")).map_err(|_| format!("judge eye: no {}: judge the round first (raea judge {})", dir.join("judge.json").display(), dir.display()))?).map_err(|e| e.to_string())?;
let kind = kind_in(&verdict);
let cats = scores(kind);
// an agent's reading as the eye (`--by kimi`): a fresh session's scores, and its pass by the same rule in code
if let Some(by) = args.iter().position(|a| a == "--by").and_then(|i| args.get(i + 1)) {
let v = crate::agent::ask(by, &dir, &json!({}), None)?;
let (eye, defects, _) = crate::agent::read(&v);
if eye.len() < SCORES.len() {
return Err(format!("judge eye: {by} scored only {} of {} categories", eye.len(), SCORES.len()));
let v = crate::agent::ask(kind, by, &dir, &json!({}), None)?;
let (eye, defects, _) = crate::agent::read(kind, &v);
if eye.len() < cats.len() {
return Err(format!("judge eye: {by} scored only {} of {} categories", eye.len(), cats.len()));
}
let eye_pass = pass(&eye, &defects).0;
let row = json!({"dir": verdict["dir"], "by": by, "judge": verdict["raw"], "judge_pass": verdict["pass"], "defects": verdict["defects"], "eye": eye, "eye_pass": eye_pass, "eye_defects": defects});
let eye_pass = pass_for(kind, &eye, &defects).0;
let row = json!({"dir": verdict["dir"], "kind": kind, "by": by, "judge": verdict["raw"], "judge_pass": verdict["pass"], "defects": verdict["defects"], "eye": eye, "eye_pass": eye_pass, "eye_defects": defects});
append(&row)?;
let shown: Vec<String> = eye.iter().map(|(k, v)| format!("{k} {v}")).collect();
return Ok(format!("APPLIED {by}'s eye on {} recorded ({}): {}; raea judge calibrate fits clef to it", dir.display(), if eye_pass { "a pass" } else { "not yet" }, shown.join(", ")));
@@ -56,8 +69,8 @@ pub fn record(args: &[String]) -> Result<String, String> {
continue;
}
let (k, v) = args[i].split_once('=').ok_or_else(|| format!("judge eye: {:?} isn't CATEGORY=SCORE", args[i]))?;
if !SCORES.iter().any(|s| s.0 == k) {
return Err(format!("judge eye: no category {k}: {}", SCORES.iter().map(|s| s.0).collect::<Vec<_>>().join(", ")));
if !cats.iter().any(|s| s.0 == k) {
return Err(format!("judge eye: no category {k}: {}", cats.iter().map(|s| s.0).collect::<Vec<_>>().join(", ")));
}
let x: f64 = v.parse().ok().filter(|x| (0.0..=10.0).contains(x)).ok_or_else(|| format!("judge eye: {k} is a score 0-10, got {v:?}"))?;
eye.insert(k.into(), json!(x));
@@ -67,8 +80,8 @@ pub fn record(args: &[String]) -> Result<String, String> {
return Err("judge eye: give your scores, e.g. composition=6 form=5 assembly=7 materials=4 light=6 detail=5 world=6".into());
}
// his pass: as he says it, else the same rule on his scores with the judge's defects
let eye_pass = said_pass.unwrap_or_else(|| pass(&eye, verdict["defects"].as_array().map(Vec::as_slice).unwrap_or(&[])).0);
let row = json!({"dir": verdict["dir"], "by": "shane", "judge": verdict["raw"], "judge_pass": verdict["pass"], "defects": verdict["defects"], "eye": eye, "eye_pass": eye_pass});
let eye_pass = said_pass.unwrap_or_else(|| pass_for(kind, &eye, verdict["defects"].as_array().map(Vec::as_slice).unwrap_or(&[])).0);
let row = json!({"dir": verdict["dir"], "kind": kind, "by": "shane", "judge": verdict["raw"], "judge_pass": verdict["pass"], "defects": verdict["defects"], "eye": eye, "eye_pass": eye_pass});
append(&row)?;
Ok(format!("APPLIED your eye on {} recorded ({}): raea judge calibrate fits the judge to it", dir.display(), if eye_pass { "a pass" } else { "not yet" }))
}
@@ -94,10 +107,11 @@ fn fit(xy: &[(f64, f64)]) -> (f64, f64) {
(a, my - a * mx)
}
/// The fit over rows of {judge, eye, defects, eye_pass}: per-category maps and errors, and the pass agreement.
pub fn fit_rows(rows: &[Value]) -> Value {
/// The fit over a kind's rows of {judge, eye, defects, eye_pass} (none: the default rubric's): per-category maps and
/// errors, and the pass agreement.
pub fn fit_rows_for(kind: Option<&str>, rows: &[Value]) -> Value {
let mut maps = Map::new();
for (k, _, _) in SCORES {
for &(k, _, _) in scores(kind) {
let xy: Vec<(f64, f64)> = rows.iter().filter_map(|r| Some((r["judge"][k].as_f64()?, r["eye"][k].as_f64()?))).collect();
if xy.len() < 2 {
continue;
@@ -112,7 +126,7 @@ pub fn fit_rows(rows: &[Value]) -> Value {
for r in rows {
let mut s = r["judge"].as_object().cloned().unwrap_or_default();
apply(&cal, &mut s);
let p = pass(&s, r["defects"].as_array().map(Vec::as_slice).unwrap_or(&[])).0;
let p = pass_for(kind, &s, r["defects"].as_array().map(Vec::as_slice).unwrap_or(&[])).0;
if Value::Bool(p) == r["eye_pass"] {
agree += 1;
}
@@ -126,16 +140,20 @@ pub fn fit_rows(rows: &[Value]) -> Value {
}
pub fn calibrate(args: &[String]) -> Result<String, String> {
let rows: Vec<Value> = std::fs::read_to_string(home().join("eye.jsonl")).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect();
let kind = crate::kind_of(args)?;
let kind = kind.as_deref();
let rows: Vec<Value> = std::fs::read_to_string(home().join("eye.jsonl")).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).filter(|r: &Value| kind_in(r) == kind).collect();
if rows.is_empty() {
return Err("judge calibrate: no rounds with your eye yet (raea judge eye DIR form=5 ...)".into());
let k = kind.map(|k| format!(" of a {k}")).unwrap_or_default();
return Err(format!("judge calibrate: no rounds{k} with your eye yet (raea judge eye DIR form=5 ...)"));
}
let mut cal = fit_rows(&rows);
let mut cal = fit_rows_for(kind, &rows);
cal["kind"] = json!(kind);
let mut eyes: Vec<String> = rows.iter().map(whose).map(str::to_string).collect();
eyes.sort();
eyes.dedup();
cal["eyes"] = json!(eyes);
std::fs::write(home().join("calibration.json"), serde_json::to_string_pretty(&cal).unwrap_or_default()).map_err(|e| e.to_string())?;
std::fs::write(file_of(kind), serde_json::to_string_pretty(&cal).unwrap_or_default()).map_err(|e| e.to_string())?;
if args.iter().any(|a| a == "--json") {
return Ok(serde_json::to_string_pretty(&cal).unwrap_or_default());
}
+51 -22
View File
@@ -2,15 +2,24 @@
//! fresh every round and blind to the code, with the pass decided here in code. Until it is calibrated against Shane's
//! eye (`raea judge eye`, `raea judge calibrate`, eye.rs) its verdict is advice: `gating` says which.
//!
//! raea judge DIR [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry]
//! raea judge DIR [--kind scene|kit|shot] [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry]
//! raea judge eye DIR composition=6 form=5 ... [--pass yes|no] (or --by kimi: an agent's reading as the eye)
//! raea judge calibrate [--json]
//! raea judge calibrate [--kind scene|kit|shot] [--json]
//!
//! `--kind` asks a `raea make` job's own rubric (docs/goal.feature MK5): a scene's, a kit's or a shot list's categories,
//! with the bar AnyKit's critic is given; each kind is calibrated on its own rounds (MK6).
//!
//! DIR/judge.json is the verdict; DIR's parent's judge.log.jsonl holds every round's, so "done" (two passes in a row,
//! each a fresh call) and the stall (the mean up by less than a point over two rounds) are read from it.
mod agent;
mod eye;
/// Whether the judge's score gates a `raea make` kind's jobs: its calibration (`raea judge calibrate --kind KIND`)
/// agreed with the person's eye (docs/goal.feature MK6).
pub fn kind_gates(kind: &str) -> bool {
eye::calibration(Some(kind)).is_some_and(|c| c["gate"] == true)
}
pub mod rubric;
pub use agent::BY;
@@ -21,7 +30,16 @@ use raea_core_facts::{Finding, Level, finding};
use raea_runtime_bundle::flag;
use serde_json::{Value, json};
pub const USAGE: &str = "raea judge DIR [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR (CATEGORY=SCORE ... [--pass yes|no] | --by kimi|claude) | judge calibrate [--json] (a --review folder's sheets judged blind: clef-omni on the frozen rubric, or a fresh kimi or claude session on the judge prompt; the pass decided in code; clef advises until calibrated against your eye or an agent's)";
pub const USAGE: &str = "raea judge DIR [--kind scene|kit|shot] [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR (CATEGORY=SCORE ... [--pass yes|no] | --by kimi|claude) | judge calibrate [--kind scene|kit|shot] [--json] (a --review folder's sheets judged blind: clef-omni on the frozen rubric, or a fresh kimi or claude session on the judge prompt; --kind asks a scene, kit or shot goal's own rubric (a shot list's framing.png); the pass decided in code; clef advises until calibrated against your eye or an agent's, each kind on its own)";
/// `--kind`, checked: one of the rubric's kinds, or none (the default rubric).
pub fn kind_of(args: &[String]) -> Result<Option<String>, String> {
match flag(args, "--kind") {
None => Ok(None),
Some(k) if rubric::KINDS.contains(&k.as_str()) => Ok(Some(k)),
Some(k) => Err(format!("judge: --kind {k}: the kinds are {}", rubric::KINDS.join(", "))),
}
}
/// One call through raea's one clef client (raea-io-clef: the person's plan first, then their own Cloudflare keys),
/// with the rubric's questions as written and each sheet as a JPEG still.
@@ -40,7 +58,7 @@ fn brief_of(path: Option<&str>) -> Result<Value, String> {
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let out = std::process::Command::new(exe).args(["spec", p, "--as", "brief"]).output().map_err(|e| e.to_string())?;
let text = String::from_utf8_lossy(&out.stdout);
let start = text.find('{').ok_or_else(|| format!("judge: {p} didn't read as a brief: {}", String::from_utf8_lossy(&out.stderr).lines().last().unwrap_or("")))?;
let start = text.find('{').ok_or_else(|| format!("judge: {p} didn't read as a brief: {}", why_refused(&out)))?;
let v: Value = serde_json::from_str(&text[start..]).map_err(|e| format!("judge: {p}: {e}"))?;
Ok(v.get("brief").cloned().unwrap_or(v))
}
@@ -76,10 +94,14 @@ pub fn cli(args: &[String]) -> Result<String, String> {
None => return Err(USAGE.into()),
}
let dir = PathBuf::from(&args[1]);
let (colour, clay, hero) = (dir.join("colour.png"), dir.join("clay.png"), dir.join("hero-colour.png"));
for f in [&colour, &clay] {
let kind = kind_of(args)?;
let kind = kind.as_deref();
let hero = dir.join("hero-colour.png");
let sheets: Vec<(&str, PathBuf)> = rubric::sheets(kind).iter().map(|(s, f)| (*s, dir.join(f))).collect();
for (_, f) in &sheets {
if !f.is_file() {
return Err(format!("judge: no {} (make the sheets with raea render EDIT.tsx --review {})", f.display(), dir.display()));
let make = if kind == Some("shot") { format!("raea make framing --out {}", dir.display()) } else { format!("raea render EDIT.tsx --review {}", dir.display()) };
return Err(format!("judge: no {} (make the sheets with {make})", f.display()));
}
}
let brief = brief_of(flag(args, "--brief").as_deref())?;
@@ -88,21 +110,21 @@ pub fn cli(args: &[String]) -> Result<String, String> {
let by = flag(args, "--by").unwrap_or_else(|| "clef".into());
if by != "clef" {
if dry {
return Ok(agent::prompt(&dir, &brief, target.as_deref()));
return Ok(agent::prompt(kind, &dir, &brief, target.as_deref()));
}
let v = agent::ask(&by, &dir, &brief, target.as_deref())?;
let (scores, defects, photo) = agent::read(&v);
return finish(args, &dir, scores.clone(), scores, defects, photo, 0.0, &by, false, json!({"blind": v["blind"], "show_as_is": v["show_as_is"]}));
let v = agent::ask(kind, &by, &dir, &brief, target.as_deref())?;
let (scores, defects, photo) = agent::read(kind, &v);
return finish(args, kind, &dir, scores.clone(), scores, defects, photo, 0.0, &by, false, json!({"blind": v["blind"], "show_as_is": v["show_as_is"]}));
}
let mut calls = Vec::new();
for (sheet, img) in [("colour", &colour), ("clay", &clay)] {
for (sheet, img) in &sheets {
let mut images = vec![img.clone()];
if sheet == "colour" {
if *sheet == "colour" {
images.extend(target.clone());
}
calls.push((sheet, rubric::state(sheet, &brief), rubric::questions(sheet), images));
calls.push((*sheet, rubric::state_for(kind, sheet, &brief), rubric::questions_for(kind, sheet), images));
}
if hero.is_file() {
if hero.is_file() && kind != Some("shot") {
calls.push(("blind", "One frame. Judge only what is in the pixels.".into(), rubric::blind(), vec![hero.clone()]));
}
if dry {
@@ -120,7 +142,7 @@ pub fn cli(args: &[String]) -> Result<String, String> {
photo = json!(answers["photo"]["noul"].as_f64().map(|p| (p * 1000.0).round() / 1000.0));
continue;
}
let (s, d) = rubric::read(&answers);
let (s, d) = rubric::read_for(kind, &answers);
scores.extend(s);
defects.extend(d.into_iter().map(|mut x| {
x["sheet"] = json!(sheet);
@@ -128,12 +150,12 @@ pub fn cli(args: &[String]) -> Result<String, String> {
}));
}
let raw = scores.clone();
let cal = eye::calibration();
let cal = eye::calibration(kind);
if let Some(c) = &cal {
eye::apply(c, &mut scores);
}
let gating = cal.as_ref().is_some_and(|c| c["gate"] == true);
finish(args, &dir, scores, raw, defects, photo, cost, "clef", !gating, json!({"calibrated": cal.is_some()}))
finish(args, kind, &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
@@ -164,13 +186,13 @@ pub fn findings(defects: &[Value], by: &str, advice: bool) -> Vec<Finding> {
/// 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)]
fn finish(args: &[String], dir: &Path, scores: serde_json::Map<String, Value>, raw: serde_json::Map<String, Value>, defects: Vec<Value>, photo: Value, cost: f64, by: &str, advice: bool, extra: Value) -> Result<String, String> {
let (pass, why) = rubric::pass(&scores, &defects);
fn finish(args: &[String], kind: Option<&str>, dir: &Path, scores: serde_json::Map<String, Value>, raw: serde_json::Map<String, Value>, defects: Vec<Value>, photo: Value, cost: f64, by: &str, advice: bool, extra: Value) -> Result<String, String> {
let (pass, why) = rubric::pass_for(kind, &scores, &defects);
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,
let mut verdict = json!({"dir": dir.display().to_string(), "kind": kind, "by": by, "scores": scores, "raw": raw, "mean": mean, "defects": defects, "photo": photo,
"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());
@@ -181,7 +203,7 @@ fn finish(args: &[String], dir: &Path, scores: serde_json::Map<String, Value>, r
verdict["progress"] = progress(&rounds);
let file = if by == "clef" { "judge.json".to_string() } else { format!("judge.{by}.json") };
std::fs::write(dir.join(file), serde_json::to_string_pretty(&verdict).unwrap_or_default()).map_err(|e| e.to_string())?;
let lines: Vec<String> = rounds.iter().map(|r| serde_json::to_string(&json!({"dir": r["dir"], "pass": r["pass"], "mean": r["mean"], "defects": r["defects"]})).unwrap_or_default()).collect();
let lines: Vec<String> = rounds.iter().map(|r| serde_json::to_string(&json!({"dir": r["dir"], "kind": r["kind"], "by": r["by"], "pass": r["pass"], "mean": r["mean"], "defects": r["defects"]})).unwrap_or_default()).collect();
std::fs::write(&log, lines.join("\n") + "\n").map_err(|e| e.to_string())?;
if cost > 0.0 {
let _ = std::process::Command::new("antsy").args(["spend", &format!("{cost:.6}"), "raea judge (clef-omni)"]).output();
@@ -204,3 +226,10 @@ fn finish(args: &[String], dir: &Path, scores: serde_json::Map<String, Value>, r
#[cfg(test)]
mod tests;
/// Why `raea spec` refused a brief, in its own words: its refusal is the last line it printed, on whichever stream
/// (a REFUSED line goes to stdout, a thrown module's error to stderr). Reading stderr alone left the reason empty.
pub fn why_refused(out: &std::process::Output) -> String {
let last = |b: &[u8]| String::from_utf8_lossy(b).lines().rev().find(|l| !l.trim().is_empty()).map(|l| l.trim().trim_start_matches("REFUSED").trim().to_string());
last(&out.stderr).or_else(|| last(&out.stdout)).unwrap_or_else(|| "raea spec printed nothing".into())
}
+107 -11
View File
@@ -18,8 +18,11 @@ fn levels(what: &str) -> Value {
])
}
/// (id, the sheet it is judged on, the question)
pub const SCORES: [(&str, &str, &str); 7] = [
/// A category: (id, the sheet it is judged on, the question).
pub type Score = (&'static str, &'static str, &'static str);
/// (id, the sheet it is judged on, the question): the rubric raea judge has always asked, when no `--kind` is given.
pub const SCORES: [Score; 7] = [
("composition", "colour", "Composition: the camera, framing and layout; every major object's position and scale against the brief's space."),
("form", "clay", "Form, judged on these grey clay tiles: silhouettes read at a glance, parts have real thickness, nothing blobby or melted, no primitive standing in for a thing, repeated things vary."),
("assembly", "clay", "Assembly, judged on these grey clay tiles: nothing floats, sinks, pokes through or rests on the wrong thing; joints touch; the low tile shows the feet resting."),
@@ -29,6 +32,64 @@ pub const SCORES: [(&str, &str, &str); 7] = [
("world", "colour", "World: one coherent real place matching the brief; nothing off-era, no real brands, nothing invented beyond the brief."),
];
/// The job kinds with a rubric of their own (docs/goal.feature MK5): `raea judge DIR --kind scene|kit|shot`.
pub const KINDS: [&str; 3] = ["scene", "kit", "shot"];
/// A scene made to a plan (AnyScene's categories): judged on the six-camera sheets.
pub const SCENE: [Score; 8] = [
("layout", "clay", "Layout, judged on these grey clay tiles: every major object where the plan and the reference put it, at its real size, with room to move between them."),
("props", "clay", "Props, judged on these grey clay tiles: each object's form reads at a glance, with real thickness; nothing blobby or a primitive standing in; nothing floats, sinks or pokes through."),
("signage", "colour", "Screens and signage: every screen, sign, label and printed thing reads, belongs to one invented world, and shows no real brand."),
("materials", "colour", "Materials: every surface reads as its real material with wear where use puts it; nothing a flat default colour; glass is glass."),
("light", "colour", "Light: motivated by the place's own sources; exposure and contrast believable; emissive things glow without lighting the room wrong."),
("atmosphere", "colour", "Atmosphere: the air, haze, dust or weather the place would have, matching the plan's dials; not empty and clinical."),
("plausibility", "colour", "Plausibility: one coherent real place a person could stand in; nothing off-era, nothing that couldn't be there."),
("composition", "colour", "Composition: the hero camera's framing and the place's layout read as the reference's."),
];
/// A kit (AnyKit's categories): judged on the six-camera sheets of its lineup.
pub const KIT: [Score; 8] = [
("cohesion", "colour", "Cohesion: every prop belongs to one set: the same era, palette, materials, wear and maker; none is an outlier."),
("fidelity", "colour", "Reference fidelity: the props read as the style references' world, at normal viewing distance."),
("brief", "colour", "Brief: the kit holds the props the brief asked for, each recognisable as what it is meant to be."),
("mesh", "clay", "Mesh, judged on these grey clay tiles: crisp silhouettes, real thickness, no melted or blobby forms, no holes or spikes."),
("texture", "colour", "Texture: real materials with wear where use puts it; no smeared, stretched or flat default surfaces; glass is glass."),
("assembly", "clay", "Assembly, judged on these grey clay tiles: every part of each prop is connected to its body; handles, legs and lids attached."),
("scale", "clay", "Scale, judged on these grey clay tiles: each prop's size is right beside the others and the scale bar."),
("labels", "colour", "Labels: printed text and logos read, belong to the one invented maker, and no real brand shows."),
];
/// A shot list (AnyShot's categories): judged on the framing sheet, each shot's first, middle and last frame.
pub const SHOT: [Score; 6] = [
("framing", "colour", "Framing: each shot frames its subject as its description says, at every one of its frames."),
("move", "colour", "Move: the camera's change from first to last frame is the move the description names, at a believable size."),
("focus", "colour", "Focus: what the description says is sharp is sharp; nothing important lost in blur."),
("clearance", "colour", "Clearance: the camera is never inside or against a wall or object; nothing blocks the frame."),
("continuity", "colour", "Continuity: the shots read as one place at one time: the same light, weather and dressing across them."),
("grade", "colour", "Grade: the look matches the plan's look dial, with believable exposure and colour."),
];
/// The categories asked for a kind: its own rubric, or the default one.
pub fn scores(kind: Option<&str>) -> &'static [Score] {
match kind {
Some("scene") => &SCENE,
Some("kit") => &KIT,
Some("shot") => &SHOT,
_ => &SCORES,
}
}
/// What a kind's critic is told the bar is (AnyKit's own words, docs/goal.feature MK5).
pub const BAR: &str = "The bar is a production base an artist then refines, judged at normal viewing distance: take no points off for choices that differ from the reference, don't nitpick, and name at most five fixes, most damaging first.";
/// The sheets a kind is judged on: the six-camera colour and clay sheets, or a shot list's framing sheet alone.
pub fn sheets(kind: Option<&str>) -> &'static [(&'static str, &'static str)] {
match kind {
Some("shot") => &[("colour", "framing.png")],
_ => &[("colour", "colour.png"), ("clay", "clay.png")],
}
}
/// (id, sheet, the yes/no question, blocking when yes)
pub const DEFECTS: [(&str, &str, &str, bool); 12] = [
("floating", "clay", "Does any object float above the surface it should rest on, with a visible gap under it?", true),
@@ -47,26 +108,50 @@ pub const DEFECTS: [(&str, &str, &str, bool); 12] = [
/// The paragraph clef reads before the sheet: what it is looking at, and the brief's words (no code, no log, no line).
pub fn state(sheet: &str, brief: &Value) -> String {
state_for(None, sheet, brief)
}
/// state, for a kind: a kind's critic also reads what it is looking at in its terms, and the bar.
pub fn state_for(kind: Option<&str>, sheet: &str, brief: &Value) -> String {
let what = match kind {
Some("shot") => "The image is a framing sheet: each row is one shot, its first, middle and last frame left to right, each stamped with the shot's name and time. Judge each shot as its description would.".to_string(),
_ => {
let tiles = "six tiles of one 3D scene, left to right and top to bottom: hero (the shot's own camera), front, right, top, iso, and low (a camera 0.3 m off the floor)";
let what = if sheet == "clay" { format!("The image is {tiles}, rendered in clay: every surface plain grey, so only form and assembly show.") } else { format!("The image is {tiles}, in full colour.") };
let target = if sheet == "colour" { " A second image, when given, is the target picture the scene should read as." } else { "" };
let kit = if kind == Some("kit") { " The scene is a kit: a lineup of props made to belong together, with a scale bar." } else { "" };
format!("{what}{target}{kit}")
}
};
// the default rubric's words stay as calibrated: "the scene"
let it = match kind { None | Some("scene") => "the scene", Some("kit") => "the kit", _ => "the shots" };
let mut s = format!("{what} Judge only what is in the pixels, as the person who will use {it} would.");
let look = brief["look"].as_str().unwrap_or("");
let logline = brief["logline"].as_str().unwrap_or("");
let not: Vec<&str> = brief["notDoing"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
let tiles = "six tiles of one 3D scene, left to right and top to bottom: hero (the shot's own camera), front, right, top, iso, and low (a camera 0.3 m off the floor)";
let what = if sheet == "clay" { format!("The image is {tiles}, rendered in clay: every surface plain grey, so only form and assembly show.") } else { format!("The image is {tiles}, in full colour.") };
let target = if sheet == "colour" { " A second image, when given, is the target picture the scene should read as." } else { "" };
let mut s = format!("{what}{target} Judge only what is in the pixels, as the person who will use the scene would.");
if !logline.is_empty() || !look.is_empty() {
s.push_str(&format!(" The brief: {logline} Look: {look}."));
}
if !not.is_empty() {
s.push_str(&format!(" The scene must not contain: {}.", not.join("; ")));
let it = it[..1].to_uppercase() + &it[1..];
s.push_str(&format!(" {it} must not contain: {}.", not.join("; ")));
}
if kind.is_some() {
s.push(' ');
s.push_str(BAR);
}
s
}
/// The questions for one sheet, by id.
pub fn questions(sheet: &str) -> Value {
questions_for(None, sheet)
}
/// questions, for a kind's rubric.
pub fn questions_for(kind: Option<&str>, sheet: &str) -> Value {
let mut q = serde_json::Map::new();
for (id, on, ask) in SCORES {
for &(id, on, ask) in scores(kind) {
if on == sheet {
q.insert(format!("score_{id}"), json!({"type": "score", "instructions": ask, "criteria": levels(id)}));
}
@@ -86,9 +171,14 @@ pub fn blind() -> Value {
/// clef's answers read into scores (0-10) and defects (probability of yes, blocking ones flagged).
pub fn read(answers: &Value) -> (serde_json::Map<String, Value>, Vec<Value>) {
read_for(None, answers)
}
/// read, for a kind's rubric.
pub fn read_for(kind: Option<&str>, answers: &Value) -> (serde_json::Map<String, Value>, Vec<Value>) {
let mut scores = serde_json::Map::new();
let mut defects = Vec::new();
for (id, _, _) in SCORES {
for &(id, _, _) in self::scores(kind) {
if let Some(a) = answers.get(format!("score_{id}")) {
let level = a["score"].as_f64().unwrap_or(0.0);
scores.insert(id.into(), json!((level * 2.0 * 100.0).round() / 100.0));
@@ -106,6 +196,12 @@ pub fn read(answers: &Value) -> (serde_json::Map<String, Value>, Vec<Value>) {
/// The loop's pass, in code: no blocking defect present, the lowest score 6 or more and the mean 7 or more (raea's
/// 0-10 scale; the prompt pack's line). Scores mapped by a calibration first, when there is one.
pub fn pass(scores: &serde_json::Map<String, Value>, defects: &[Value]) -> (bool, Vec<String>) {
pass_for(None, scores, defects)
}
/// pass, for a kind's rubric: every one of its categories scored.
pub fn pass_for(kind: Option<&str>, scores: &serde_json::Map<String, Value>, defects: &[Value]) -> (bool, Vec<String>) {
let want = self::scores(kind).len();
let vals: Vec<f64> = scores.values().filter_map(Value::as_f64).collect();
let mut why = Vec::new();
let blocking = blocking(defects);
@@ -114,8 +210,8 @@ pub fn pass(scores: &serde_json::Map<String, Value>, defects: &[Value]) -> (bool
}
let min = vals.iter().cloned().fold(f64::INFINITY, f64::min);
let mean = if vals.is_empty() { 0.0 } else { vals.iter().sum::<f64>() / vals.len() as f64 };
if vals.len() < SCORES.len() {
why.push(format!("only {} of {} categories scored", vals.len(), SCORES.len()));
if vals.len() < want {
why.push(format!("only {} of {want} categories scored", vals.len()));
}
if min < 6.0 {
let low: Vec<String> = scores.iter().filter(|(_, v)| v.as_f64().is_some_and(|x| x < 6.0)).map(|(k, _)| k.clone()).collect();
+53 -4
View File
@@ -37,15 +37,15 @@ fn calibration_maps_a_lenient_judge_onto_the_eye() {
// the judge says 8 to everything the eye gives 5, and 9 to what the eye gives 8
let row = |j: f64, e: f64, p: bool| json!({"judge": scores(j), "eye": scores(e), "eye_pass": p, "defects": []});
let rows: Vec<Value> = (0..12).map(|i| if i % 2 == 0 { row(8.0, 5.0, false) } else { row(9.0, 8.0, true) }).collect();
let cal = eye::fit_rows(&rows);
let cal = eye::fit_rows_for(None, &rows);
assert_eq!(cal["agreement"], 1.0);
assert_eq!(cal["gate"], true);
assert!((cal["maps"]["form"]["a"].as_f64().unwrap() - 3.0).abs() < 1e-6);
let few = eye::fit_rows(&rows[..4]);
let few = eye::fit_rows_for(None, &rows[..4]);
assert_eq!(few["gate"], false, "too few rounds to gate");
// an eye that failed everything agrees with a judge that fails everything, which proves nothing
let fails: Vec<Value> = (0..12).map(|_| row(3.0, 2.0, false)).collect();
let all_fail = eye::fit_rows(&fails);
let all_fail = eye::fit_rows_for(None, &fails);
assert_eq!(all_fail["agreement"], 1.0);
assert_eq!(all_fail["gate"], false, "no pass among the eye's rounds");
}
@@ -60,7 +60,7 @@ fn an_agent_verdict_is_read_from_the_end_of_its_thinking() {
{"tile": "low", "wrong": "", "level": "detail"}],
"show_as_is": "no"}"#;
let v = crate::agent::last_verdict(text).unwrap();
let (scores, defects, photo) = crate::agent::read(&v);
let (scores, defects, photo) = crate::agent::read(None, &v);
assert_eq!(scores.len(), 7, "only the seven categories, each 0-10");
assert_eq!(scores["form"], serde_json::json!(5.5));
assert_eq!(defects.len(), 1, "a defect with nothing wrong named is dropped");
@@ -75,3 +75,52 @@ fn an_agent_verdict_is_read_from_the_end_of_its_thinking() {
assert!(f.says.starts_with("iso sheet: "), "{}", f.says);
assert_eq!(crate::findings(&defects, "kimi", true)[0].level, raea_core_facts::Level::Warn);
}
#[test]
fn each_make_kind_has_its_own_rubric_and_the_default_is_unchanged() {
// docs/goal.feature MK5: a kit's categories, a shot list's on the framing sheet alone, the bar said to each
let kit = rubric::questions_for(Some("kit"), "clay");
for k in ["score_mesh", "score_assembly", "score_scale"] {
assert!(kit.get(k).is_some(), "{k} in {kit}");
}
assert!(kit.get("score_cohesion").is_none(), "cohesion is judged in colour");
assert_eq!(rubric::sheets(Some("shot")), &[("colour", "framing.png")]);
assert_eq!(rubric::sheets(None).len(), 2);
let shot = rubric::questions_for(Some("shot"), "colour");
assert!(shot.get("score_clearance").is_some() && shot.get("score_composition").is_none());
assert!(rubric::state_for(Some("kit"), "colour", &json!({})).contains(rubric::BAR));
assert!(rubric::state_for(Some("shot"), "colour", &json!({})).contains("framing sheet"));
// the default's words are what it was calibrated on
let d = rubric::state("clay", &json!({"notDoing": ["cats"]}));
assert!(d.contains("as the person who will use the scene would") && d.contains("The scene must not contain: cats.") && !d.contains(rubric::BAR), "{d}");
// every kind scored in full to pass
let all = |k: Option<&str>, v: f64| -> serde_json::Map<String, Value> { rubric::scores(k).iter().map(|s| (s.0.to_string(), json!(v))).collect() };
assert!(rubric::pass_for(Some("kit"), &all(Some("kit"), 8.0), &[]).0);
let (ok, why) = rubric::pass_for(Some("kit"), &all(None, 8.0), &[]);
assert!(!ok && why.iter().any(|w| w.contains("of 8 categories")), "{why:?}");
assert!(kind_of(&["judge".into(), "d".into(), "--kind".into(), "film".into()]).is_err());
assert_eq!(kind_of(&["judge".into(), "d".into(), "--kind".into(), "shot".into()]).unwrap().as_deref(), Some("shot"));
}
#[test]
fn an_agent_critic_is_asked_its_kinds_categories() {
let p = crate::agent::prompt(Some("shot"), std::path::Path::new("/r/r1"), &json!({"look": "dusk"}), None);
assert!(p.contains("/r/r1/framing.png") && p.contains("\"clearance\": 0") && p.contains(rubric::BAR) && !p.contains("PART 1, BLIND"), "{p}");
let k = crate::agent::prompt(Some("kit"), std::path::Path::new("/r/r1"), &json!({}), None);
assert!(k.contains("\"cohesion\": 0") && k.contains("scale bar") && k.contains("(judged on CLAY)"));
let d = crate::agent::prompt(None, std::path::Path::new("/r/r1"), &json!({}), None);
assert!(d.contains("\"composition\": 0") && !d.contains(rubric::BAR));
let v = json!({"scores": {"cohesion": 7, "fidelity": 8, "composition": 9}});
let (s, _, _) = crate::agent::read(Some("kit"), &v);
assert_eq!(s.len(), 2, "only the kit's categories");
}
#[test]
fn a_kind_is_calibrated_on_its_own_categories() {
// docs/goal.feature MK6
let s = |j: f64| -> serde_json::Map<String, Value> { rubric::KIT.iter().map(|c| (c.0.to_string(), json!(j))).collect() };
let rows: Vec<Value> = (0..12).map(|i| if i % 2 == 0 { json!({"kind": "kit", "judge": s(8.0), "eye": s(5.0), "eye_pass": false, "defects": []}) } else { json!({"kind": "kit", "judge": s(9.0), "eye": s(8.0), "eye_pass": true, "defects": []}) }).collect();
let cal = eye::fit_rows_for(Some("kit"), &rows);
assert_eq!(cal["gate"], true);
assert!(cal["maps"]["cohesion"].is_object() && cal["maps"]["form"].is_null());
}
+22
View File
@@ -0,0 +1,22 @@
[package]
name = "raea-app-lightbake"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "raea make bake light: bounce light baked into lightmaps on raea's own ray tracer, and the bar it is held to against Cycles (docs/bake.feature)"
[dependencies]
# the frames' distance in stops, as raea light check measures it (LT1)
raea-light = { path = "../../engine/light" }
# the CLI's flag reader and result type
raea-runtime-bundle = { path = "../../runtime/bundle" }
# raea's own files (the test set, the Blender library scripts) and the home folder
raea-io-home = { path = "../../io/home" }
image = { version = "0.25", default-features = false, features = ["png"] }
serde_json = "1"
sha2 = "0.10"
[target.'cfg(unix)'.dependencies]
# wait4: a step's peak memory
libc = "0.2"
+13
View File
@@ -0,0 +1,13 @@
{
"about": "the bake's test set (docs/bake.feature BK0), for `raea make bake light --compare DIR`: each set's Cycles still (blender/look.py, given the composition's own sky, tone and lens) and Cycles bake (blender/lightbake.py), and raea's frames beside them",
"sets": [
{ "name": "table", "dir": "bench/bake", "file": "table.tsx", "composition": "table", "cycles": ["table-cycles.tsx", "table-cycles"], "bar": true, "texels": 128,
"look": ["--hdri", "media/kloofendal_48d_partly_cloudy_puresky_1k.hdr", "--strength", "0.25", "--rotation", "0.6", "--tone", "agx", "--exposure", "-0.8", "--focus", "2.5", "--fstop", "2.8", "--size", "1280x720"] },
{ "name": "cornell", "dir": "bench/bake", "file": "cornell.tsx", "composition": "cornell", "cycles": ["cornell-cycles.tsx", "cornell-cycles"], "texels": 128,
"look": ["--tone", "agx", "--exposure", "0", "--size", "1280x720"] },
{ "name": "window", "dir": "bench/bake", "file": "window.tsx", "composition": "window", "cycles": ["window-cycles.tsx", "window-cycles"], "texels": 64,
"look": ["--hdri", "media/kloofendal_48d_partly_cloudy_puresky_1k.hdr", "--strength", "0.25", "--rotation", "0.6", "--tone", "agx", "--exposure", "1.5", "--size", "1280x720"] },
{ "name": "atelier", "dir": "~/Studio/raea/projects/atelier", "file": "compositions/atelier.tsx", "composition": "set", "texels": 64, "reference": false,
"why": "a test agent's project, still being built; its Manifold solids stop `raea blender open` (filed with raea bug), so its Blender bake runs through its own tools/bake.sh. It joins at BK5, with that bake as the comparison" }
]
}
+200
View File
@@ -0,0 +1,200 @@
//! One set against Cycles (docs/bake.feature BK0): its Cycles still (blender/look.py) and Cycles bake
//! (blender/lightbake.py), kept in DIR/NAME until the set or the samples change, then raea's frames beside them: the set
//! unbaked, the set with Cycles' maps, and the set with raea's own bake. A frame is measured against the Cycles still by
//! its RMSE (sRGB 0..1 over every pixel and channel, as docs/blender-research.md's table) and in stops (raea light
//! check's distance); a lightmap against Cycles' in stops, texel by texel on the same UVs (map_stops).
use crate::{key, library, run, Ran, Set};
use raea_runtime_bundle::R;
use serde_json::{json, Value};
use std::path::{Path, PathBuf};
/// The bar (BK0): the frame with raea's bake within this RMSE of the Cycles still on the table set (lightbake.py's gives
/// 0.040), no mesh's map off by more than a third of a stop on average, in under a quarter of lightbake.py's time.
pub const BAR_RMSE: f64 = 0.045;
pub const BAR_STOPS: f64 = 1.0 / 3.0;
pub const BAR_TIME: f64 = 0.25;
/// The set's Cycles references, made: the export, look.py's still at `samples` (OUT/cycles.png), lightbake.py's bake at
/// `samples` into the set's media/baked/NAME/, which the set's `cycles` composition reads.
fn reference(set: &Set, samples: u32, out: &Path, baked: &Path) -> R<Value> {
let bl = out.join("bl");
let _ = std::fs::remove_dir_all(&bl);
let _ = std::fs::remove_dir_all(baked);
let stem = Path::new(&set.file).file_stem().map(|x| x.to_string_lossy().to_string()).unwrap_or_default();
let open = run(&set.dir, &["blender".into(), "open".into(), set.file.clone(), "--no-window".into(), "-o".into(), format!("{}", bl.display())], &out.join("open.log"))?;
let (blend, look) = (bl.join(format!("{stem}.blend")), bl.join("look.blend"));
let mut a = vec!["blender".into(), "run".into(), format!("{}", library("look.py")?.display()), format!("{}", blend.display()), format!("{}", look.display())];
a.extend(set.look.iter().cloned());
a.extend(["--engine".into(), "cycles".into(), "--samples".into(), samples.to_string(), "--still".into(), format!("{}", out.join("cycles.png").display())]);
let still = run(&set.dir, &a, &out.join("look.log"))?;
let a = vec!["blender".into(), "run".into(), format!("{}", library("lightbake.py")?.display()), format!("{}", look.display()), format!("{}", baked.join("set.glb").display()), "--samples".into(), samples.to_string(), "--texels".into(), set.texels.to_string()];
let bake = run(&set.dir, &a, &out.join("lightbake.log"))?;
Ok(json!({ "export": open.json(), "still": still.json(), "lightbake": bake.json() }))
}
/// Frame 0 of `composition` in `file`, drawn by raea into OUT/LABEL/: the picture and what it cost.
fn frame(set: &Set, file: &str, composition: &str, out: &Path, label: &str) -> R<(PathBuf, Ran)> {
let dir = out.join(label);
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
let a = ["render", file, "--composition", composition, "--at", "0", "-o", &format!("{}/", dir.display())].map(String::from);
let ran = run(&set.dir, &a, &out.join(format!("{label}.log")))?;
Ok((dir.join("frame-00000.png"), ran))
}
fn round(x: f64) -> f64 {
(x * 10000.0).round() / 10000.0
}
/// RMSE of two pictures the same size, sRGB 0..1 over every pixel and channel.
pub fn rmse(a: &Path, b: &Path) -> R<f64> {
let load = |p: &Path| image::open(p).map(|i| i.to_rgb8()).map_err(|e| format!("{}: {e}", p.display()));
let (a, b) = (load(a)?, load(b)?);
if a.dimensions() != b.dimensions() {
return Err(format!("sizes differ: {:?} against {:?}", a.dimensions(), b.dimensions()));
}
let sum: f64 = a.as_raw().iter().zip(b.as_raw()).map(|(x, y)| ((*x as f64 - *y as f64) / 255.0).powi(2)).sum();
Ok((sum / a.as_raw().len().max(1) as f64).sqrt())
}
/// A raea frame against the Cycles still: RMSE, and the mean and worst tile in stops.
fn measure(got: &(PathBuf, Ran), cycles: &Path) -> R<Value> {
let d = raea_light::metric::distance(&raea_light::metric::load(&got.0)?, &raea_light::metric::load(cycles)?)?;
Ok(json!({ "rmse": round(rmse(&got.0, cycles)?), "mean_stops": round(d.mean as f64), "worst_stops": round(d.worst as f64), "render": got.1.json() }))
}
/// A lightmap against another on the same UVs, each scaled by its lightmap_exposure: over the texels both cover, the
/// mean distance in stops, the mean signed (brighter is positive), and the worst 8 x 8 tile's mean distance.
pub fn map_stops(a: &Path, a_exposure: f64, b: &Path, b_exposure: f64) -> R<Value> {
let lum = |p: &Path, k: f64| -> R<(u32, u32, Vec<f64>)> {
let i = image::open(p).map_err(|e| format!("{}: {e}", p.display()))?.to_rgb32f();
Ok((i.width(), i.height(), i.pixels().map(|q| k * (0.2126 * q[0] as f64 + 0.7152 * q[1] as f64 + 0.0722 * q[2] as f64)).collect()))
};
let ((w, h, a), (bw, bh, b)) = (lum(a, a_exposure)?, lum(b, b_exposure)?);
if (w, h) != (bw, bh) {
return Err(format!("map sizes differ: {w}x{h} against {bw}x{bh}"));
}
let (mut sum, mut signed, mut n) = (0.0, 0.0, 0usize);
let mut tiles = vec![(0.0, 0usize); w.div_ceil(8) as usize * h.div_ceil(8) as usize];
for (i, (x, y)) in a.iter().zip(&b).enumerate() {
if *x <= 0.0 || *y <= 0.0 {
continue;
}
let st = (x / y).log2();
(sum, signed, n) = (sum + st.abs(), signed + st, n + 1);
let t = &mut tiles[(i / w as usize / 8) * w.div_ceil(8) as usize + (i % w as usize) / 8];
*t = (t.0 + st.abs(), t.1 + 1);
}
let worst = tiles.iter().filter(|t| t.1 >= 32).map(|t| t.0 / t.1 as f64).fold(0.0, f64::max);
let k = n.max(1) as f64;
Ok(json!({ "texels": n, "mean_stops": round(sum / k), "bias_stops": round(signed / k), "worst_tile_stops": round(worst) }))
}
/// Whether a set's numbers meet the bar, and why not.
fn bar(r: &Value) -> Value {
let f = &r["frames"]["raea-bake"];
if f["made"] == json!(false) {
return json!({ "met": false, "why": f["why"] });
}
let rmse = f["rmse"].as_f64().is_some_and(|x| x <= BAR_RMSE);
let meshes = r["meshes"].as_array().is_some_and(|m| m.iter().all(|m| m["raea"]["mean_stops"].as_f64().is_some_and(|x| x <= BAR_STOPS)));
let time = match (f["bake"]["seconds"].as_f64(), r["reference"]["lightbake"]["seconds"].as_f64()) {
(Some(a), Some(b)) => a < b * BAR_TIME,
_ => false,
};
json!({ "met": rmse && meshes && time, "rmse": rmse, "meshes": meshes, "time": time })
}
pub fn set(set: &Set, samples: u32, out: &Path, fresh: bool) -> R<Value> {
std::fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?;
let mut r = json!({ "name": set.name, "samples": samples });
if let Err(why) = &set.reference {
r["reference"] = json!({ "made": false, "why": why });
return Ok(r);
}
let (baked, cycles, made) = (set.dir.join("media/baked").join(&set.name), out.join("cycles.png"), out.join("made.json"));
let key = key(set, samples);
let kept = std::fs::read_to_string(&made).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok());
r["reference"] = match kept.filter(|k| !fresh && k["key"] == json!(key) && cycles.is_file() && baked.join("set.lightmaps.json").is_file()) {
Some(k) => {
let mut v = k["reference"].clone();
v["kept"] = json!(true);
v
}
None => {
let v = reference(set, samples, out, &baked)?;
std::fs::write(&made, json!({ "key": key, "reference": v }).to_string()).map_err(|e| e.to_string())?;
v
}
};
r["frames"]["raea"] = measure(&frame(set, &set.file, &set.composition, out, "raea")?, &cycles)?;
if let Some((file, comp)) = &set.cycles {
r["frames"]["cycles-bake"] = measure(&frame(set, file, comp, out, "cycles-bake")?, &cycles)?;
}
// rask: BK5 raea's own bake of the set (<LightBake>): its frame against the Cycles still, its time and memory, and each mesh's map against Cycles' by map_stops on lightbake.py's UVs
r["frames"]["raea-bake"] = json!({ "made": false, "why": "raea's bake isn't built yet (BK1-BK5)" });
let maps: Value = std::fs::read_to_string(baked.join("set.lightmaps.json")).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default();
r["meshes"] = json!(maps["meshes"].as_array().into_iter().flatten().map(|m| json!({ "mesh": m["mesh"], "size": m["size"], "cycles_exposure": m["lightmap_exposure"] })).collect::<Vec<_>>());
if set.bar {
r["bar"] = bar(&r);
}
Ok(r)
}
/// The table a person reads: a line a set and frame, then the Cycles bake's cost and the bar.
pub fn table(reports: &[Value]) -> String {
let mut t = format!("{:<10} {:<12} {:>7} {:>7} {:>7}\n", "set", "frame", "rmse", "stops", "worst");
for r in reports {
let name = r["name"].as_str().unwrap_or("");
if r["reference"]["made"] == json!(false) {
t += &format!("{name:<10} (no reference: {})\n", r["reference"]["why"].as_str().unwrap_or(""));
continue;
}
for (label, f) in r["frames"].as_object().into_iter().flatten() {
let n = |k: &str| match f[k].as_f64() {
Some(x) => format!("{x:.4}"),
None => "-".into(),
};
let why = f["why"].as_str().map(|w| format!(" ({w})")).unwrap_or_default();
t += &format!("{name:<10} {label:<12} {:>7} {:>7} {:>7}{why}\n", n("rmse"), n("mean_stops"), n("worst_stops"));
}
let (lb, st) = (&r["reference"]["lightbake"], &r["reference"]["still"]);
t += &format!("{name:<10} Cycles at {} samples: lightbake.py {}s (peak {} MB) for {} meshes, the still {}s\n", r["samples"], lb["seconds"], lb["peak_mb"], r["meshes"].as_array().map_or(0, Vec::len), st["seconds"]);
if let Some(b) = r.get("bar") {
t += &format!("{name:<10} bar: {}\n", if b["met"] == json!(true) { "met".to_string() } else { format!("not met: {}", b["why"].as_str().unwrap_or("see report.json")) });
}
}
t
}
#[cfg(test)]
mod tests {
use super::*;
fn png16(path: &Path, w: u32, h: u32, v: u16) {
image::ImageBuffer::<image::Rgb<u16>, _>::from_pixel(w, h, image::Rgb([v, v, v])).save(path).unwrap();
}
#[test]
fn a_map_twice_as_bright_is_one_stop_off_and_its_exposure_brings_it_back() {
let d = std::env::temp_dir().join(format!("raea-lightbake-{}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
let (a, b) = (d.join("a.png"), d.join("b.png"));
png16(&a, 16, 16, 40000);
png16(&b, 16, 16, 20000);
let off = map_stops(&a, 1.0, &b, 1.0).unwrap();
assert_eq!((off["mean_stops"].as_f64(), off["bias_stops"].as_f64(), off["texels"].as_u64()), (Some(1.0), Some(1.0), Some(256)));
assert_eq!(map_stops(&a, 1.0, &b, 2.0).unwrap()["mean_stops"].as_f64(), Some(0.0));
assert!(rmse(&a, &b).unwrap() > 0.3 && rmse(&a, &a).unwrap() == 0.0);
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn the_bar_is_unmet_until_raeas_bake_exists() {
let r = json!({ "frames": { "raea-bake": { "made": false, "why": "not yet" } } });
assert_eq!(bar(&r)["met"], json!(false));
let r = json!({ "frames": { "raea-bake": { "rmse": 0.04, "bake": { "seconds": 4.0 } } }, "meshes": [{ "raea": { "mean_stops": 0.2 } }], "reference": { "lightbake": { "seconds": 20.0 } } });
assert_eq!(bar(&r)["met"], json!(true));
}
}
+158
View File
@@ -0,0 +1,158 @@
//! `raea make bake light EDIT.tsx [--composition ID] [--samples N] [--compare DIR]` (docs/bake.feature): raea's own bake of a
//! composition's static parts (BK1-BK5), and the bar it is held to (BK0). `--compare DIR` runs the test set (sets.json)
//! through Cycles (blender/look.py's still and blender/lightbake.py's bake, both at --samples, 1024 by default) and
//! through raea, then writes DIR/report.json and a table: each frame's RMSE and stops against the Cycles still, each
//! mesh's lightmap against Cycles', and each bake's time and peak memory.
//!
//! A set in sets.json: { "name", "dir" (under raea's home, or ~/...), "file", "composition", "cycles": [file,
//! composition] (the set drawn with lightbake.py's maps), "look": [look.py's flags, the composition's own values],
//! "texels" (lightbake.py's texels a metre), "bar": true (the set the bar is read on), "reference": false and "why" (a
//! set whose references can't be made yet) }.
pub mod compare;
use raea_runtime_bundle::{flag, R};
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use std::path::{Path, PathBuf};
pub const USAGE: &str = "raea make bake light EDIT.tsx [--composition ID] [--samples N] | raea make bake light --compare DIR [--sets FILE] [--set NAME] [--samples N] [--fresh] (bounce light baked into lightmaps on raea's ray tracer; --compare measures the test set against Cycles' bake and still, docs/bake.feature)";
/// One set of the test set, as sets.json lists it.
pub struct Set {
pub name: String,
pub dir: PathBuf,
pub file: String,
pub composition: String,
pub cycles: Option<(String, String)>,
pub look: Vec<String>,
pub texels: u32,
pub bar: bool,
pub reference: Result<(), String>,
}
fn home_path(p: &str) -> PathBuf {
match (p.strip_prefix("~/"), raea_io_home::user_home()) {
(Some(rest), Some(h)) => h.join(rest),
_ if Path::new(p).is_absolute() => PathBuf::from(p),
_ => raea_io_home::home().join(p),
}
}
pub fn sets(path: &Path) -> R<Vec<Set>> {
let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
let v: Value = serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?;
let list = v["sets"].as_array().ok_or(format!("{}: no \"sets\" list", path.display()))?;
let strs = |x: &Value| x.as_array().map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect::<Vec<_>>()).unwrap_or_default();
list.iter()
.map(|s| {
let text = |k: &str| match &s[k] {
Value::String(v) => Ok(v.clone()),
_ => Err(format!("{}: a set without \"{k}\"", path.display())),
};
let cycles = match strs(&s["cycles"]).as_slice() {
[file, comp] => Some((file.clone(), comp.clone())),
_ => None,
};
let reference = if s["reference"] == json!(false) { Err(s["why"].as_str().unwrap_or("not yet").to_string()) } else { Ok(()) };
Ok(Set { name: text("name")?, dir: home_path(&text("dir")?), file: text("file")?, composition: text("composition")?, cycles, look: strs(&s["look"]), texels: s["texels"].as_u64().unwrap_or(128) as u32, bar: s["bar"] == json!(true), reference })
})
.collect()
}
/// What a step cost: its seconds, and its peak memory in MB where the OS reports it (a child's and its children's).
#[derive(Debug, Clone, Copy)]
pub struct Ran {
pub seconds: f64,
pub peak_mb: Option<u64>,
}
impl Ran {
pub fn json(&self) -> Value {
json!({ "seconds": (self.seconds * 10.0).round() / 10.0, "peak_mb": self.peak_mb })
}
}
#[cfg(unix)]
fn wait(child: std::process::Child) -> R<(bool, Option<u64>)> {
let (mut status, pid) = (0, child.id() as libc::pid_t);
// SAFETY: rusage is plain data, zeroed is a valid value; wait4 reaps the child std spawned and never waited on
let mut ru: libc::rusage = unsafe { std::mem::zeroed() };
if unsafe { libc::wait4(pid, &mut status, 0, &mut ru) } < 0 {
return Err(format!("waiting for {pid}: {}", std::io::Error::last_os_error()));
}
// ru_maxrss is bytes on macOS, kilobytes elsewhere
let kb = if cfg!(target_os = "macos") { ru.ru_maxrss as u64 / 1024 } else { ru.ru_maxrss as u64 };
Ok((libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, Some(kb / 1024)))
}
#[cfg(not(unix))]
fn wait(mut child: std::process::Child) -> R<(bool, Option<u64>)> {
Ok((child.wait().map_err(|e| e.to_string())?.success(), None))
}
/// This raea with `args` in `dir`, its output into `log`: what it cost, or the log's last lines.
pub fn run(dir: &Path, args: &[String], log: &Path) -> R<Ran> {
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let out = std::fs::File::create(log).map_err(|e| format!("{}: {e}", log.display()))?;
let err = out.try_clone().map_err(|e| e.to_string())?;
let t = std::time::Instant::now();
let child = std::process::Command::new(exe).current_dir(dir).args(args).stdout(out).stderr(err).spawn().map_err(|e| e.to_string())?;
let (ok, peak_mb) = wait(child)?;
let ran = Ran { seconds: t.elapsed().as_secs_f64(), peak_mb };
if ok {
return Ok(ran);
}
let text = std::fs::read_to_string(log).unwrap_or_default();
let last: Vec<&str> = text.lines().filter(|l| !l.starts_with("Fra:") && l.chars().any(|c| !c.is_whitespace())).rev().take(4).collect();
Err(format!("raea {} failed ({}): {}", args.first().map_or("", String::as_str), log.display(), last.into_iter().rev().collect::<Vec<_>>().join(" | ")))
}
/// A set's identity for its kept references: every .tsx in its folder and its parts/, the flags look.py and lightbake.py
/// get, and the samples.
pub fn key(s: &Set, samples: u32) -> String {
let mut h = Sha256::new();
for d in [s.dir.clone(), s.dir.join("parts")] {
let mut fs: Vec<PathBuf> = std::fs::read_dir(&d).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "tsx")).collect();
fs.sort();
for f in fs {
h.update(f.file_name().unwrap_or_default().as_encoded_bytes());
h.update(std::fs::read(&f).unwrap_or_default());
}
}
h.update(format!("{:?} {} {samples}", s.look, s.texels));
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
}
/// Where the Blender library scripts are (sdk/guides/craft/bevy/blender), with `name` there, or why not.
pub fn library(name: &str) -> R<PathBuf> {
let p = raea_io_home::home().join("sdk/guides/craft/bevy/blender").join(name);
if p.is_file() { Ok(p) } else { Err(format!("no {} (the Blender library script the Cycles reference is made with)", p.display())) }
}
pub fn cli(args: &[String]) -> R<String> {
if args.get(1).map(String::as_str) != Some("light") {
return Err(format!("usage: {USAGE}"));
}
let samples: u32 = flag(args, "--samples").map(|v| v.parse().map_err(|_| format!("--samples {v}: a count of samples a texel"))).transpose()?.unwrap_or(1024);
let Some(out) = flag(args, "--compare").map(PathBuf::from) else {
// rask: BK5 `raea make bake light EDIT.tsx` bakes a composition's <LightBake> ahead of a render and says what it baked
return Err("raea's own bake isn't built yet (docs/bake.feature BK1-BK5); `raea make bake light --compare DIR` measures the test set against Cycles".into());
};
let list = sets(&flag(args, "--sets").map_or_else(|| raea_io_home::home().join("apps/lightbake/sets.json"), PathBuf::from))?;
let only = flag(args, "--set");
let fresh = args.iter().any(|a| a == "--fresh");
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
let mut reports = Vec::new();
for s in list.iter().filter(|s| only.is_none() || only.as_deref() == Some(s.name.as_str())) {
eprintln!("raea make bake light: {} ...", s.name);
reports.push(compare::set(s, samples, &out.join(&s.name), fresh)?);
}
if reports.is_empty() {
return Err(format!("no set named {}", only.unwrap_or_default()));
}
let report = json!({ "samples": samples, "sets": reports });
let path = out.join("report.json");
std::fs::write(&path, serde_json::to_string_pretty(&report).unwrap_or_default()).map_err(|e| e.to_string())?;
Ok(format!("{}raea make bake light: wrote {}", compare::table(&reports), path.display()))
}
+29
View File
@@ -0,0 +1,29 @@
[package]
name = "raea-app-make"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "raea make's Rust: a scene, kit or shot job's steps, and the record and critic gates raea/goal's packs read (docs/goal.feature)"
[dependencies]
# the plan: `make` on brief.ts
raea-core-brief = { path = "../../core/brief" }
# the project's record of renders and checks, and the folder it lives in
raea-core-facts = { path = "../../core/facts" }
# the parts a render showed closer than their planned detail (MK24)
raea-runtime-lod-plan = { path = "../../runtime/lod-plan" }
# the judge's rounds, passes and blocking defects, read as it keeps them
raea-app-judge = { path = "../judge" }
# the make questions, their calibrations and a sheet's ident, as raea ask keeps them (MK4)
raea-core-ask = { path = "../../core/ask" }
# a lens's field of view (MK15's lens chart), as the review sheets work it out
raea-core-review = { path = "../../core/review" }
# raea ask's ledger folder
raea-io-home = { path = "../../io/home" }
# the contact sheets: tiles composited, labels drawn in the system's fonts
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
resvg = { version = "=0.48.1", default-features = false, features = ["text", "system-fonts"] }
dunce = "1"
serde_json = "1"
+114
View File
@@ -0,0 +1,114 @@
//! The second tier of the gate (docs/goal.feature MK4): the `make` set of `raea ask` questions (core/ask
//! library/make.json), asked of the job's newest sheets. A question gates once it is calibrated on the person's labels
//! (`raea ask calibrate`: 16 problem, 16 clean, an AUC of 0.8); until then what it says is advice in the gates. An
//! answer counts for a sheet only when its call was about exactly that sheet's bytes (the ledger's `ident`), so a sheet
//! rendered again must be asked again.
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use raea_core_ask::{Calibration, Question};
use serde_json::{Value, json};
/// The ledger as the gates read it: every call's ident by id, every answer, and the person's calibrations.
#[derive(Default)]
pub struct Ledger {
pub idents: HashMap<String, String>,
pub answers: Vec<Value>,
pub calibrations: BTreeMap<String, Calibration>,
}
impl Ledger {
/// `raea ask`'s record (RAEA_ASK_DIR, else ~/.raea/ask), read once.
pub fn read() -> Ledger {
let dir = raea_io_home::env_path("RAEA_ASK_DIR", ".raea/ask");
let rows = |f: &str| -> Vec<Value> { std::fs::read_to_string(dir.join(f)).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect() };
let idents = rows("calls.jsonl").into_iter().filter_map(|c| Some((c["id"].as_str()?.to_string(), c["ident"].as_str()?.to_string()))).collect();
let answers = rows("answers.jsonl").into_iter().filter(|a| a["question"].as_str().is_some_and(|q| q.starts_with("make."))).collect();
let calibrations = std::fs::read_to_string(dir.join("calibration.json")).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default();
Ledger { idents, answers, calibrations }
}
}
/// The `make` set's questions with the person's calibrations in place of raea's (as `raea ask` applies them).
pub fn questions(ledger: &Ledger) -> Vec<Question> {
let mut qs = raea_core_ask::library::set("make", None).unwrap_or_default();
for q in &mut qs {
if let Some(c) = ledger.calibrations.get(&q.version()) {
q.calibration = Some(c.clone());
}
}
qs
}
/// The sheet a question is asked of: its id's second word (make.clay.floating is asked of a clay sheet).
pub fn sheet_of(q: &Question) -> &str {
match q.id.split('.').nth(1) {
Some(sheet) => sheet,
None => "",
}
}
/// The command that asks a sheet its questions.
pub fn command(sheet: &Path, qs: &[&Question]) -> String {
let std: Vec<String> = qs.iter().map(|q| format!("--std {}", q.id)).collect();
format!("raea ask {} {}", sheet.display(), std.join(" "))
}
/// Each sheet's gate, and the advice: what uncalibrated questions flagged. `sheets` are (kind, file): clay, colour,
/// refs, framing. `notes` is NOTES.md: a flagged question answered there by its id holds nothing.
pub fn gates(sheets: &[(&str, PathBuf)], ledger: &Ledger, notes: &str) -> (Vec<Value>, Vec<String>) {
let qs = questions(ledger);
let mut gates = Vec::new();
let mut advice = Vec::new();
for (kind, file) in sheets {
let mine: Vec<&Question> = qs.iter().filter(|q| sheet_of(q) == *kind).collect();
if mine.is_empty() {
continue;
}
let rel = file.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let Some(ident) = raea_core_ask::ident::ident(file) else { continue };
// the newest answer to each question about these exact bytes
let mut latest: BTreeMap<&str, &Value> = BTreeMap::new();
for a in &ledger.answers {
let about = a["call"].as_str().and_then(|c| ledger.idents.get(c)).is_some_and(|i| *i == ident);
let Some(q) = a["question"].as_str() else { continue };
if about && latest.get(q).is_none_or(|b| at(a) >= at(b)) {
latest.insert(q, a);
}
}
let mut open = Vec::new();
let mut unasked = Vec::new();
for q in &mine {
let a = latest.get(q.id.as_str());
let flagged = a.is_some_and(|a| a["flagged"] == true);
let p = a.and_then(|a| a["problem"].as_f64()).map(|p| format!(" (p {p:.2})")).unwrap_or_default();
if q.calibrated() {
match a {
None => unasked.push(*q),
Some(_) if flagged && !notes.contains(&q.id) => open.push(format!("{} flagged{p}: {}", q.id, q.fix.as_deref().unwrap_or("fix it, or answer it in NOTES.md by its id"))),
_ => {}
}
} else if flagged {
advice.push(format!("{rel}: {} says yes{p}, advice until calibrated: {}", q.id, q.fix.as_deref().unwrap_or("")));
}
}
if !unasked.is_empty() {
open.push(format!("not asked of this {kind} sheet yet: {}", command(file, &unasked)));
}
let calibrated = mine.iter().filter(|q| q.calibrated()).count();
let says = match (open.is_empty(), calibrated) {
(true, 0) => format!("advice only: none of its {} questions is calibrated yet (raea ask calibrate)", mine.len()),
(true, n) => format!("{n} calibrated question{} clear", if n == 1 { "" } else { "s" }),
(false, _) => open.join("; "),
};
let mut g = json!({"gate": "ask", "of": rel, "clear": open.is_empty(), "says": says});
g["ask"] = json!(command(file, &mine));
gates.push(g);
}
(gates, advice)
}
fn at(a: &Value) -> u64 {
a["at"].as_str().and_then(|s| s.parse().ok()).or_else(|| a["at"].as_u64()).unwrap_or(0)
}
+157
View File
@@ -0,0 +1,157 @@
//! The plan stop (docs/goal.feature MK18, from AnyScene's endpoint/floorplan.py, MIT): before anything is generated,
//! the plan drawn so a person can approve it. A floor plan from above (every object's footprint at its `at`, turned by
//! its `rot`, labelled; invented ones dashed, so what came from the reference and what was added are told apart), a
//! grey-box blockout of the same plan rendered from the entrance and through `raea render --review`, and the
//! reference beside the blockout on one comparison sheet.
//!
//! raea make blockout [DIR] -> review/plan/floor-plan.png, blockout.tsx, blockout.png, comparison.png, colour/clay sheets
use std::path::{Path, PathBuf};
use raea_core_brief::goal::{Goal, Object, Origin};
use crate::sheet::{Tile, esc, sheet, svg_png};
use crate::shots::raea;
/// An object's footprint, metres: [width, depth] (its box, else a square about as wide as it's tall).
pub fn footprint(o: &Object) -> [f64; 2] {
if let Some([w, d, _]) = o.dims {
return [w, d];
}
let s = o.max.unwrap_or_else(|| o.h.unwrap_or(0.5) * 0.6).max(0.05);
[s, s]
}
fn height(o: &Object) -> f64 {
o.dims.map(|d| d[2]).or(o.h).unwrap_or(0.05).max(0.01)
}
/// The placed objects and the floor they span: (objects with an `at`, [x0, z0, x1, z1] with half a metre around).
pub fn extent(m: &Goal) -> (Vec<&Object>, [f64; 4]) {
let placed: Vec<&Object> = m.objects.iter().filter(|o| o.at.is_some()).collect();
let mut b = [0.0f64, 0.0, 1.0, 1.0];
for o in &placed {
let at = o.at.unwrap();
let [w, d] = footprint(o);
let r = 0.5 * (w * w + d * d).sqrt();
b = [b[0].min(at[0] - r), b[1].min(at[2] - r), b[2].max(at[0] + r), b[3].max(at[2] + r)];
}
(placed, [b[0] - 0.5, b[1] - 0.5, b[2] + 0.5, b[3] + 0.5])
}
/// The floor plan as SVG: the entrance (z = 0) at the bottom, a metre grid, each footprint turned and labelled.
pub fn floor_svg(m: &Goal) -> Result<String, String> {
let (placed, [x0, z0, x1, z1]) = extent(m);
if placed.is_empty() {
return Err("raea make blockout: no object has an `at` (where it stands, in metres: x right, z away from the entrance)".into());
}
let px = (1400.0 / (x1 - x0).max(z1 - z0)).min(260.0);
let (w, h) = (((x1 - x0) * px).ceil() as u32 + 40, ((z1 - z0) * px).ceil() as u32 + 130);
// text sized to the plan, so it still reads once the plan is a third of a comparison sheet
let t = (w as f64 * 0.02).max(16.0);
// plan x right, z away from the entrance: up the page
let sx = |x: f64| (x - x0).mul_add(px, 20.0);
let sy = |z: f64| 70.0 + (z1 - z) * px;
let mut s = format!("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{w}\" height=\"{h}\"><rect width=\"100%\" height=\"100%\" fill=\"#f4f2ee\"/>");
s += &format!("<text x=\"20\" y=\"{:.0}\" font-size=\"{:.0}\" font-weight=\"bold\" fill=\"#222\">Floor plan: {} objects (solid: from the reference; dashed: invented)</text>", t * 1.6, t * 1.1, placed.len());
let mut g = x0.ceil();
while g <= x1 {
s += &format!("<line x1=\"{0:.1}\" y1=\"{1:.1}\" x2=\"{0:.1}\" y2=\"{2:.1}\" stroke=\"#dedad2\" stroke-width=\"1\"/>", sx(g), sy(z1), sy(z0));
g += 1.0;
}
let mut g = z0.ceil();
while g <= z1 {
s += &format!("<line x1=\"{1:.1}\" y1=\"{0:.1}\" x2=\"{2:.1}\" y2=\"{0:.1}\" stroke=\"#dedad2\" stroke-width=\"1\"/>", sy(g), sx(x0), sx(x1));
g += 1.0;
}
// the entrance: the front edge, and where the camera looks in from
s += &format!("<line x1=\"{0:.1}\" y1=\"{1:.1}\" x2=\"{2:.1}\" y2=\"{1:.1}\" stroke=\"#3a7bd5\" stroke-width=\"4\"/>", sx(x0), sy(z0), sx(x1));
s += &format!("<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"{:.0}\" fill=\"#3a7bd5\" text-anchor=\"middle\">entrance: the camera looks in from here</text>", (sx(x0) + sx(x1)) / 2.0, sy(z0) + t * 1.3, t * 0.9);
for o in &placed {
let at = o.at.unwrap();
let [fw, fd] = footprint(o);
let invented = o.source == Some(Origin::Invented);
let dash = if invented { " stroke-dasharray=\"8 5\"" } else { "" };
let fill = if o.hero == Some(true) { "#f2c46d" } else if invented { "#ece8f4" } else { "#d9e4d2" };
s += &format!(
"<g transform=\"translate({:.1} {:.1}) rotate({:.1})\"><rect x=\"{:.1}\" y=\"{:.1}\" width=\"{:.1}\" height=\"{:.1}\" fill=\"{fill}\" stroke=\"#333\" stroke-width=\"2\"{dash}/><line x1=\"0\" y1=\"0\" x2=\"0\" y2=\"{:.1}\" stroke=\"#333\" stroke-width=\"2\"/></g>",
sx(at[0]),
sy(at[2]),
-o.rot.unwrap_or(0.0),
-fw * px / 2.0,
-fd * px / 2.0,
fw * px,
fd * px,
fd * px / 2.0
);
s += &format!("<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"{:.0}\" fill=\"#111\" text-anchor=\"middle\">{}</text>", sx(at[0]), sy(at[2]) - t * 0.25, t, esc(&o.label));
s += &format!("<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"{:.0}\" fill=\"#555\" text-anchor=\"middle\">{:.2} m{}</text>", sx(at[0]), sy(at[2]) + t * 0.9, t * 0.8, height(o), o.lod.map(|l| format!(", LOD {l}")).unwrap_or_default());
}
s += &format!("<line x1=\"20\" y1=\"{0}\" x2=\"{1:.1}\" y2=\"{0}\" stroke=\"#111\" stroke-width=\"5\"/><text x=\"20\" y=\"{2:.0}\" font-size=\"{3:.0}\" fill=\"#111\">1 m</text>", h - 18, 20.0 + px, h as f64 - 26.0, t * 0.9);
s += "</svg>";
Ok(s)
}
/// The blockout: a grey box for each placed object at its place and turn on a floor, seen from the entrance.
pub fn blockout_tsx(m: &Goal) -> String {
let (placed, [x0, z0, x1, z1]) = extent(m);
let mut boxes = String::new();
for o in &placed {
let at = o.at.unwrap();
let [w, d] = footprint(o);
let h = height(o);
let colour = if o.source == Some(Origin::Invented) { "#b4b0bd" } else { "#bdbdb8" };
let a = -o.rot.unwrap_or(0.0).to_radians() / 2.0;
let lod = o.lod.map(|l| format!(" lod={{{l}}}")).unwrap_or_default();
boxes += &format!(
" <Mesh3d name=\"{}\"{lod} transform={{Transform.fromXyz({:.3}, {:.3}, {:.3}).withRotation([0, {:.5}, 0, {:.5}])}}>\n <Cuboid half_size={{[{:.3}, {:.3}, {:.3}]}} />\n <StandardMaterial base_color=\"{colour}\" perceptual_roughness={{0.9}} />\n </Mesh3d>\n",
o.id,
at[0],
at[1] + h / 2.0,
at[2],
a.sin(),
a.cos(),
w / 2.0,
h / 2.0,
d / 2.0
);
}
let (cx, cz) = ((x0 + x1) / 2.0, (z0 + z1) / 2.0);
let (fw, fd) = ((x1 - x0) / 2.0, (z1 - z0) / 2.0);
format!(
"// written by raea make blockout: the plan as grey boxes, seen from the entrance (approve it before anything is made)\nimport {{ AbsoluteFill, Composition, registerRoot }} from \"raea\";\nimport {{ StandardMaterial }} from \"raea/pbr\";\nimport {{ Cuboid, Mesh3d }} from \"raea/mesh\";\nimport {{ AmbientLight, DirectionalLight }} from \"raea/light\";\nimport {{ Transform }} from \"raea/transform\";\nimport {{ Camera3d }} from \"raea/camera\";\n\nfunction Blockout() {{\n return (\n <AbsoluteFill style={{{{ background: \"#cfd3d6\" }}}}>\n <Camera3d transform={{Transform.fromXyz({cx:.3}, 1.6, {ez:.3}).lookingAt([{cx:.3}, 0.9, {cz:.3}])}} projection={{{{ Perspective: {{ fov: (50 * Math.PI) / 180 }} }}}} />\n <AmbientLight brightness={{350}} />\n <DirectionalLight transform={{Transform.fromXyz({lx:.3}, 6, -2).lookingAt([{cx:.3}, 0, {cz:.3}])}} illuminance={{8000}} shadow_maps_enabled />\n <Mesh3d transform={{Transform.fromXyz({cx:.3}, -0.01, {cz:.3})}}>\n <Cuboid half_size={{[{fw:.3}, 0.01, {fd:.3}]}} />\n <StandardMaterial base_color=\"#e6e3dc\" perceptual_roughness={{0.95}} />\n </Mesh3d>\n{boxes} </AbsoluteFill>\n );\n}}\n\nregisterRoot(() => <Composition id=\"blockout\" component={{Blockout}} width={{1280}} height={{720}} fps={{30}} durationInFrames={{1}} />);\n",
ez = z0 - 0.4,
lx = cx + 2.0,
)
}
pub fn plan_dir(dir: &Path) -> PathBuf {
dir.join("review/plan")
}
/// The plan stop's pictures: floor plan, blockout (and its review sheets), and the comparison with reference 0.
pub fn draw_plan(dir: &Path, m: &Goal, review: bool) -> Result<String, String> {
let out = plan_dir(dir);
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
let floor = out.join("floor-plan.png");
svg_png(&floor_svg(m)?)?.save(&floor).map_err(|e| format!("{}: {e}", floor.display()))?;
let tsx = out.join("blockout.tsx");
std::fs::write(&tsx, blockout_tsx(m)).map_err(|e| format!("{}: {e}", tsx.display()))?;
let shot = out.join("blockout.png");
raea(&["render".into(), tsx.display().to_string(), "-o".into(), shot.display().to_string(), "--frame".into(), "0".into()], &[])?;
let mut said = vec![format!("wrote {}", floor.display()), format!("wrote {}", shot.display())];
if review {
raea(&["render".into(), tsx.display().to_string(), "--review".into(), out.display().to_string()], &[])?;
said.push(format!("review sheets of the blockout in {}", out.display()));
}
let mut row = Vec::new();
if let Some(r) = m.references.first() {
row.push(Tile { img: dir.join(r), label: "reference".into() });
}
row.push(Tile { img: shot, label: "blockout from the entrance".into() });
row.push(Tile { img: floor, label: "floor plan".into() });
let cmp = out.join("comparison.png");
sheet("Plan: the reference, the blockout from the entrance, the floor plan", &[row], 640, &cmp)?;
said.push(format!("wrote {}: approve the plan (positions, sizes, what's invented) before any generation", cmp.display()));
Ok(said.join("\n"))
}
+202
View File
@@ -0,0 +1,202 @@
//! A scene, kit or shot job's record and critic gates (docs/goal.feature MK38), from what's on disk and nothing the agent
//! says: the record of renders and checks, the parts seen closer than planned, the judge's rounds on the kind's rubric
//! and the make questions asked of its sheets. `raea goal gates --json` prints them, and raea/goal's record and critic
//! packs hold the job to them (sdk/goal/src/packs/job.ts); deliverables and notes are packs of their own. Pure over a
//! `Job` so it is tested on fixtures.
use std::{path::{Path, PathBuf}, time::SystemTime};
use raea_core_brief::goal::{self, Goal};
use raea_core_facts::{Level, record::Entry};
use serde_json::{Value, json};
/// Everything the gates read, gathered by `lib.rs` (or a test).
pub struct Job<'a> {
pub make: &'a Goal,
/// the brief's folder: deliverables, NOTES.md and review/ are relative to it
pub dir: &'a Path,
/// the project's folder (record paths are relative to it), when it is a raea project
pub project: Option<&'a Path>,
pub record: &'a [Entry],
/// review/judge.log.jsonl's rounds, oldest first
pub rounds: &'a [Value],
/// the latest round's judge.json, when there is one
pub verdict: Option<&'a Value>,
/// when the judge last wrote its log
pub judged_at: Option<SystemTime>,
/// `raea ask`'s ledger, for the make questions' gate (asked.rs)
pub ledger: &'a crate::asked::Ledger,
/// `raea judge calibrate --kind KIND` agreed with the person's eye for this kind: its score gates too (MK6)
pub score_gates: bool,
}
/// A round's folder: as the judge wrote it when absolute, else the folder of that name beside the log (review/), since
/// `raea judge DIR` keeps its log in DIR's parent and DIR was written relative to wherever it ran.
pub fn round_dir(dir: &Path, round: &Value) -> Option<PathBuf> {
let d = Path::new(round["dir"].as_str()?);
if d.is_absolute() {
return Some(d.to_path_buf());
}
Some(dir.join("review").join(d.file_name()?))
}
/// The sheets the make questions are asked of: the newest round's (its framing sheet for a shot list, its colour and
/// clay sheets otherwise) and a kit's reference sheet.
pub fn sheets(job: &Job) -> Vec<(&'static str, PathBuf)> {
let mut out = Vec::new();
if let Some(r) = job.rounds.last().and_then(|r| round_dir(job.dir, r)) {
if job.make.kind == goal::Kind::Shot {
out.push(("framing", r.join("framing.png")));
} else {
out.push(("clay", r.join("clay.png")));
out.push(("colour", r.join("colour.png")));
}
}
if job.make.kind == goal::Kind::Kit {
out.push(("refs", job.dir.join("review/refs.png")));
}
out.into_iter().filter(|(_, f)| f.is_file()).collect()
}
/// When a file last changed, and that as seconds since 1970 (a record entry's clock).
fn mtime(p: &Path) -> Option<SystemTime> {
std::fs::metadata(p).ok()?.modified().ok()
}
fn mtime_secs(p: &Path) -> Option<u64> {
Some(mtime(p)?.duration_since(SystemTime::UNIX_EPOCH).ok()?.as_secs())
}
fn is_picture(p: &Path) -> bool {
matches!(p.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref(), Some("png" | "jpg" | "jpeg" | "exr"))
}
/// One deliverable: a file, `a|b` (either), or `dir/` (three or more pictures in it). Returns the files that answer it.
fn answered(dir: &Path, want: &str) -> Result<Vec<PathBuf>, String> {
if let Some(folder) = want.strip_suffix('/') {
let pics: Vec<PathBuf> = std::fs::read_dir(dir.join(folder)).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| is_picture(p)).collect();
return if pics.len() >= 3 { Ok(pics) } else { Err(format!("{want} holds {} picture{}; three or more", pics.len(), if pics.len() == 1 { "" } else { "s" })) };
}
let found: Vec<PathBuf> = want.split('|').map(|w| dir.join(w)).filter(|p| p.is_file()).collect();
if found.is_empty() { Err(want.replace('|', " or ")) } else { Ok(found) }
}
fn notes_text(dir: &Path) -> Option<String> {
std::fs::read_to_string(dir.join("NOTES.md")).ok()
}
/// AnyKit's stall: three rounds in a row without beating the best mean before them. Not the judge's own `stall`
/// (the same defect twice: change the approach), which is advice to the agent, not a reason to let it stop.
pub fn stalled(rounds: &[Value]) -> bool {
let means: Vec<f64> = rounds.iter().filter_map(|r| r["mean"].as_f64()).collect();
means.len() >= 4 && {
let (before, last) = means.split_at(means.len() - 3);
last.iter().cloned().fold(f64::MIN, f64::max) <= before.iter().cloned().fold(f64::MIN, f64::max)
}
}
fn gate(name: &str, of: Option<&str>, clear: bool, says: String) -> Value {
let mut g = json!({"gate": name, "clear": clear, "says": says});
if let Some(of) = of {
g["of"] = json!(of);
}
g
}
/// Tier 1: each composition the plan names has a render or check newer than it that found no error.
fn checks(job: &Job) -> Vec<Value> {
job.make
.compositions
.iter()
.map(|c| {
let file = job.dir.join(c);
let rel = job.project.map(|p| raea_core_facts::record::rel(p, &file)).unwrap_or_else(|| c.clone());
let Some(last) = job.record.iter().rev().find(|e| e.of == rel) else {
return gate("checks", Some(c), false, format!("never rendered or checked: raea render {c} (or raea scene lint {c})"));
};
let changed = mtime_secs(&file);
if changed.is_some_and(|t| t > last.at) {
return gate("checks", Some(c), false, format!("changed since its last {} ({}): run it again", last.by, last.id));
}
let errors: Vec<&str> = last.findings.iter().filter(|f| f.level == Level::Error).map(|f| f.says.as_str()).collect();
match errors.as_slice() {
[] => gate("checks", Some(c), true, format!("clean at {} ({})", last.id, last.by)),
[one] => gate("checks", Some(c), false, format!("{} found: {one}", last.id)),
many => gate("checks", Some(c), false, format!("{} found {} errors, first: {}", last.id, many.len(), many[0])),
}
})
.collect()
}
/// MK24: parts a composition's last render showed closer than planned, held until replanned or answered (raea-runtime-lod-plan)
fn lods(job: &Job, notes: &str) -> Vec<Value> {
let plans = job.make.objects.iter().any(|o| o.lod.is_some());
let last = |c: &String| job.record.iter().rev().find(|e| e.of == job.project.map(|p| raea_core_facts::record::rel(p, &job.dir.join(c))).unwrap_or_else(|| c.clone()));
job.make.compositions.iter().filter_map(|c| last(c).and_then(|l| raea_runtime_lod_plan::gate(c, &l.id, &l.findings, notes, plans)).map(|(clear, says)| gate("lod", Some(c), clear, says))).collect()
}
/// Tier 3: a fresh critic has judged a round newer than the newest deliverable, and each blocking defect it named is
/// fixed (the round passed) or answered in NOTES.md by its name. Its score gates once the judge is calibrated.
fn critic(job: &Job, newest: Option<SystemTime>, notes: &str) -> Vec<Value> {
let Some(last) = job.rounds.last() else {
let kind = job.make.kind.name();
let what = match job.make.kind {
goal::Kind::Kit => "raea render shared/components/KIT/lineup.tsx --review review/r1",
goal::Kind::Shot => "raea make framing --out review/r1",
goal::Kind::Scene | goal::Kind::Cut | goal::Kind::Rules => "raea render EDIT.tsx --review review/r1",
};
return vec![gate("critic", None, false, format!("no round yet: {what}, then raea judge review/r1 --kind {kind} --by claude --brief brief.ts"))];
};
let mut out = Vec::new();
let fresh = match (job.judged_at, newest) {
(Some(j), Some(n)) => j >= n,
(Some(_), None) => true,
_ => false,
};
out.push(gate("critic", None, fresh, if fresh { format!("round {} judged after the newest deliverable", job.rounds.len()) } else { "the newest deliverable came after the last round: review and judge it again".into() }));
// the kind's own rubric (MK5): a round judged on another's doesn't count
let kind = job.make.kind.name();
if last["kind"].as_str() != Some(kind) {
let dir = last["dir"].as_str().unwrap_or("review/rN");
out.push(gate("rubric", None, false, format!("the last round wasn't judged on the {kind} rubric: raea judge {dir} --kind {kind} --by claude")));
}
let blocking: Vec<&str> = raea_app_judge::rubric::blocking(last["defects"].as_array().map(Vec::as_slice).unwrap_or_default());
let open: Vec<&str> = if last["pass"] == true { Vec::new() } else { blocking.into_iter().filter(|d| !notes.contains(d)).collect() };
out.push(gate("defects", None, open.is_empty(), if open.is_empty() { "no blocking defect left unanswered".into() } else { format!("blocking, neither fixed nor answered in NOTES.md: {}", open.join(", ")) }));
// the score gates once the judge is calibrated for this kind; before that, fixed-or-answered is enough (MK6)
if job.score_gates {
let p = raea_app_judge::progress(job.rounds);
let done = p["done"] == true;
out.push(gate("score", None, done, format!("the calibrated judge: {} passes in a row, two needed", p["passesInARow"])));
}
out
}
/// The job's gates: each, whether all are clear, and why it's delivered short (out of rounds, or stalled) when it is.
pub fn gates(job: &Job) -> Value {
// the newest deliverable: a round judged before it is stale (the deliverables pack says what's missing)
let newest = goal::deliverables(job.make).iter().filter_map(|w| answered(job.dir, w).ok()).flatten().filter_map(|f| mtime(&f)).max();
let notes = notes_text(job.dir).unwrap_or_default();
let mut gates = checks(job);
gates.extend(lods(job, &notes));
gates.extend(critic(job, newest, &notes));
let (asks, said) = crate::asked::gates(&sheets(job), job.ledger, &notes);
gates.extend(asks);
let cap = job.make.rounds.unwrap_or(goal::ROUNDS) as usize;
let clear = gates.iter().all(|g| g["clear"] == true);
let mut short = Vec::new();
if job.rounds.len() >= cap && !clear {
short.push(format!("capped: {} critic rounds, the most this job gets; delivered with what's still open", job.rounds.len()));
}
if stalled(job.rounds) && !clear {
short.push("stalled: three rounds without beating the best before them; delivered with what's still open".to_string());
}
let advice = raea_app_judge::progress(job.rounds);
json!({
"kind": job.make.kind,
"clear": clear,
"short": short,
"gates": gates,
"judge": {"rounds": job.rounds.len(), "cap": cap, "passesInARow": advice["passesInARow"], "changeApproach": advice["stall"], "again": advice["again"]},
"advice": said,
})
}
+300
View File
@@ -0,0 +1,300 @@
//! A kit's steps (docs/goal.feature MK10-MK12, from AnyKit): every object's reference made in one style from the
//! style images, checked on one sheet before any 3D; each reference to both generators (Tripo H3.1 and Meshy, on fal)
//! and the pick made on clay renders (kitout.rs draws the pick sheets); the pick fitted to its real size with a
//! quarter-triangle LOD beside it, each with a sidecar saying how it was made.
//!
//! raea make refs [DIR] [--only ID,...] [--model M] [--dry]
//! raea make sheet refs [DIR]
//! raea make gen [DIR] [--only ID,...] [--tripo M] [--meshy M] [--dry]
//! raea make pick ID GENERATOR "why"
//! raea make prep [DIR] [--only ID,...]
use std::path::{Path, PathBuf};
use raea_core_brief::goal::{Goal, Object};
use serde_json::{Value, json};
use crate::sheet::{Tile, sheet};
use crate::shots::raea;
/// What every reference prompt ends with: one object, whole, on a plain ground, in even light (the scan template).
pub const SCAN: &str = "One object only, whole and centred, on a plain light grey background, soft even studio light, a three-quarter view from slightly above. Its own printed labels only, from the one maker named; no real brands, no text overlays.";
/// The two generators every reference goes to (MK11).
pub const TRIPO: &str = "tripo:H3.1";
pub const MESHY: &str = "fal:meshy/v7.1/image-to-3d";
/// Face limits: a hero, a small prop.
const HERO_FACES: u32 = 150_000;
const PROP_FACES: u32 = 60_000;
/// The objects named in `--only` (all when it's empty).
pub fn objects<'a>(m: &'a Goal, only: &[String]) -> Vec<&'a Object> {
crate::only(&m.objects, only, |o| o.id.as_str())
}
/// The prompt a reference is made from: the plan's style paragraph, the object's own words, the scan template.
pub fn ref_prompt(m: &Goal, o: &Object) -> String {
let style = m.style.as_deref().unwrap_or("").trim().trim_end_matches('.');
let what = o.prompt.as_deref().unwrap_or(&o.label).trim().trim_end_matches('.');
format!("{style}. {what}. {SCAN}")
}
/// `--h`, `--dims` or nothing: how gen check fits an object to its real size.
pub fn size_args(o: &Object) -> Vec<String> {
if let Some([w, d, h]) = o.dims {
return vec!["--dims".into(), format!("{w},{d},{h}")];
}
if let Some(h) = o.h {
return vec!["--h".into(), h.to_string()];
}
Vec::new()
}
/// How `raea gen check -o` fits one generator's model to the object's size: its height (`--h`, which is what scales;
/// a boxy object's is the third of its dims) and, for a boxy one, a quarter turn when the model's long side lies
/// across (x) where the plan's lies front to back (z), or the other way: generators don't agree on which way is front.
/// `measured` is the raw model's [w, h, d] (`raea gen check --json`'s measured.size).
pub fn fit_args(o: &Object, measured: Option<[f64; 3]>) -> Vec<String> {
let mut a = size_args(o);
if let Some([w, d, h]) = o.dims {
a.extend(["--h".into(), h.to_string()]);
if let Some([mw, _, md]) = measured {
let long = |x: f64, z: f64| if x > z * 1.2 { Some(true) } else if z > x * 1.2 { Some(false) } else { None };
if let (Some(want), Some(got)) = (long(w, d), long(mw, md)) {
if want != got {
a.extend(["--turn".into(), "90".into()]);
}
}
}
}
a
}
/// The raw model's size [w, h, d], measured by `raea gen check --json`.
pub fn measured_size(model: &Path) -> Option<[f64; 3]> {
let out = raea(&["gen".into(), "check".into(), model.display().to_string(), "--json".into()], &[]).ok()?;
let v = json_of(&out)?;
let s = v["measured"]["size"].as_array()?;
Some([s.first()?.as_f64()?, s.get(1)?.as_f64()?, s.get(2)?.as_f64()?])
}
/// The file a single-shot `raea gen` wrote: its JSON's `out.out`, a path or the first of a list.
pub fn gen_file(out: &str) -> Option<PathBuf> {
let v: Value = serde_json::from_str(out.trim()).ok()?;
let o = &v["out"]["out"];
o.as_str().or_else(|| o.as_array()?.first()?.as_str()).map(PathBuf::from)
}
fn cents(out: &str) -> f64 {
json_of(out).and_then(|v| v["cents"].as_f64()).unwrap_or(0.0)
}
/// raea gen's JSON from its output (anything printed before it skipped).
fn json_of(out: &str) -> Option<Value> {
serde_json::from_str(out[out.find('{')?..].trim()).ok()
}
/// A `--plan` or `gen plan` quote in a line: what each paid step runs on, and the total.
pub fn quote(out: &str) -> String {
let Some(v) = json_of(out) else { return out.split_whitespace().collect::<Vec<_>>().join(" ") };
let on: Vec<&str> = v["steps"].as_array().into_iter().flatten().filter_map(|s| s["runs_on"].as_str()).filter(|r| *r != "load").collect();
format!("{} (about {}¢)", if on.is_empty() { "nothing paid".to_string() } else { on.join(" + ") }, v["cents"].as_f64().unwrap_or(0.0))
}
pub fn refs_dir(dir: &Path) -> PathBuf {
dir.join("out/kit/refs")
}
/// Every object's reference, made from the style images (`references`) in the plan's style; then the sheet.
pub fn refs(dir: &Path, m: &Goal, only: &[String], model: Option<&str>, dry: bool) -> Result<String, String> {
if m.references.is_empty() {
return Err("raea make refs: the plan has no `references` (the style images every reference is made from)".into());
}
let mut said = Vec::new();
let mut spent = 0.0;
for o in objects(m, only) {
let work = refs_dir(dir).join("gen").join(&o.id);
let mut args: Vec<String> = vec!["gen".into(), "image".into(), ref_prompt(m, o)];
for r in &m.references {
args.extend(["--image".into(), dir.join(r).display().to_string()]);
}
args.extend(["--aspect".into(), "1:1".into(), "-o".into(), work.display().to_string()]);
if let Some(md) = model {
args.extend(["--model".into(), md.to_string()]);
}
if dry {
args.push("--plan".into());
let out = raea(&args, &[])?;
spent += cents(&out);
said.push(format!("{}: {}", o.id, quote(&out)));
continue;
}
eprintln!("raea make refs: {}", o.id);
let out = raea(&args, &[])?;
spent += cents(&out);
let made = gen_file(&out).ok_or_else(|| format!("{}: raea gen image wrote no file: {}", o.id, out.trim()))?;
let to = refs_dir(dir).join(format!("{}.png", o.id));
std::fs::copy(&made, &to).map_err(|e| format!("{}: {e}", to.display()))?;
said.push(format!("{}: {}", o.id, to.display()));
}
if dry {
return Ok(format!("would make {} reference{} for about ${:.2} (nothing spent):\n{}", said.len(), if said.len() == 1 { "" } else { "s" }, spent / 100.0, said.join("\n")));
}
let sheet = sheet_refs(dir, m)?;
Ok(format!("{}\n{sheet}\nspent about ${:.2}", said.join("\n"), spent / 100.0))
}
/// The reference sheet: the style images first, then every object's reference, labelled with its id and size.
pub fn sheet_refs(dir: &Path, m: &Goal) -> Result<String, String> {
let style: Vec<Tile> = m.references.iter().enumerate().map(|(i, r)| Tile { img: dir.join(r), label: format!("style {}", i + 1) }).collect();
let refs: Vec<Tile> = m
.objects
.iter()
.map(|o| {
let size = o.h.map(|h| format!("{h} m tall")).or(o.dims.map(|d| format!("{} x {} x {} m", d[0], d[1], d[2]))).or(o.max.map(|x| format!("{x} m long"))).unwrap_or_default();
Tile { img: refs_dir(dir).join(format!("{}.png", o.id)), label: format!("{} {size}", o.id) }
})
.collect();
let mut rows = vec![style];
rows.extend(refs.chunks(4).map(|c| c.iter().map(|t| Tile { img: t.img.clone(), label: t.label.clone() }).collect()));
let file = dir.join("review/refs.png");
sheet("Reference sheet: the style, then every object's reference", &rows, 320, &file)?;
Ok(format!("wrote {}: regenerate an outlier before any 3D (raea make refs --only ID); ask it: raea ask {} --std make.refs.outlier --std make.refs.two_objects --std make.refs.brands", file.display(), file.display()))
}
/// The flow that sends one reference to both generators, each at its face limit.
pub fn gen_flow(m: &Goal, o: &Object, reference: &Path, tripo: &str, meshy: &str) -> Value {
let faces = if o.hero == Some(true) { HERO_FACES } else { PROP_FACES };
let prompt = o.prompt.clone().unwrap_or_else(|| o.label.clone());
let _ = m;
json!({"flow": 1, "steps": {
"ref": {"op": "media.load", "in": {"path": reference.display().to_string()}},
"tripo": {"op": "mesh.generate", "model": tripo, "in": {"prompt": prompt, "image": "@ref", "x_face_limit": faces}},
"meshy": {"op": "mesh.generate", "model": meshy, "in": {"prompt": prompt, "image": "@ref"}}
}, "out": ["tripo", "meshy"]})
}
pub fn gen_dir(dir: &Path, id: &str) -> PathBuf {
dir.join("out/kit/gen").join(id)
}
/// Every reference to both generators: out/kit/gen/ID/tripo.glb and meshy.glb.
pub fn generate(dir: &Path, m: &Goal, only: &[String], tripo: &str, meshy: &str, dry: bool) -> Result<String, String> {
let mut said = Vec::new();
let mut spent = 0.0;
for o in objects(m, only) {
let reference = refs_dir(dir).join(format!("{}.png", o.id));
if !reference.is_file() {
return Err(format!("raea make gen: no reference for {} ({}): raea make refs --only {}", o.id, reference.display(), o.id));
}
let to = gen_dir(dir, &o.id);
// both models already there: a rerun (after a stop, or for the pieces still missing) doesn't pay twice
if !dry && to.join("tripo.glb").is_file() && to.join("meshy.glb").is_file() {
said.push(format!("{}: already made ({})", o.id, to.display()));
continue;
}
std::fs::create_dir_all(&to).map_err(|e| format!("{}: {e}", to.display()))?;
if !dry {
eprintln!("raea make gen: {} on {tripo} and {meshy} (a few minutes each)", o.id);
}
let flow = to.join("flow.json");
std::fs::write(&flow, serde_json::to_string_pretty(&gen_flow(m, o, &reference, tripo, meshy)).unwrap_or_default()).map_err(|e| e.to_string())?;
// quoted first: the run is capped at its own quote (a little over, for rounding), never gen's default cap
let plan = raea(&["gen".into(), "plan".into(), flow.display().to_string()], &[])?;
let out = if dry {
plan
} else {
let cap = (cents(&plan) * 1.1).ceil().max(1.0) as u64;
raea(&["gen".into(), "run".into(), flow.display().to_string(), "-o".into(), to.display().to_string(), "--max-cents".into(), cap.to_string()], &[])?
};
spent += cents(&out);
said.push(if dry { format!("{}: {}", o.id, quote(&out)) } else { format!("{}: {}", o.id, to.display()) });
}
let tail = if dry { format!("about ${:.2} in all; nothing spent", spent / 100.0) } else { format!("spent about ${:.2}; next: raea make pick-sheet", spent / 100.0) };
Ok(format!("{}\n{tail}", said.join("\n")))
}
/// The model a pick's generator ran (from its flow.json), for the sidecar.
fn pick_model(dir: &Path, id: &str, generator: &str) -> String {
let flow: Option<Value> = std::fs::read_to_string(gen_dir(dir, id).join("flow.json")).ok().and_then(|t| serde_json::from_str(&t).ok());
flow.and_then(|f| f["steps"][generator]["model"].as_str().map(String::from)).unwrap_or_else(|| generator.to_string())
}
pub fn picks_file(dir: &Path) -> PathBuf {
dir.join("out/kit/picks.json")
}
/// The picks so far, by object id: {generator, why}.
pub fn picks(dir: &Path) -> serde_json::Map<String, Value> {
std::fs::read_to_string(picks_file(dir)).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()
}
/// One object's pick and why, recorded (MK11).
pub fn choose(dir: &Path, m: &Goal, id: &str, generator: &str, why: &str) -> Result<String, String> {
if !m.objects.iter().any(|o| o.id == id) {
return Err(format!("raea make pick: no object `{id}` in the plan"));
}
let glb = gen_dir(dir, id).join(format!("{generator}.glb"));
if !glb.is_file() {
return Err(format!("raea make pick: no {} (the generators are tripo and meshy: raea make gen --only {id})", glb.display()));
}
if why.trim().is_empty() {
return Err("raea make pick: say why in one line (\"sharper dial numerals; Tripo fused the handset to the cradle\")".into());
}
let mut p = picks(dir);
p.insert(id.into(), json!({"generator": generator, "why": why.trim()}));
let f = picks_file(dir);
std::fs::write(&f, serde_json::to_string_pretty(&p).unwrap_or_default()).map_err(|e| format!("{}: {e}", f.display()))?;
Ok(format!("picked {generator} for {id}: {}", why.trim()))
}
/// The triangles gen check measured.
fn triangles(glb: &Path) -> Result<u64, String> {
let out = raea(&["gen".into(), "check".into(), glb.display().to_string(), "--json".into()], &[]).or_else(|e| if e.contains('{') { Ok(e) } else { Err(e) })?;
let v: Value = serde_json::from_str(out.trim()).map_err(|e| format!("gen check {}: {e}", glb.display()))?;
v["measured"]["triangles"].as_u64().ok_or_else(|| format!("gen check couldn't read {}", glb.display()))
}
/// Each pick fitted to its real size (front -Y, bottom-centre, metres) and a quarter-triangle LOD1 beside it, each
/// with a sidecar saying how it was made (MK12).
pub fn prep(dir: &Path, m: &Goal, only: &[String]) -> Result<String, String> {
let p = picks(dir);
let mut said = Vec::new();
for o in objects(m, only) {
let Some(pick) = p.get(&o.id) else {
said.push(format!("{}: no pick yet (raea make pick {} tripo|meshy \"why\")", o.id, o.id));
continue;
};
let generator = pick["generator"].as_str().unwrap_or("tripo");
let src = gen_dir(dir, &o.id).join(format!("{generator}.glb"));
let to = dir.join("out/kit").join(&o.id);
std::fs::create_dir_all(&to).map_err(|e| format!("{}: {e}", to.display()))?;
let full = to.join(format!("{}.glb", o.id));
let mut args = vec!["gen".into(), "check".into(), src.display().to_string()];
args.extend(fit_args(o, measured_size(&src)));
args.extend(["-o".into(), full.display().to_string()]);
// gen check exits non-zero on a finding it can't fix; the fitted copy is still written, and its findings said
let _ = raea(&args, &[]);
if !full.is_file() {
return Err(format!("{}: gen check wrote no fitted copy of {}", o.id, src.display()));
}
let tris = triangles(&full)?;
let lod = to.join(format!("{}_lod1.glb", o.id));
let quarter = (tris / 4).max(500);
let model = pick_model(dir, &o.id, generator);
// the sidecar the Blender scripts carry along (source, licence, credit) and how it was made: ours, generated
let made = |what: &str, tris: u64| {
json!({"source": format!("generated by raea make: {model} from out/kit/refs/{}.png", o.id), "license": "ours (generated for this project)", "credit": "",
"made": {"by": "raea make (docs/goal.feature)", "route": "gen", "generator": generator, "model": model, "why": pick["why"], "prompt": o.prompt, "reference": format!("out/kit/refs/{}.png", o.id),
"style": m.style, "what": what, "triangles": tris, "source": if o.source.is_some() { json!(o.source) } else { Value::Null }}})
};
std::fs::write(full.with_extension("glb.json"), serde_json::to_string_pretty(&made("fitted to its real size", tris)).unwrap_or_default()).map_err(|e| e.to_string())?;
raea(&["blender".into(), "run".into(), "blender/decimate.py".into(), full.display().to_string(), lod.display().to_string(), quarter.to_string()], &[])?;
// decimate.py wrote the LOD's sidecar from the model's, with its step; it says what it is, over the copy
let side = lod.with_extension("glb.json");
let mut v: Value = std::fs::read_to_string(&side).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_else(|| made("", 0));
v["made"] = made("LOD1: a quarter of the fitted model's triangles", quarter)["made"].clone();
std::fs::write(&side, serde_json::to_string_pretty(&v).unwrap_or_default()).map_err(|e| e.to_string())?;
said.push(format!("{}: {} ({tris} triangles) and its LOD1 ({quarter})", o.id, full.display()));
}
Ok(said.join("\n"))
}
+224
View File
@@ -0,0 +1,224 @@
//! The kit's sheets and its landing (docs/goal.feature MK11, MK13): the pick sheet (each object's reference beside
//! both generators' models, each in colour and in clay, drawn in raea), and the kit landed as a component set (one
//! component per object, its model and LOD imported beside it, so it travels as one folder), a `<Lineup>` of them all
//! with a scale bar, a thumb each, and kit.json.
//!
//! raea make pick-sheet [DIR] [--only ID,...]
//! raea make kit [DIR] [--name KIT] [--to FOLDER]
use std::path::{Path, PathBuf};
use raea_core_brief::goal::{Goal, Object};
use serde_json::{Value, json};
use crate::kit::{gen_dir, objects, picks};
use crate::sheet::{Tile, sheet};
use crate::shots::raea;
/// The tallest side an object will have once fitted, metres (for framing it): its height, its box, or its longest side.
pub fn tall(o: &Object) -> f64 {
o.h.or(o.dims.map(|d| d[2])).or(o.max).unwrap_or(0.5).max(0.02)
}
/// The size a model is framed to: its biggest side (a stapler is framed by its length, not its height).
pub fn frame_size(o: &Object) -> f64 {
o.dims.map(|[w, d, h]| w.max(d).max(h)).unwrap_or_else(|| tall(o))
}
/// A composition showing one model alone, fitted (bottom-centred at the origin, metres), on a pale floor in a
/// three-quarter view from slightly above, framed to its height.
pub fn viewer(model: &Path, h: f64) -> String {
let d = h * 3.2 + 0.06;
let m = model.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_default();
format!(
"// written by raea make (pick sheet, kit thumbs): one model, framed to its height\nimport {{ AbsoluteFill, Composition, registerRoot }} from \"raea\";\nimport {{ Model }} from \"raea/3d\";\nimport {{ StandardMaterial }} from \"raea/pbr\";\nimport {{ Cuboid, Mesh3d }} from \"raea/mesh\";\nimport {{ AmbientLight, DirectionalLight }} from \"raea/light\";\nimport {{ Transform }} from \"raea/transform\";\nimport {{ Camera3d }} from \"raea/camera\";\nimport model from \"./{m}\";\n\nfunction View() {{\n return (\n <AbsoluteFill style={{{{ background: \"#d9d6d0\" }}}}>\n <Camera3d transform={{Transform.fromXyz({x:.3}, {y:.3}, {z:.3}).lookingAt([0, {cy:.3}, 0])}} projection={{{{ Perspective: {{ fov: (30 * Math.PI) / 180 }} }}}} />\n <AmbientLight brightness={{300}} />\n <DirectionalLight transform={{Transform.fromXyz(2, 5, 3).lookingAt([0, 0, 0])}} illuminance={{9000}} shadow_maps_enabled />\n <Mesh3d transform={{Transform.fromXyz(0, -0.005, 0)}}>\n <Cuboid half_size={{[{g:.2}, 0.005, {g:.2}]}} />\n <StandardMaterial base_color=\"#cfccc6\" perceptual_roughness={{0.95}} />\n </Mesh3d>\n <Model src={{model}} />\n </AbsoluteFill>\n );\n}}\n\nregisterRoot(() => <Composition id=\"view\" component={{View}} width={{768}} height={{768}} fps={{30}} durationInFrames={{1}} />);\n",
x = d * 0.62,
y = h * 0.55 + d * 0.32,
z = d * 0.78,
cy = h * 0.45,
g = (h * 4.0).max(1.0),
)
}
/// One model drawn in colour and in clay: (colour.png, clay.png) beside it.
pub fn draw(model: &Path, h: f64) -> Result<(PathBuf, PathBuf), String> {
let dir = model.parent().ok_or("a model's folder")?;
let stem = model.file_stem().map(|f| f.to_string_lossy().to_string()).unwrap_or_default();
let tsx = dir.join(format!("{stem}.view.tsx"));
std::fs::write(&tsx, viewer(model, h)).map_err(|e| format!("{}: {e}", tsx.display()))?;
let (colour, clay) = (dir.join(format!("{stem}.colour.png")), dir.join(format!("{stem}.clay.png")));
raea(&["render".into(), tsx.display().to_string(), "-o".into(), colour.display().to_string(), "--frame".into(), "0".into()], &[])?;
raea(&["render".into(), tsx.display().to_string(), "-o".into(), clay.display().to_string(), "--frame".into(), "0".into(), "--clay".into()], &[])?;
Ok((colour, clay))
}
/// The pick sheet: a row an object, its reference, then each generator's model fitted to size, in colour and in clay.
pub fn pick_sheet(dir: &Path, m: &Goal, only: &[String]) -> Result<String, String> {
let mut rows = Vec::new();
for o in objects(m, only) {
let g = gen_dir(dir, &o.id);
let mut row = vec![Tile { img: crate::kit::refs_dir(dir).join(format!("{}.png", o.id)), label: format!("{} reference", o.id) }];
for generator in ["tripo", "meshy"] {
let raw = g.join(format!("{generator}.glb"));
if !raw.is_file() {
row.push(Tile { img: g.join("none.png"), label: format!("{generator}: not made") });
continue;
}
// fitted to its real size first, so both are framed alike
let fit = g.join(format!("{generator}.fit.glb"));
let mut args = vec!["gen".into(), "check".into(), raw.display().to_string()];
args.extend(crate::kit::fit_args(o, crate::kit::measured_size(&raw)));
args.extend(["-o".into(), fit.display().to_string()]);
let _ = raea(&args, &[]);
let shown = if fit.is_file() { fit } else { raw };
let (colour, clay) = draw(&shown, frame_size(o))?;
row.push(Tile { img: colour, label: generator.to_string() });
row.push(Tile { img: clay, label: format!("{generator} clay") });
}
rows.push(row);
}
if rows.is_empty() {
return Err("raea make pick-sheet: no objects in the plan (or none named)".into());
}
let file = dir.join("review/picks.png");
sheet("Pick sheet: reference | Tripo | Tripo clay | Meshy | Meshy clay", &rows, 300, &file)?;
Ok(format!("wrote {}: judge each on its clay (fused parts, blobs, fidelity to the reference), then: raea make pick ID tripo|meshy \"why\"", file.display()))
}
/// A component's name from an object id: rotary_phone -> RotaryPhone.
pub fn component_name(id: &str) -> String {
let mut out = String::new();
for w in id.split(['_', '-']) {
let mut c = w.chars();
out.extend(c.next().into_iter().flat_map(char::to_uppercase).chain(c));
}
out
}
/// One object's component: its model imported beside it, its LOD for far away, placed by the props a composition gives.
pub fn component(o: &Object, why: &str) -> String {
let n = component_name(&o.id);
format!(
"// raea make component add: {label}, {h} m, from the kit's style (raea make kit; {why})\nimport {{ Model }} from \"raea/3d\";\nimport full from \"./{id}.glb\";\nimport far from \"./{id}_lod1.glb\";\n\ntype Props = {{\n position?: [number, number, number];\n rotation?: [number, number, number];\n /** the quarter-triangle model, for when it's small on screen */\n lod?: boolean;\n}};\n\n/** {label}: fitted to its real size, its bottom at the origin, its front toward +z. */\nexport default function {n}({{ position = [0, 0, 0], rotation = [0, 0, 0], lod = false }}: Props) {{\n return <Model src={{lod ? far : full}} position={{position}} rotation={{rotation}} />;\n}}\n",
label = o.label,
h = tall(o),
id = o.id,
why = why.replace('\n', " "),
)
}
/// The lineup: every component side by side in the plan's order, gaps between, a label each lying in front of the pieces and a
/// scale bar (the longest round length the set covers), seen from a little right of centre and above.
pub fn lineup(m: &Goal, kit: &str) -> String {
let mut imports = String::new();
let mut parts = String::new();
let mut x = 0.0;
let foot = |o: &Object| o.dims.map(|d| (d[0], d[1])).unwrap_or((tall(o) * 0.8, tall(o) * 0.8));
let widths: Vec<f64> = m.objects.iter().map(|o| foot(o).0).collect();
let gap = (widths.iter().cloned().fold(0.0, f64::max) * 0.6).clamp(0.03, 0.3);
let total: f64 = widths.iter().sum::<f64>() + gap * (m.objects.len().saturating_sub(1)) as f64;
let highest = m.objects.iter().map(tall).fold(0.02, f64::max);
let deepest = m.objects.iter().map(|o| foot(o).1).fold(0.02, f64::max);
// labels lie on the floor in front of every piece, so none hides one; the bar in front of them
let fs = (total * 0.035).clamp(0.01, 0.06);
let lz = deepest / 2.0 + fs * 1.9;
let (bar, bar_label) = scale_bar(total);
let bz = lz + fs * 2.8;
for (o, w) in m.objects.iter().zip(&widths) {
let n = component_name(&o.id);
imports.push_str(&format!("import {n} from \"./{n}\";\n"));
let cx = x + w / 2.0 - total / 2.0;
parts.push_str(&format!(" <{n} position={{[{cx:.3}, 0, 0]}} />\n <Mesh3d transform={{Transform.fromXyz({cx:.3}, 0.002, {lz:.3}).withRotation(FLAT)}}>\n <Text3D size={{{fs:.3}}} depth={{0.001}} read={{false}}>{{{label:?}}}</Text3D>\n <StandardMaterial base_color=\"#2a2a2a\" />\n </Mesh3d>\n", label = o.label));
x += w + gap;
}
// framed to the set: wide enough for every piece, tall enough for the highest and the bar in front, from a little
// to the right and above, so a long piece shows its length
let d = (total * 1.45).max(highest * 4.2).max(bz * 3.0).max(0.35);
let (cx, cy, cz) = (d * 0.34, highest * 0.5 + d * 0.36, d * 0.88 + bz * 0.5);
format!(
"// raea make kit: the {kit} kit's lineup, every piece at its real size beside a {bar_label} bar (the kit's cover)\nimport {{ AbsoluteFill, Composition, registerRoot }} from \"raea\";\nimport {{ Text3D }} from \"raea/3d\";\nimport {{ StandardMaterial }} from \"raea/pbr\";\nimport {{ Cuboid, Mesh3d }} from \"raea/mesh\";\nimport {{ AmbientLight, DirectionalLight }} from \"raea/light\";\nimport {{ Transform }} from \"raea/transform\";\nimport {{ Camera3d }} from \"raea/camera\";\n{imports}\n// lying flat on the floor, reading toward the camera\nconst FLAT: [number, number, number, number] = [-0.7071068, 0, 0, 0.7071068];\n\nexport function Lineup() {{\n return (\n <AbsoluteFill style={{{{ background: \"#d6d2ca\" }}}}>\n <Camera3d transform={{Transform.fromXyz({cx:.3}, {cy:.3}, {cz:.3}).lookingAt([0, {ty:.3}, {tz:.3}])}} projection={{{{ Perspective: {{ fov: (30 * Math.PI) / 180 }} }}}} />\n <AmbientLight brightness={{300}} />\n <DirectionalLight transform={{Transform.fromXyz(2, 6, 4).lookingAt([0, 0, 0])}} illuminance={{9000}} shadow_maps_enabled />\n <Mesh3d transform={{Transform.fromXyz(0, -0.005, 0)}}>\n <Cuboid half_size={{[{g:.2}, 0.005, {g:.2}]}} />\n <StandardMaterial base_color=\"#d6d2ca\" perceptual_roughness={{0.95}} />\n </Mesh3d>\n <Mesh3d transform={{Transform.fromXyz({bx:.3}, 0.002, {bz:.3})}}>\n <Cuboid half_size={{[{bh:.3}, 0.002, {bt:.4}]}} />\n <StandardMaterial base_color=\"#202020\" />\n </Mesh3d>\n <Mesh3d transform={{Transform.fromXyz({bx:.3}, 0.002, {blz:.3}).withRotation(FLAT)}}>\n <Text3D size={{{fs:.3}}} depth={{0.001}} read={{false}}>{bar_label}</Text3D>\n <StandardMaterial base_color=\"#202020\" />\n </Mesh3d>\n{parts} </AbsoluteFill>\n );\n}}\n\nregisterRoot(() => <Composition id=\"lineup\" component={{Lineup}} width={{1920}} height={{1080}} fps={{30}} durationInFrames={{1}} />);\n",
ty = highest * 0.35,
tz = bz * 0.45,
// a floor past every edge of the frame (the review's views leave a ground slab out of their framing)
g = (total * 3.0).max(2.0),
bh = bar / 2.0,
bt = fs * 0.25,
bx = -total / 2.0 + bar / 2.0,
blz = bz + fs * 1.3,
)
}
/// The scale bar for a set this wide: the longest round length that fits under it, and its label.
pub fn scale_bar(width: f64) -> (f64, &'static str) {
[(1.0, "1 m"), (0.5, "50 cm"), (0.25, "25 cm"), (0.1, "10 cm"), (0.05, "5 cm")].into_iter().find(|(l, _)| *l <= width.max(0.05)).unwrap_or((0.05, "5 cm"))
}
/// Where a kit lands: `--to`, else the workspace's shared/components/KIT (every project imports it as
/// @shared/components/KIT), else the project's components/KIT.
pub fn kit_dir(dir: &Path, kit: &str, to: Option<&str>) -> PathBuf {
if let Some(t) = to {
return PathBuf::from(t);
}
if let Some(ws) = raea_core_facts::record::up(dir, ".raea/workspace") {
let shared = if !ws.join("shared").is_dir() && ws.join("components").is_dir() { ws.join("components") } else { ws.join("shared/components") };
return shared.join(kit);
}
let project = raea_core_facts::record::up(dir, ".raea/project").unwrap_or_else(|| dir.to_path_buf());
project.join("components").join(kit)
}
fn copy(a: &Path, b: &Path) -> Result<(), String> {
match std::fs::copy(a, b) {
Ok(_) => Ok(()),
Err(e) => Err(format!("{} -> {}: {e}", a.display(), b.display())),
}
}
/// The kit landed: each prepped object's model, LOD and sidecars, its component and thumb; the lineup and its cover
/// render; kit.json. Objects not prepped yet are named, not skipped silently.
pub fn land(dir: &Path, m: &Goal, name: Option<&str>, to: Option<&str>) -> Result<String, String> {
let kit = name.map(str::to_string).unwrap_or_else(|| dir.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or("kit".into()));
let dest = kit_dir(dir, &kit, to);
std::fs::create_dir_all(dest.join("thumbs")).map_err(|e| format!("{}: {e}", dest.display()))?;
let p = picks(dir);
let (mut items, mut missing) = (Vec::new(), Vec::new());
for o in &m.objects {
let from = dir.join("out/kit").join(&o.id);
let (full, lod) = (from.join(format!("{}.glb", o.id)), from.join(format!("{}_lod1.glb", o.id)));
if !full.is_file() || !lod.is_file() {
missing.push(o.id.clone());
continue;
}
for f in [&full, &lod] {
let name = f.file_name().unwrap();
copy(f, &dest.join(name))?;
let side = f.with_extension("glb.json");
if side.is_file() {
copy(&side, &dest.join(format!("{}.json", name.to_string_lossy())))?;
}
}
let why = p.get(&o.id).and_then(|v| v["why"].as_str()).unwrap_or("");
let n = component_name(&o.id);
std::fs::write(dest.join(format!("{n}.tsx")), component(o, why)).map_err(|e| e.to_string())?;
let (colour, _) = draw(&full, frame_size(o))?;
copy(&colour, &dest.join("thumbs").join(format!("{}.png", o.id)))?;
std::fs::create_dir_all(dir.join("out/kit/thumbs")).map_err(|e| e.to_string())?;
copy(&colour, &dir.join("out/kit/thumbs").join(format!("{}.png", o.id)))?;
items.push(json!({"id": o.id, "label": o.label, "component": format!("{n}.tsx"), "model": format!("{}.glb", o.id), "lod1": format!("{}_lod1.glb", o.id),
"thumb": format!("thumbs/{}.png", o.id), "h": tall(o), "pick": p.get(&o.id).cloned().unwrap_or(Value::Null)}));
}
if !missing.is_empty() {
return Err(format!("raea make kit: not prepped yet: {} (raea make prep --only {})", missing.join(", "), missing.join(",")));
}
let lineup_tsx = dest.join("lineup.tsx");
std::fs::write(&lineup_tsx, lineup(m, &kit)).map_err(|e| e.to_string())?;
let cover = dest.join("cover.png");
raea(&["render".into(), lineup_tsx.display().to_string(), "-o".into(), cover.display().to_string(), "--frame".into(), "0".into()], &[])?;
let doc = json!({"kit": kit, "style": m.style, "references": m.references, "items": items, "lineup": "lineup.tsx", "cover": "cover.png", "landed": dest.display().to_string(), "made": {"by": "raea make kit (docs/goal.feature MK13)"}});
let text = serde_json::to_string_pretty(&doc).unwrap_or_default();
std::fs::write(dest.join("kit.json"), &text).map_err(|e| e.to_string())?;
// the job's own record of it, what raea/goal's deliverables pack counts
std::fs::write(dir.join("out/kit/kit.json"), &text).map_err(|e| e.to_string())?;
copy(&cover, &dir.join("out/kit/lineup.png"))?;
Ok(format!("landed the {kit} kit ({} pieces) in {}: components, lineup.tsx, cover.png, thumbs/, kit.json", items.len(), dest.display()))
}
+215
View File
@@ -0,0 +1,215 @@
//! The asset tools for a scene, kit or shot goal (docs/goal.feature): `raea make blockout|refs|...` build to the goal's
//! frozen plan (`goal` on brief.ts, core/brief goal.rs), and `raea goal gates` gives the record and critic gates
//! raea/goal's packs read. The loop itself, every rule at its moments, is TypeScript: `raea goal check|tasks|seen|judge`
//! run sdk/goal/src/run.ts (engine/cli verbs.rs goal_ts).
//!
//! raea goal gates [DIR] [--goal NAME] --json (the record and critic gates of a scene, kit or shot goal)
//! raea make blockout|refs|sheet refs|gen|pick-sheet|pick|prep|kit|framing|lenschart ... (the steps, USAGE)
pub mod asked;
pub mod floor;
pub mod kit;
pub mod kitout;
pub mod sheet;
pub mod shots;
pub mod gates;
use std::path::{Path, PathBuf};
use raea_core_brief::goal::Goal;
use serde_json::Value;
pub const USAGE: &str = "raea make place FILE [--at S[,S...]] [--box WxH] (the clearest places in a shot for a text box that size, in a 1080-wide frame)
raea goal gates [DIR] [--goal NAME] --json (a scene, kit or shot goal's record and critic gates, as raea/goal's packs read them)
raea make blockout [DIR] [--no-review] (a scene's blockout stop: review/plan/floor-plan.png, a grey-box blockout from the entrance and its review sheets, comparison.png beside reference 0)
raea make refs [DIR] [--only ID,...] [--model M] [--dry] (a kit: every object's reference from the style images, in the plan's style, then review/refs.png; --dry quotes it)
raea make sheet refs [DIR] (review/refs.png again: the style images, then every reference)
raea make gen [DIR] [--only ID,...] [--tripo M] [--meshy M] [--dry] (each reference to both generators, Tripo H3.1 and Meshy on fal: out/kit/gen/ID/)
raea make pick-sheet [DIR] [--only ID,...] (review/picks.png: reference | Tripo | Tripo clay | Meshy | Meshy clay, fitted to size)
raea make pick ID tripo|meshy \"why\" [DIR] (the pick and its reason, out/kit/picks.json)
raea make prep [DIR] [--only ID,...] (each pick fitted to its real size, a quarter-triangle _lod1 beside it, .glb.json sidecars)
raea make kit [DIR] [--name KIT] [--to FOLDER] (the kit as a component set: shared/components/KIT, lineup.tsx, cover.png, thumbs, kit.json)
raea make framing [DIR] [--only NAME,...] [--out DIR] (a shot list: each shot's first, middle and last frame on framing.png, stamped)
raea make lenschart SHOT [DIR] [--out DIR] (a shot's first frame at 18, 24, 35, 50, 85 and 135 mm on lens-SHOT.png)";
/// The brief.ts the job is read from: DIR's own, else the nearest above it inside its raea project.
pub fn brief_path(dir: &Path) -> Option<PathBuf> {
let dir = dunce::canonicalize(dir).ok()?;
let project = raea_core_facts::record::up(&dir, ".raea/project");
for d in dir.ancestors() {
let p = d.join("brief.ts");
if p.is_file() {
return Some(p);
}
if project.as_deref() == Some(d) {
break;
}
}
None
}
/// Whether a brief.ts has a goal at all, read from its words: cheap enough for a hook at every turn's end, so the
/// module is only evaluated when it can matter.
pub fn has_goal(brief: &Path) -> bool {
std::fs::read_to_string(brief).is_ok_and(|t| t.contains("goal:") || t.contains("goal :"))
}
/// The goals of brief.ts, evaluated by `raea spec FILE --as brief` (the module runs; Rust checks it against core/brief).
pub fn read_goals(brief: &Path) -> Result<Vec<Goal>, String> {
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let out = std::process::Command::new(exe).arg("spec").arg(brief).args(["--as", "brief"]).env("RAEA_RECORD", "off").output().map_err(|e| e.to_string())?;
let text = String::from_utf8_lossy(&out.stdout);
let start = text.find('{').ok_or_else(|| format!("{} didn't read as a brief: {}", brief.display(), raea_app_judge::why_refused(&out)))?;
let v: Value = serde_json::from_str(&text[start..]).map_err(|e| format!("{}: {e}", brief.display()))?;
let b = v.get("brief").cloned().unwrap_or(v);
match b.get("goal") {
None | Some(Value::Null) => Ok(vec![]),
Some(g) => {
let gs: raea_core_brief::goal::Goals = serde_json::from_value(g.clone()).map_err(|e| format!("{}: goal: {e}", brief.display()))?;
Ok(gs.all().into_iter().cloned().collect())
}
}
}
/// The scene, kit or shot goal the asset tools build to: the one named, else the only one of those kinds.
pub fn read_goal(brief: &Path) -> Result<Option<Goal>, String> {
read_goal_named(brief, None)
}
pub fn read_goal_named(brief: &Path, name: Option<&str>) -> Result<Option<Goal>, String> {
use raea_core_brief::goal::{name_of, Kind};
let all = read_goals(brief)?;
if let Some(n) = name {
return all.into_iter().find(|g| name_of(g) == n).map(Some).ok_or_else(|| format!("{}: no goal is named {n}", brief.display()));
}
let mut built: Vec<Goal> = all.into_iter().filter(|g| matches!(g.kind, Kind::Scene | Kind::Kit | Kind::Shot)).collect();
match built.len() {
0 => Ok(None),
1 => Ok(built.pop()),
_ => Err(format!("{}: several scene, kit or shot goals ({}): name one with --goal", brief.display(), built.iter().map(name_of).collect::<Vec<_>>().join(", "))),
}
}
/// The judge's rounds beside the brief (review/judge.log.jsonl, as `raea judge` keeps them), the newest round's
/// verdict (judge.json, or judge.BY.json for an agent critic), and when the log was last written.
fn judged(dir: &Path) -> (Vec<Value>, Option<Value>, Option<std::time::SystemTime>) {
let log = dir.join("review").join("judge.log.jsonl");
let rounds: Vec<Value> = std::fs::read_to_string(&log).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect();
let verdict = rounds.last().and_then(|r| {
let d = gates::round_dir(dir, r)?;
let file = r["by"].as_str().filter(|b| *b != "clef").map_or_else(|| "judge.json".to_string(), |b| format!("judge.{b}.json"));
serde_json::from_str(&std::fs::read_to_string(d.join(file)).ok()?).ok()
});
let at = std::fs::metadata(&log).and_then(|m| m.modified()).ok();
(rounds, verdict, at)
}
/// The record and critic gates of the job whose brief is at `brief`, with its plan already read.
pub fn gates_of(brief: &Path, make: &Goal) -> Value {
let dir = brief.parent().unwrap_or(Path::new("."));
let project = raea_core_facts::record::up(dir, ".raea/project");
let record = project.as_deref().map(raea_core_facts::record::read).unwrap_or_default();
let (rounds, verdict, judged_at) = judged(dir);
let ledger = asked::Ledger::read();
let job = gates::Job { make, dir, project: project.as_deref(), record: &record, rounds: &rounds, verdict: verdict.as_ref(), judged_at, ledger: &ledger, score_gates: raea_app_judge::kind_gates(make.kind.name()) };
let mut s = gates::gates(&job);
s["brief"] = Value::String(brief.display().to_string());
s
}
/// The flags that take a value: what follows them isn't a positional argument.
const VALUED: [&str; 9] = ["--only", "--model", "--tripo", "--meshy", "--name", "--to", "--out", "--by", "--goal"];
fn flag<'a>(args: &'a [String], k: &str) -> Option<&'a str> {
args.iter().position(|a| a == k).and_then(|i| args.get(i + 1)).map(String::as_str)
}
/// The positional arguments after the verb (words), flags and their values left out.
pub fn positional(args: &[String], skip: usize) -> Vec<String> {
let mut out = Vec::new();
let mut i = skip;
while i < args.len() {
if VALUED.contains(&args[i].as_str()) {
i += 2;
continue;
}
if !args[i].starts_with("--") {
out.push(args[i].clone());
}
i += 1;
}
out
}
/// A flag's comma list (`--only a,b`), empty when it isn't given.
fn list(args: &[String], k: &str) -> Vec<String> {
let Some(v) = flag(args, k) else { return vec![] };
v.split(',').map(str::trim).filter(|s| !s.is_empty()).map(String::from).collect()
}
/// What `--only` names of a list (all of it when it names nothing), each item known by `name`.
pub(crate) fn only<'a, T>(all: &'a [T], only: &[String], name: impl Fn(&T) -> &str) -> Vec<&'a T> {
all.iter().filter(|t| only.is_empty() || only.iter().any(|n| n.as_str() == name(t))).collect()
}
/// The job's brief and plan from a folder.
fn job(dir: &Path, name: Option<&str>) -> Result<(PathBuf, Goal), String> {
let brief = brief_path(dir).ok_or_else(|| format!("no brief.ts at or above {} in its project", dir.display()))?;
let goal = read_goal_named(&brief, name)?.ok_or_else(|| format!("{} has no scene, kit or shot goal (`goal: scene({{...}})`, kit() or shot() from raea/brief)", brief.display()))?;
Ok((brief, goal))
}
/// The steps: each reads the plan from DIR's brief.ts and works beside it.
fn step(verb: &str, args: &[String]) -> Result<String, String> {
let skip = if verb == "sheet" { 3 } else { 2 };
let pos = positional(args, skip);
let (words, dir_at) = match verb {
"pick" => (3, 3),
"lenschart" => (1, 1),
_ => (0, 0),
};
if pos.len() < words {
return Err(USAGE.into());
}
let dir = pos.get(dir_at).map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."));
let (brief, m) = job(&dir, flag(args, "--goal"))?;
let here = brief.parent().unwrap_or(Path::new(".")).to_path_buf();
let only = list(args, "--only");
let dry = args.iter().any(|a| a == "--dry");
let out_or = |d: PathBuf| flag(args, "--out").map(PathBuf::from).unwrap_or(d);
match verb {
"blockout" => floor::draw_plan(&here, &m, !args.iter().any(|a| a == "--no-review")),
"refs" => kit::refs(&here, &m, &only, flag(args, "--model"), dry),
"sheet" => match args.get(2).map(String::as_str) {
Some("refs") => kit::sheet_refs(&here, &m),
Some("picks") => kitout::pick_sheet(&here, &m, &only),
Some("framing") => shots::framing(&here, &m, &only, &out_or(here.join("review"))),
_ => Err("raea make sheet refs|picks|framing [DIR]".into()),
},
"gen" => kit::generate(&here, &m, &only, flag(args, "--tripo").unwrap_or(kit::TRIPO), flag(args, "--meshy").unwrap_or(kit::MESHY), dry),
"pick-sheet" => kitout::pick_sheet(&here, &m, &only),
"pick" => kit::choose(&here, &m, &pos[0], &pos[1], &pos[2]),
"prep" => kit::prep(&here, &m, &only),
"kit" => kitout::land(&here, &m, flag(args, "--name"), flag(args, "--to")),
"framing" => shots::framing(&here, &m, &only, &out_or(here.join("review"))),
"lenschart" => shots::lenschart(&here, &m, &pos[0], &out_or(here.join("review"))),
_ => Err(USAGE.into()),
}
}
pub fn cli(args: &[String]) -> Result<String, String> {
match args.get(1).map(String::as_str) {
Some("gates") => {
let dir = positional(args, 2).first().map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."));
let (brief, make) = job(&dir, flag(args, "--goal"))?;
Ok(serde_json::to_string_pretty(&gates_of(&brief, &make)).unwrap_or_default())
}
Some(v @ ("blockout" | "refs" | "sheet" | "gen" | "pick-sheet" | "pick" | "prep" | "kit" | "framing" | "lenschart")) => step(v, args),
_ => Err(USAGE.into()),
}
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tests_steps;
+96
View File
@@ -0,0 +1,96 @@
//! The contact sheets a gate looks at (docs/goal.feature MK10, MK11, MK15): pictures in rows, each labelled under it,
//! a title over them, on one PNG a person, `raea ask` and the critic read at once. Labels are drawn by resvg in the
//! system's own fonts; an SVG drawn whole (the floor plan, MK18) goes through `svg_png`.
use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock};
use image::{Rgba, RgbaImage, imageops};
use resvg::{tiny_skia, usvg};
/// One picture on a sheet and what it is.
pub struct Tile {
pub img: PathBuf,
pub label: String,
}
const LABEL_H: u32 = 30;
const TITLE_H: u32 = 44;
const GAP: u32 = 6;
fn options() -> usvg::Options<'static> {
static DB: OnceLock<Arc<usvg::fontdb::Database>> = OnceLock::new();
let db = DB.get_or_init(|| {
let mut db = usvg::fontdb::Database::new();
db.load_system_fonts();
Arc::new(db)
});
usvg::Options { fontdb: db.clone(), font_family: "Helvetica".into(), ..usvg::Options::default() }
}
/// SVG text escaped.
pub fn esc(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
c => out.push(c),
}
}
out
}
/// An SVG document drawn at its own size.
pub fn svg_png(svg: &str) -> Result<RgbaImage, String> {
let tree = usvg::Tree::from_str(svg, &options()).map_err(|e| format!("svg: {e}"))?;
let size = tree.size().to_int_size();
let mut pix = tiny_skia::Pixmap::new(size.width(), size.height()).ok_or("svg: empty size")?;
resvg::render(&tree, tiny_skia::Transform::default(), &mut pix.as_mut());
// tiny-skia keeps premultiplied alpha; image wants it straight
let mut img = RgbaImage::new(size.width(), size.height());
for (p, c) in img.pixels_mut().zip(pix.pixels()) {
let d = c.demultiply();
*p = Rgba([d.red(), d.green(), d.blue(), d.alpha()]);
}
Ok(img)
}
/// Rows of tiles, each `tile_w` wide (its height from the first picture's shape; any other shape fitted inside it), a label under each and the title
/// over them all, written to `out`. A tile whose picture won't open is drawn grey, its label saying so.
pub fn sheet(title: &str, rows: &[Vec<Tile>], tile_w: u32, out: &Path) -> Result<(), String> {
let first = rows.iter().flatten().find_map(|t| image::open(&t.img).ok()).ok_or_else(|| format!("{title}: no picture to put on the sheet"))?;
let th = ((tile_w as f64) * first.height() as f64 / first.width().max(1) as f64).round().max(1.0) as u32;
let cols = rows.iter().map(Vec::len).max().unwrap_or(1).max(1) as u32;
let (w, h) = (GAP + cols * (tile_w + GAP), TITLE_H + rows.len() as u32 * (th + LABEL_H + GAP));
let mut img = RgbaImage::from_pixel(w, h, Rgba([18, 18, 20, 255]));
let mut text = format!("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{w}\" height=\"{h}\"><text x=\"{GAP}\" y=\"30\" font-size=\"22\" font-weight=\"bold\" fill=\"#ffffff\">{}</text>", esc(title));
for (r, row) in rows.iter().enumerate() {
for (c, t) in row.iter().enumerate() {
let (x, y) = (GAP + c as u32 * (tile_w + GAP), TITLE_H + r as u32 * (th + LABEL_H + GAP));
let label = match image::open(&t.img) {
Ok(p) => {
// fitted inside the tile, its own shape kept, centred
let k = (tile_w as f64 / p.width().max(1) as f64).min(th as f64 / p.height().max(1) as f64);
let (pw, ph) = (((p.width() as f64 * k).round() as u32).max(1), ((p.height() as f64 * k).round() as u32).max(1));
let small = imageops::resize(&p.to_rgba8(), pw, ph, imageops::FilterType::Triangle);
imageops::overlay(&mut img, &small, (x + (tile_w - pw.min(tile_w)) / 2) as i64, (y + (th - ph.min(th)) / 2) as i64);
t.label.clone()
}
Err(_) => {
imageops::overlay(&mut img, &RgbaImage::from_pixel(tile_w, th, Rgba([70, 70, 70, 255])), x as i64, y as i64);
format!("{} (missing)", t.label)
}
};
text.push_str(&format!("<text x=\"{}\" y=\"{}\" font-size=\"17\" fill=\"#e8e8e8\">{}</text>", x + 4, y + th + 21, esc(&label)));
}
}
text.push_str("</svg>");
imageops::overlay(&mut img, &svg_png(&text)?, 0, 0);
if let Some(d) = out.parent() {
std::fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?;
}
img.save(out).map_err(|e| format!("{}: {e}", out.display()))
}
+108
View File
@@ -0,0 +1,108 @@
//! Blocking a shot list (docs/goal.feature MK15): `raea make framing` renders each shot's first, middle and last
//! frame and puts them on one sheet, a row a shot, each stamped with its name and time, so the person, `raea ask`
//! (make.framing.*) and the critic (`raea judge --kind shot`) see every shot's start and end at once; `raea make
//! lenschart SHOT` renders a shot's first frame at 18, 24, 35, 50, 85 and 135 mm (RAEA_LENS, core/review) to choose its
//! lens before it's moved.
use std::path::{Path, PathBuf};
use raea_core_brief::goal::{Goal, Shot};
use crate::sheet::{Tile, sheet};
/// The focal lengths a lens chart shows.
pub const LENSES: [u32; 6] = [18, 24, 35, 50, 85, 135];
/// raea itself, run on `args` with `env`: its output, or what it said when it failed.
pub fn raea(args: &[String], env: &[(&str, String)]) -> Result<String, String> {
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let mut c = std::process::Command::new(exe);
c.args(args);
for (k, v) in env {
c.env(k, v);
}
// stderr passes through as it comes (a generation's progress, a render's frames), so whoever watches sees it
// working, and is kept for the error
let mut child = c.stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()).spawn().map_err(|e| e.to_string())?;
let err = child.stderr.take().map(|e| {
std::thread::spawn(move || {
use std::io::BufRead;
let mut kept = Vec::new();
for line in std::io::BufReader::new(e).lines().map_while(Result::ok) {
eprintln!(" {line}");
kept.push(line);
}
kept
})
});
let out = child.wait_with_output().map_err(|e| e.to_string())?;
let err = err.and_then(|t| t.join().ok()).unwrap_or_default();
let text = String::from_utf8_lossy(&out.stdout).to_string();
if out.status.success() {
Ok(text)
} else {
Err(format!("raea {}: {}", args.first().map(String::as_str).unwrap_or(""), err.iter().rev().find(|l| !l.trim().is_empty()).map_or(text.trim(), String::as_str)))
}
}
/// A shot's frames: its first, middle and last, from its seconds at its frame rate.
pub fn frames_of(s: &Shot) -> Vec<i64> {
let n = ((s.seconds.unwrap_or(0.0) * s.fps.unwrap_or(30.0)).round() as i64).max(1);
if s.still == Some(true) || n == 1 {
return vec![0];
}
let mut v = vec![0, (n - 1) / 2, n - 1];
v.dedup();
v
}
fn composition(dir: &Path, s: &Shot) -> Result<PathBuf, String> {
let c = s.composition.as_deref().ok_or_else(|| format!("shot `{}` has no composition (the .tsx that renders it)", s.name))?;
Ok(dir.join(c))
}
/// The framing sheet of the plan's shots (or those named in `only`), written to `out` (OUT/framing.png).
pub fn framing(dir: &Path, m: &Goal, only: &[String], out: &Path) -> Result<String, String> {
let shots: Vec<&Shot> = crate::only(&m.shots, only, |s| s.name.as_str());
if shots.is_empty() {
return Err("raea make framing: no shots in the plan (or none named)".into());
}
let work = out.join("framing-frames");
let mut rows = Vec::new();
for s in &shots {
let tsx = composition(dir, s)?;
let fr = frames_of(s);
let to = work.join(&s.name);
let _ = std::fs::remove_dir_all(&to);
std::fs::create_dir_all(&to).map_err(|e| format!("{}: {e}", to.display()))?;
let at = fr.iter().map(|f| f.to_string()).collect::<Vec<_>>().join(",");
raea(&["render".into(), tsx.display().to_string(), "-o".into(), to.display().to_string(), "--at".into(), at], &[])?;
let fps = s.fps.unwrap_or(30.0);
rows.push(fr.iter().enumerate().map(|(i, f)| Tile { img: to.join(format!("frame-{i:05}.png")), label: format!("{} t={:.1}s (frame {f})", s.name, *f as f64 / fps) }).collect());
}
let file = out.join("framing.png");
sheet("Framing: each shot's first, middle and last frame", &rows, 480, &file)?;
Ok(format!("wrote {} ({} shot{}); ask it: raea ask {} --set make (the framing questions apply); judge it: raea judge {} --kind shot", file.display(), shots.len(), if shots.len() == 1 { "" } else { "s" }, file.display(), out.display()))
}
/// One shot's first frame at every lens of the chart, on one sheet (OUT/lens-SHOT.png).
pub fn lenschart(dir: &Path, m: &Goal, name: &str, out: &Path) -> Result<String, String> {
let s = m.shots.iter().find(|s| s.name == name).ok_or_else(|| format!("raea make lenschart: no shot `{name}` in the plan"))?;
let tsx = composition(dir, s)?;
let work = out.join("lens-frames").join(name);
std::fs::create_dir_all(&work).map_err(|e| format!("{}: {e}", work.display()))?;
let mut tiles = Vec::new();
for mm in LENSES {
let png = work.join(format!("{mm}mm.png"));
raea(&["render".into(), tsx.display().to_string(), "-o".into(), png.display().to_string(), "--frame".into(), "0".into()], &[("RAEA_LENS", mm.to_string())])?;
tiles.push(Tile { img: png, label: format!("{mm} mm ({:.0}° vertical)", raea_core_review::fov_of_lens(mm as f64)) });
}
let rows: Vec<Vec<Tile>> = {
let mut it = tiles.into_iter();
vec![it.by_ref().take(3).collect(), it.collect()]
};
let file = out.join(format!("lens-{name}.png"));
sheet(&format!("Lens chart: {name}, its first frame"), &rows, 480, &file)?;
Ok(format!("wrote {}: pick the lens, then set the shot's `lens` (raea/camera lens(mm) for its fov)", file.display()))
}
+196
View File
@@ -0,0 +1,196 @@
use std::path::PathBuf;
use std::time::{Duration, SystemTime};
use raea_core_brief::{goal::Goal, read};
use raea_core_facts::record::Entry;
use serde_json::{Value, json};
use crate::asked::Ledger;
use crate::gates::{Job, gates, stalled};
fn dir(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("raea-make-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
fn put(d: &PathBuf, rel: &str, text: &str) {
let p = d.join(rel);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, text).unwrap();
}
fn kit() -> Goal {
read("make", r#"{"kind": "kit", "style": "1970s desk, maker Aurora", "objects": [{"id": "phone", "label": "Phone", "h": 0.12, "prompt": "a rotary phone"}]}"#).unwrap()
}
fn delivered(d: &PathBuf) {
for f in ["out/kit/phone/phone.glb", "out/kit/phone/phone_lod1.glb", "out/kit/thumbs/phone.png", "out/kit/lineup.png", "out/kit/kit.json", "review/refs.png"] {
put(d, f, "x");
}
put(d, "NOTES.md", "# Notes\n\n## What the skill got wrong\n- nothing yet\n");
}
fn round(pass: bool, mean: f64, defects: Value) -> Value {
json!({"dir": "review/r1", "kind": "kit", "pass": pass, "mean": mean, "defects": defects})
}
fn run(make: &Goal, d: &PathBuf, record: &[Entry], rounds: &[Value], judged_at: Option<SystemTime>) -> Value {
run_with(make, d, record, rounds, judged_at, &Ledger::default())
}
fn run_with(make: &Goal, d: &PathBuf, record: &[Entry], rounds: &[Value], judged_at: Option<SystemTime>, ledger: &Ledger) -> Value {
gates(&Job { make, dir: d, project: None, record, rounds, verdict: None, judged_at, ledger, score_gates: false })
}
fn later() -> Option<SystemTime> {
Some(SystemTime::now() + Duration::from_secs(5))
}
#[test]
fn delivered_and_judged_after_is_done() {
let d = dir("done");
delivered(&d);
let s = run(&kit(), &d, &[], &[round(true, 7.5, json!([]))], later());
assert_eq!(s["clear"], true, "{s:#}");
assert_eq!(s["short"], json!([]));
}
#[test]
fn a_round_older_than_the_newest_deliverable_is_stale() {
let d = dir("stale");
delivered(&d);
let s = run(&kit(), &d, &[], &[round(true, 7.5, json!([]))], Some(SystemTime::UNIX_EPOCH));
assert_eq!(s["clear"], false);
assert!(s["gates"].to_string().contains("came after the last round"), "{s:#}");
}
#[test]
fn a_blocking_defect_must_be_fixed_or_answered_in_the_notes() {
let d = dir("defect");
delivered(&d);
let defects = json!([{"defect": "floating", "present": true, "level": "blocking"}]);
let s = run(&kit(), &d, &[], &[round(false, 6.0, defects.clone())], later());
assert_eq!(s["clear"], false);
assert!(s["gates"].to_string().contains("floating"));
put(&d, "NOTES.md", "## What the skill got wrong\n- floating: the handset rests in its cradle; the judge read its shadow as a gap\n");
let s = run(&kit(), &d, &[], &[round(false, 6.0, defects.clone())], later());
assert_eq!(s["clear"], true, "{s:#}");
// once the judge is calibrated for kits, its score gates too: two passes in a row (MK6)
let (rounds, ledger) = ([round(false, 6.0, defects)], Ledger::default());
let s = gates(&Job { make: &kit(), dir: &d, project: None, record: &[], rounds: &rounds, verdict: None, judged_at: later(), ledger: &ledger, score_gates: true });
assert_eq!(s["clear"], false, "{s:#}");
assert!(s["gates"].to_string().contains("two needed"), "{s:#}");
}
#[test]
fn at_the_cap_it_is_delivered_short() {
let d = dir("cap");
// eight rounds, the last still blocked by a defect no one answered
let blocked = json!([{"defect": "floating", "present": true, "level": "blocking"}]);
let rounds: Vec<Value> = (0..8).map(|i| round(false, 5.0 + i as f64 * 0.5, blocked.clone())).collect();
let s = run(&kit(), &d, &[], &rounds, later());
assert_eq!(s["clear"], false, "{s:#}");
assert!(s["short"].to_string().contains("capped"), "{s:#}");
}
#[test]
fn three_rounds_without_beating_the_best_is_a_stall() {
let r = |m: f64| json!({"mean": m});
assert!(stalled(&[r(5.0), r(6.5), r(6.0), r(6.4), r(6.5)]));
assert!(!stalled(&[r(5.0), r(6.0), r(6.2), r(6.4), r(6.6)]));
assert!(!stalled(&[r(5.0), r(5.0), r(5.0)]), "too few rounds to call it");
}
#[test]
fn a_composition_needs_a_clean_check_newer_than_it() {
let d = dir("checks");
delivered(&d);
put(&d, "scene.tsx", "x");
let mut make = kit();
make.compositions = vec!["scene.tsx".into()];
let rounds = [round(true, 7.5, json!([]))];
let s = run(&make, &d, &[], &rounds, later());
assert!(s["gates"].to_string().contains("never rendered"), "{s:#}");
let entry = |at: u64, level: &str| -> Entry {
serde_json::from_value(json!({"id": "20261123-x", "at": at, "by": "raea render", "of": "scene.tsx",
"findings": [{"check": "float", "level": level, "says": "the mug floats 2 cm", "by": "raea scene lint"}]})).unwrap()
};
let future = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() + 60;
let s = run(&make, &d, &[entry(future, "error")], &rounds, later());
assert!(s["gates"].to_string().contains("the mug floats"), "{s:#}");
let s = run(&make, &d, &[entry(future, "warn")], &rounds, later());
assert_eq!(s["clear"], true, "a warn doesn't block: {s:#}");
let s = run(&make, &d, &[entry(1, "warn")], &rounds, later());
assert!(s["gates"].to_string().contains("changed since"), "{s:#}");
}
// MK24: a part a render showed closer than planned holds the job until it's replanned or answered in the notes
#[test]
fn a_part_seen_closer_than_planned_holds_the_job() {
let d = dir("lod");
delivered(&d);
put(&d, "scene.tsx", "x");
let mut make = kit();
make.compositions = vec!["scene.tsx".into()];
let future = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() + 60;
let entry: Entry = serde_json::from_value(json!({"id": "r1", "at": future, "by": "raea render", "of": "scene.tsx", "findings": [{"check": "lod-closer", "level": "warn", "about": [{"name": "kiosk"}], "says": "'kiosk' is planned at LOD 3", "by": "raea render"}]})).unwrap();
let s = run(&make, &d, &[entry.clone()], &[round(true, 7.5, json!([]))], later());
assert!(s["clear"] == false && s["gates"].to_string().contains("seen closer than planned at r1: kiosk"), "{s:#}");
put(&d, "NOTES.md", "- lod kiosk: one frame at the cut, left as a box\n## What the skill got wrong\n- nothing\n");
assert_eq!(run(&make, &d, &[entry], &[round(true, 7.5, json!([]))], later())["clear"], true);
}
#[test]
fn a_round_judged_on_another_kinds_rubric_does_not_count() {
// docs/goal.feature MK5: a kit is judged on the kit's rubric
let d = dir("rubric");
delivered(&d);
let old = json!({"dir": "review/r1", "pass": true, "mean": 8.0, "defects": []});
let s = run(&kit(), &d, &[], &[old], later());
assert_eq!(s["clear"], false);
assert!(s["gates"].to_string().contains("--kind kit"), "{s:#}");
}
#[test]
fn a_calibrated_ask_question_gates_and_an_uncalibrated_one_advises() {
// docs/goal.feature MK4
let d = dir("ask");
delivered(&d);
put(&d, "review/r1/clay.png", "clay sheet bytes");
put(&d, "review/r1/colour.png", "colour sheet bytes");
let rounds = [round(true, 7.5, json!([]))];
let floating = raea_core_ask::library::find("make.clay.floating", None).unwrap();
let mut ledger = Ledger::default();
// nothing calibrated: every question is advice, and the job is done
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
assert_eq!(s["clear"], true, "{s:#}");
assert!(s["gates"].to_string().contains("advice only"), "{s:#}");
// floating calibrated on the person's labels: it must be asked of this exact clay sheet
ledger.calibrations.insert(floating.version(), serde_json::from_value(json!({"auc": 0.9, "n": 40, "positives": 16, "threshold": 0.4, "date": "2026-11-23", "by": "you"})).unwrap());
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
assert_eq!(s["clear"], false);
let gates = s["gates"].to_string();
assert!(gates.contains("not asked of this clay sheet") && gates.contains("--std make.clay.floating"), "{gates}");
// asked, and it flagged: open until fixed or answered by its id in NOTES.md
let ident = raea_core_ask::ident::ident(&d.join("review/r1/clay.png")).unwrap();
ledger.idents.insert("c-1".into(), ident);
ledger.answers.push(json!({"id": "a-1", "at": "100", "call": "c-1", "question": "make.clay.floating", "flagged": true, "problem": 0.8}));
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
assert_eq!(s["clear"], false);
assert!(s["gates"].to_string().contains("make.clay.floating flagged (p 0.80)"), "{s:#}");
put(&d, "NOTES.md", "## What the skill got wrong\n- make.clay.floating: the handset's shadow, not a gap; checked on the low tile\n");
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
assert_eq!(s["clear"], true, "{s:#}");
// the sheet rendered again: the old answer was about other bytes, so it's asked again
put(&d, "review/r1/clay.png", "a new clay sheet");
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
assert!(s["gates"].to_string().contains("not asked of this clay sheet"), "{s:#}");
// an uncalibrated question that flags is said as advice, holding nothing
let ident = raea_core_ask::ident::ident(&d.join("review/r1/colour.png")).unwrap();
ledger.idents.insert("c-2".into(), ident);
ledger.answers.push(json!({"id": "a-2", "at": "101", "call": "c-2", "question": "make.colour.plastic", "flagged": true, "problem": 0.7}));
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
assert!(s["advice"].to_string().contains("make.colour.plastic says yes"), "{s:#}");
}
+206
View File
@@ -0,0 +1,206 @@
//! The steps' own work, without a render or a paid call: sheets, prompts, flows, picks, components, the floor plan.
use std::path::PathBuf;
use image::{Rgba, RgbaImage};
use raea_core_brief::{make::Make, read};
use crate::sheet::{Tile, sheet};
fn dir(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("raea-make-steps-{name}-{}", std::process::id()));
std::fs::remove_dir_all(&d).ok();
std::fs::create_dir_all(&d).expect("a scratch folder");
d
}
fn png(p: &PathBuf, w: u32, h: u32, c: [u8; 3]) {
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
RgbaImage::from_pixel(w, h, Rgba([c[0], c[1], c[2], 255])).save(p).unwrap();
}
fn kit() -> Make {
read("make", r#"{"kind": "kit", "references": ["media/style.png"], "style": "1970s flight desk, cream enamel, maker Aurora Instruments.", "objects": [
{"id": "rotary_phone", "label": "Rotary phone", "h": 0.12, "prompt": "a rotary desk phone, worn bakelite", "hero": true},
{"id": "clock", "label": "Wall clock", "dims": [0.3, 0.05, 0.3]}]}"#)
.unwrap()
}
// MK10, MK11, MK15: a sheet is its tiles in rows, labelled, any shape fitted without stretching, a missing one grey
#[test]
fn a_sheet_holds_its_tiles_in_rows_with_labels() {
let d = dir("sheet");
let (a, b, wide) = (d.join("a.png"), d.join("b.png"), d.join("wide.png"));
png(&a, 200, 100, [200, 30, 30]);
png(&b, 200, 100, [30, 200, 30]);
png(&wide, 400, 100, [30, 30, 200]);
let out = d.join("review/sheet.png");
let rows = vec![
vec![Tile { img: a.clone(), label: "red <a&b>".into() }, Tile { img: b, label: "green".into() }],
vec![Tile { img: wide, label: "wide".into() }, Tile { img: d.join("gone.png"), label: "gone".into() }],
];
sheet("Test sheet", &rows, 300, &out).unwrap();
let img = image::open(&out).unwrap().to_rgba8();
// two columns of 300 and three gaps of 6; the tile is 150 tall (from the first's 2:1), title 44, label 30, gap 6
assert_eq!((img.width(), img.height()), (618, 44 + 2 * (150 + 30 + 6)));
// the first tile is red in its middle; the wide one is letterboxed (fitted 300x75, centred), not stretched
assert_eq!(img.get_pixel(6 + 150, 44 + 75).0[..3], [200, 30, 30]);
let row2 = 44 + 150 + 30 + 6;
assert_eq!(img.get_pixel(6 + 150, row2 + 75).0[..3], [30, 30, 200]);
assert_ne!(img.get_pixel(6 + 150, row2 + 10).0[..3], [30, 30, 200]);
// the missing one is grey
assert_eq!(img.get_pixel(6 + 300 + 6 + 150, row2 + 75).0[..3], [70, 70, 70]);
// a label was drawn under the first tile (light pixels on the dark ground)
let lit = (0..300).flat_map(|x| (0..30).map(move |y| (x, y))).filter(|&(x, y)| img.get_pixel(6 + x, 44 + 150 + y).0[0] > 150).count();
assert!(lit > 40, "no label drawn ({lit} lit pixels)");
assert!(sheet("empty", &[vec![Tile { img: d.join("none.png"), label: "x".into() }]], 100, &d.join("e.png")).is_err());
}
// MK10: a reference prompt is the plan's style, the object's words and the scan template, never a brand
#[test]
fn a_reference_prompt_is_style_object_and_scan() {
let m = kit();
let p = crate::kit::ref_prompt(&m, &m.objects[0]);
assert!(p.starts_with("1970s flight desk, cream enamel, maker Aurora Instruments. a rotary desk phone, worn bakelite. One object only"), "{p}");
assert!(p.contains("no real brands"));
// an object with no prompt is described by its label
assert!(crate::kit::ref_prompt(&m, &m.objects[1]).contains(". Wall clock. "));
assert_eq!(crate::kit::size_args(&m.objects[0]), ["--h", "0.12"]);
assert_eq!(crate::kit::size_args(&m.objects[1]), ["--dims", "0.3,0.05,0.3"]);
}
// MK11: one reference to both generators, the hero at 150k faces; the single-shot gen's file read from its JSON
#[test]
fn both_generators_get_each_reference() {
let m = kit();
let f = crate::kit::gen_flow(&m, &m.objects[0], std::path::Path::new("/r/rotary_phone.png"), crate::kit::TRIPO, crate::kit::MESHY);
assert_eq!(f["out"], serde_json::json!(["tripo", "meshy"]));
assert_eq!(f["steps"]["tripo"]["model"], "tripo:H3.1");
assert_eq!(f["steps"]["tripo"]["in"]["x_face_limit"], 150000);
assert_eq!(f["steps"]["meshy"]["model"], "fal:meshy/v7.1/image-to-3d");
assert_eq!(f["steps"]["meshy"]["in"]["image"], "@ref");
let small = crate::kit::gen_flow(&m, &m.objects[1], std::path::Path::new("/r/clock.png"), crate::kit::TRIPO, crate::kit::MESHY);
assert_eq!(small["steps"]["tripo"]["in"]["x_face_limit"], 60000);
assert_eq!(crate::kit::gen_file(r#"{"out": {"out": "/g/out.png"}, "cents": 4}"#), Some(PathBuf::from("/g/out.png")));
assert_eq!(crate::kit::gen_file(r#"{"out": {"out": ["/g/a.png", "/g/b.png"]}}"#), Some(PathBuf::from("/g/a.png")));
assert_eq!(crate::kit::gen_file("not json"), None);
}
// MK11: a pick names a model that exists and says why; it's kept by object
#[test]
fn a_pick_needs_its_model_and_a_reason() {
let d = dir("pick");
let m = kit();
assert!(crate::kit::choose(&d, &m, "rotary_phone", "tripo", "sharper").unwrap_err().contains("raea make gen --only rotary_phone"));
std::fs::create_dir_all(crate::kit::gen_dir(&d, "rotary_phone")).unwrap();
std::fs::write(crate::kit::gen_dir(&d, "rotary_phone").join("meshy.glb"), "x").unwrap();
assert!(crate::kit::choose(&d, &m, "rotary_phone", "meshy", " ").unwrap_err().contains("say why"));
assert!(crate::kit::choose(&d, &m, "lamp", "meshy", "x").unwrap_err().contains("no object `lamp`"));
crate::kit::choose(&d, &m, "rotary_phone", "meshy", "Tripo fused the handset to the cradle").unwrap();
assert_eq!(crate::kit::picks(&d)["rotary_phone"]["generator"], "meshy");
// prep names what isn't picked yet rather than skipping it
let said = crate::kit::prep(&d, &m, &["clock".to_string()]).unwrap();
assert!(said.contains("clock: no pick yet"), "{said}");
}
// MK13: each object a component importing its own model and LOD beside it; the lineup imports them all with a 1 m bar
#[test]
fn the_kit_lands_as_components_and_a_lineup() {
let m = kit();
assert_eq!(crate::kitout::component_name("rotary_phone"), "RotaryPhone");
let c = crate::kitout::component(&m.objects[0], "sharper numerals");
assert!(c.starts_with("// raea make component add: Rotary phone, 0.12 m"), "{c}");
assert!(c.contains("import full from \"./rotary_phone.glb\";") && c.contains("import far from \"./rotary_phone_lod1.glb\";"));
assert!(c.contains("export default function RotaryPhone("));
let l = crate::kitout::lineup(&m, "desk");
assert!(l.contains("import RotaryPhone from \"./RotaryPhone\";") && l.contains("import Clock from \"./Clock\";"));
assert!(l.contains("</Text3D>") && l.contains("registerRoot("));
// the bar is the longest round length the set covers
assert_eq!(crate::kitout::scale_bar(0.52), (0.5, "50 cm"));
assert_eq!(crate::kitout::scale_bar(1.7), (1.0, "1 m"));
assert_eq!(crate::kitout::scale_bar(0.02), (0.05, "5 cm"));
// the viewer frames a model by its height
let v = crate::kitout::viewer(std::path::Path::new("/k/tripo.fit.glb"), 0.12);
assert!(v.contains("import model from \"./tripo.fit.glb\";") && v.contains("<Model src={model} />"));
// where it lands: the workspace's shared/components, else the project's components
let d = dir("land");
let job = d.join("projects/p/kit");
std::fs::create_dir_all(&job).unwrap();
std::fs::create_dir_all(d.join("projects/p/.raea")).unwrap();
std::fs::write(d.join("projects/p/.raea/project"), "{}").unwrap();
let real = dunce::canonicalize(&d).unwrap();
assert_eq!(crate::kitout::kit_dir(&job, "desk", None), real.join("projects/p/components/desk"));
std::fs::create_dir_all(d.join(".raea")).unwrap();
std::fs::write(d.join(".raea/workspace"), "{}").unwrap();
std::fs::create_dir_all(d.join("shared")).unwrap();
assert_eq!(crate::kitout::kit_dir(&job, "desk", None), real.join("shared/components/desk"));
assert_eq!(crate::kitout::kit_dir(&job, "desk", Some("/x")), PathBuf::from("/x"));
}
// MK15: a shot's frames are its first, middle and last (a still: its first); the lens chart's angles
#[test]
fn a_shot_frames_its_start_middle_and_end() {
let m: Make = read("make", r#"{"kind": "shot", "shots": [{"name": "push", "seconds": 4, "composition": "push.tsx"}, {"name": "hold", "still": true}, {"name": "fast", "seconds": 2, "fps": 24}]}"#).unwrap();
assert_eq!(crate::shots::frames_of(&m.shots[0]), vec![0, 59, 119]);
assert_eq!(crate::shots::frames_of(&m.shots[1]), vec![0]);
assert_eq!(crate::shots::frames_of(&m.shots[2]), vec![0, 23, 47]);
assert!((raea_core_review::fov_of_lens(50.0) - 26.99).abs() < 0.01);
// a shot with no composition can't be framed, and says what's needed
let d = dir("framing");
assert!(crate::shots::framing(&d, &m, &["hold".to_string()], &d).unwrap_err().contains("no composition"));
assert!(raea_core_brief::make::doctor(&m).iter().any(|w| w.contains("shot `hold` has no composition")));
}
// MK18: the floor plan draws every placed footprint (invented ones dashed); the blockout boxes them from the entrance
#[test]
fn the_plan_draws_a_floor_plan_and_a_blockout() {
let m: Make = read("make", r#"{"kind": "scene", "references": ["media/ref.png"], "objects": [
{"id": "desk", "label": "Desk", "dims": [1.6, 0.8, 0.75], "at": [2, 0, 3], "rot": 90, "source": "reference", "hero": true},
{"id": "plant", "label": "Plant", "h": 1.2, "at": [0.5, 0, 4], "source": "invented", "lod": 3},
{"id": "pen", "label": "Pen", "max": 0.14}]}"#)
.unwrap();
let (placed, b) = crate::floor::extent(&m);
assert_eq!(placed.len(), 2);
assert!(b[0] < 0.0 && b[3] > 4.5, "{b:?}");
let svg = crate::floor::floor_svg(&m).unwrap();
assert_eq!(svg.matches("stroke-dasharray").count(), 1);
assert!(svg.contains(">Desk<") && svg.contains(">Plant<") && !svg.contains(">Pen<"));
// the entrance runs along the front edge (the plan's nearest z), where the blockout's camera stands
assert!(svg.contains("entrance: the camera looks in from here"));
let img = crate::sheet::svg_png(&svg).unwrap();
assert!(img.width() > 400 && img.height() > 400);
let t = crate::floor::blockout_tsx(&m);
assert_eq!(t.matches("<Cuboid").count(), 3, "the floor and two boxes");
assert!(t.contains("half_size={[0.800, 0.375, 0.400]}"), "{t}");
assert!(t.contains("<Mesh3d name=\"plant\" lod={3} transform=") && svg.contains("1.20 m, LOD 3<"), "MK22, each box named with its planned detail: {t}");
let none: Make = read("make", r#"{"kind": "scene", "objects": [{"id": "pen", "label": "Pen"}]}"#).unwrap();
assert!(crate::floor::floor_svg(&none).unwrap_err().contains("no object has an `at`"));
}
// the CLI's positional words skip flags and their values
#[test]
fn positional_words_skip_flags() {
let a: Vec<String> = ["make", "pick", "phone", "--only", "a,b", "tripo", "--dry", "why not", "proj"].iter().map(|s| s.to_string()).collect();
assert_eq!(crate::positional(&a, 2), ["phone", "tripo", "why not", "proj"]);
}
#[test]
fn a_quote_reads_as_one_line() {
let out = "raea: planning\n{\"steps\":[{\"op\":\"media.load\",\"runs_on\":\"load\",\"cents\":0},{\"op\":\"image\",\"runs_on\":\"made:nano_banana_2\",\"cents\":6}],\"cents\":6,\"cap_cents\":100}";
assert_eq!(crate::kit::quote(out), "made:nano_banana_2 (about 6¢)");
assert_eq!(crate::kit::quote("not json at all"), "not json at all");
}
#[test]
fn a_boxy_model_is_fitted_by_its_height_and_turned_to_lie_front_to_back() {
use raea_core_brief::make::Object;
let stapler: Object = serde_json::from_value(serde_json::json!({"id": "stapler", "label": "Stapler", "dims": [0.05, 0.17, 0.07]})).unwrap();
// long across (x) where the plan's is front to back (z): a quarter turn
assert_eq!(crate::kit::fit_args(&stapler, Some([1.9, 0.72, 0.58])), ["--dims", "0.05,0.17,0.07", "--h", "0.07", "--turn", "90"]);
// already front to back, or about square: no turn
assert_eq!(crate::kit::fit_args(&stapler, Some([0.27, 0.12, 0.84])), ["--dims", "0.05,0.17,0.07", "--h", "0.07"]);
assert_eq!(crate::kit::fit_args(&stapler, None), ["--dims", "0.05,0.17,0.07", "--h", "0.07"]);
let clock: Object = serde_json::from_value(serde_json::json!({"id": "clock", "label": "Clock", "h": 0.14})).unwrap();
assert_eq!(crate::kit::fit_args(&clock, Some([1.0, 1.0, 0.5])), ["--h", "0.14"]);
assert!((crate::kitout::frame_size(&stapler) - 0.17).abs() < 1e-9);
}
+10
View File
@@ -85,4 +85,14 @@ pub fn encode(srcs: &[(PathBuf, Option<f64>, Option<f64>)], height: Option<u32>,
Ok(json!({"wrote": out, "frames": frames, "seconds": round3(frames as f64 / fps), "width": w, "height": h, "fps": round3(fps), "kbps": kbps, "bytes": stats.bytes, "sound": any_sound}))
}
/// `media share`: a copy any phone, chat and upload form takes (H.264 and AAC in an MP4, its index first), held to
/// `cap` kbit/s (2600: a 1080p minute in about 20 MB) and never given more than a full-size copy would get (#219).
pub fn share(file: &Path, height: Option<u32>, out: &Path, cap: u32) -> R<Value> {
std::fs::metadata(file).map_err(|e| format!("{}: {e}", file.display()))?; // the platform's decoder panics on no path
let i = backend()?.open_video(file).map_err(|e| format!("{}: {e}", file.display()))?.info().clone();
let k = height.map_or(1.0, |h| (h as f64 / i.height as f64).min(1.0));
let full = (i.width as f64 * k * i.height as f64 * k * standard_fps(i.fps) * 0.1 / 1000.0).max(300.0) as u32;
encode(&[(file.to_path_buf(), None, None)], height, out, Some(cap.min(full)))
}
// ---- ffmpeg and ffprobe, read
+15 -2
View File
@@ -38,6 +38,8 @@ pub(crate) fn ffmpeg(args: &[String]) -> R<()> {
let mut pending = FfInput::default();
let (mut ss, mut t, mut to) = (None, None, None);
let (mut vf, mut af): (Option<String>, Option<String>) = (None, None);
// -maxrate: the rate the copy is held to, the one quality choice read (the skill's share copy, #219)
let mut cap = None::<u32>;
let (mut ar, mut ac, mut fmt, mut one_frame, mut outp) = (None, None, None, false, None::<String>);
let mut i = 0;
let next = |i: &mut usize| -> R<String> {
@@ -76,11 +78,19 @@ pub(crate) fn ffmpeg(args: &[String]) -> R<()> {
"-ar" => ar = Some(next(&mut i)?.parse::<u32>().map_err(|_| "-ar takes a rate")?),
"-ac" => ac = Some(next(&mut i)?.parse::<u32>().map_err(|_| "-ac takes a channel count")?),
"-frames:v" | "-vframes" => one_frame = next(&mut i)? == "1",
"-maxrate" => {
let v = next(&mut i)?.to_lowercase();
let (n, k) = match v.strip_suffix('k').map(|n| (n, 1.0)).or(v.strip_suffix('m').map(|n| (n, 1000.0))) {
Some(nk) => nk,
None => (v.as_str(), 0.001),
};
cap = Some((n.parse::<f64>().map_err(|_| "-maxrate takes a rate (2600k)")? * k).round().max(1.0) as u32);
}
"-filter_complex" | "-lavfi" => {
return Err(format!("-filter_complex isn't read here: overlays, wipes and layouts are a composition, rendered with raea render. Or {VERBS_HINT}"));
}
// codec, quality and container choices: the platform encoder decides (H.264 + AAC in MP4)
"-c" | "-c:v" | "-c:a" | "-codec" | "-vcodec" | "-acodec" | "-crf" | "-preset" | "-b:v" | "-b:a" | "-q:v" | "-qscale:v" | "-pix_fmt" | "-movflags" | "-v" | "-loglevel" | "-r" | "-safe" | "-map" | "-tune" | "-profile:v" | "-g" | "-threads" => {
"-c" | "-c:v" | "-c:a" | "-codec" | "-vcodec" | "-acodec" | "-crf" | "-preset" | "-b:v" | "-b:a" | "-q:v" | "-qscale:v" | "-pix_fmt" | "-movflags" | "-v" | "-loglevel" | "-r" | "-safe" | "-map" | "-tune" | "-profile:v" | "-g" | "-threads" | "-bufsize" => {
next(&mut i)?;
}
"-y" | "-n" | "-hide_banner" | "-nostats" | "-nostdin" | "-an" | "-vn" | "-sn" | "-shortest" | "-accurate_seek" => {}
@@ -194,7 +204,10 @@ pub(crate) fn ffmpeg(args: &[String]) -> R<()> {
} else {
vec![(path.clone(), from, until)]
};
encode(&srcs, height, Path::new(&out), None)?;
match (cap, srcs.as_slice()) {
(Some(cap), [(one, None, None)]) => share(one, height, Path::new(&out), cap)?,
(cap, _) => encode(&srcs, height, Path::new(&out), cap)?,
};
Ok(())
}
+20 -4
View File
@@ -11,6 +11,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 share FILE [--kbps 2600] [--height H] -o OUT.mp4 a copy to send: any player takes it, held to a bitrate
//! 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)
@@ -80,6 +81,17 @@ fn ext(p: &Path) -> String {
p.extension().map(|e| e.to_string_lossy().to_lowercase()).unwrap_or_default()
}
/// One argument as the files it names. A shell that doesn't split a variable (zsh's `$FILES`) hands every name over as
/// one argument, which read as a single path fails as "No such file", or past 255 bytes as "File name too long" (#218):
/// an argument that isn't a file, but whose words each are, is those files.
fn names(a: &str) -> Vec<String> {
let words: Vec<&str> = a.split_whitespace().collect();
if words.len() > 1 && !Path::new(a).exists() && words.iter().all(|w| Path::new(w).exists()) {
return words.into_iter().map(String::from).collect();
}
vec![a.to_string()]
}
/// `--name value` flags (and `-o`), switches, and positional arguments.
fn parse(args: &[String]) -> (Vec<String>, BTreeMap<String, String>) {
let (mut pos, mut fl) = (Vec::new(), BTreeMap::new());
@@ -95,7 +107,7 @@ fn parse(args: &[String]) -> (Vec<String>, BTreeMap<String, String>) {
i += 1;
}
} else {
pos.push(a.clone());
pos.extend(names(a));
}
i += 1;
}
@@ -107,11 +119,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", "lod", "trim", "concat", "encode", "help"];
pub const VERBS: &[&str] = &["probe", "still", "sheet", "audio", "loudness", "motion", "cuts", "freezes", "proxy", "share", "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|lod|trim|concat|encode> FILE ... (raea media help)");
println!("usage: raea media <probe|still|sheet|audio|loudness|motion|cuts|proxy|share|lod|trim|concat|encode> FILE ... (raea media help)");
return 2;
};
let (pos, fl) = parse(&args[1..]);
@@ -187,6 +199,10 @@ fn run(verb: &str, pos: &[String], fl: &BTreeMap<String, String>) -> R<Option<Va
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)
}
"share" => {
let cap = fl.get("kbps").and_then(|k| k.parse().ok()).unwrap_or(2600);
share(&file()?, fl.get("height").and_then(|h| h.parse().ok()), &out()?, cap).map(Some)
}
"trim" => {
let (from, to) = range()?;
if from.is_none() && to.is_none() {
@@ -210,6 +226,6 @@ fn run(verb: &str, pos: &[String], fl: &BTreeMap<String, String>) -> R<Option<Va
println!("{}", include_str!("lib.rs").lines().take_while(|l| l.starts_with("//!")).map(|l| l.trim_start_matches("//!").strip_prefix(' ').unwrap_or("")).collect::<Vec<_>>().join("\n"));
Ok(None)
}
v => Err(format!("no media verb {v:?}: probe, still, sheet, audio, loudness, motion, cuts, freezes, proxy, trim, concat, encode")),
v => Err(format!("no media verb {v:?}: probe, still, sheet, audio, loudness, motion, cuts, freezes, proxy, share, trim, concat, encode")),
}
}
+3 -1
View File
@@ -4,9 +4,11 @@ version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "`raea motion` and `raea setup motion`: body motion made by Kimodo on this machine, on MLX on a Mac, on PyTorch elsewhere"
description = "`raea make motion` and `raea setup motion`: body motion made by Kimodo on this machine, on MLX on a Mac, on PyTorch elsewhere"
[dependencies]
# a take's joints as vectors (score.rs)
glam = "0.33"
# raea's models folder, where the models and the PyTorch environment go
raea-io-home = { path = "../../io/home" }
serde_json = "1"
+12
View File
@@ -0,0 +1,12 @@
//! `raea make motion` without the rest of the CLI, for working on this crate while the workspace's other crates are mid-change:
//! `lane build -- cargo run --release -p raea-app-motion --example motion -- "LINE" --seeds 4 -o CLIP.json`
fn main() {
let args: Vec<String> = std::iter::once("motion".to_string()).chain(std::env::args().skip(1)).collect();
match raea_app_motion::motion(&args) {
Ok(s) => println!("{s}"),
Err(e) => {
eprintln!("{e}");
std::process::exit(1)
}
}
}
+67 -24
View File
@@ -1,4 +1,4 @@
//! `raea motion "LINE" [--keys KEYS.json] ...`: body motion made on this machine by Kimodo (raea-sys-kimodo): a SOMA clip
//! `raea make motion "LINE" [--keys KEYS.json] ...`: body motion made on this machine by Kimodo (raea-sys-kimodo): a SOMA clip
//! from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path:
//! what sdk/body/tools/between.ts writes). The clip is the file sdk/body/tools/fromkimodo.ts reads, the same one the
//! cloud runner wrote (docs/character.feature CH15b, CH15c).
@@ -9,15 +9,17 @@
use std::path::PathBuf;
mod score;
use raea_runtime_bundle::flag;
type R<T> = Result<T, String>;
pub const USAGE: &str = "raea motion \"LINE\" [--keys KEYS.json] [--seconds 5 | --frames N] [--seed 1] [--steps 100] [-o CLIP.json]";
pub const ABOUT: &str = "body motion made on this machine by Kimodo (NVIDIA): a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads. On a Mac it runs on MLX (Apple silicon's GPU): the first use fetches the motion model (1.1 GB) into raea's models folder, and the first new line its text encoder (8.8 GB: Llama 3 8B in 8 bits with LLM2Vec's adapters). On Linux and Windows it runs upstream Kimodo on PyTorch, set up once by raea setup motion: on an NVIDIA GPU with CUDA (the text encoder, 16 GB in bf16, on the CPU unless the card has 18 GB or more), else on the CPU alone; reading a new line on the CPU takes about 18 GB of memory. A line's words are read once and kept. Licences: Kimodo's weights NVIDIA's Open Model License, Meta Llama 3 the Meta Llama 3 Community License, LLM2Vec's adapters MIT, Kimodo's code Apache-2.0";
pub const USAGE: &str = "raea make motion \"LINE\" [--keys KEYS.json] [--seconds 5 | --frames N] [--seed 1] [--seeds 1] [--steps 100] [-o CLIP.json]";
pub const ABOUT: &str = "body motion made on this machine by Kimodo (NVIDIA): a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads. On a Mac it runs on MLX (Apple silicon's GPU): the first use fetches the motion model (1.1 GB) into raea's models folder, and the first new line its text encoder (8.8 GB: Llama 3 8B in 8 bits with LLM2Vec's adapters). On Linux and Windows it runs upstream Kimodo on PyTorch, set up once by raea setup motion: on an NVIDIA GPU with CUDA (the text encoder, 16 GB in bf16, on the CPU unless the card has 18 GB or more), else on the CPU alone; reading a new line on the CPU takes about 18 GB of memory. A line's words are read once and kept. --seeds N makes N takes (seeds SEED to SEED+N-1) and keeps the one with the fewest faults: a foot sliding while planted, the shoulders shrugging, the hips sinking, a hand or forearm into the torso or head (a skeletal check; each take's score is printed and the kept one's written into the clip). Licences: Kimodo's weights NVIDIA's Open Model License, Meta Llama 3 the Meta Llama 3 Community License, LLM2Vec's adapters MIT, Kimodo's code Apache-2.0";
pub const SETUP_USAGE: &str = "raea setup motion [--check]";
pub const SETUP_ABOUT: &str = "what raea motion runs on, made where missing (--check only says): on a Mac the MLX models in raea's models folder (the motion model 1.1 GB, the text encoder 8.8 GB); on Linux and Windows, in raea's models folder's kimodo-torch, a Python 3.11 environment made by uv (which it needs on PATH: https://docs.astral.sh/uv) with PyTorch (its CUDA build where there is an NVIDIA driver, about 8 GB, else CPU only, about 2 GB) and upstream Kimodo (nv-tlabs/kimodo at e1c219c, Apache-2.0), then the weights: Kimodo-SOMA-RP-v1 (1.1 GB, NVIDIA Open Model License), LLM2Vec's two adapters (0.3 GB, MIT) and Meta Llama 3 8B Instruct in bf16 (16 GB, Meta Llama 3 Community License, from NousResearch's ungated copy, checked file by file against Meta's SHA-256); about 26 GB in all. It says what this machine has and where each network runs: the denoiser on CUDA when there is an NVIDIA GPU, else the CPU; the text encoder beside it on a GPU of 18 GB or more, else the CPU";
pub const SETUP_ABOUT: &str = "what raea make motion runs on, made where missing (--check only says): on a Mac the MLX models in raea's models folder (the motion model 1.1 GB, the text encoder 8.8 GB); on Linux and Windows, in raea's models folder's kimodo-torch, a Python 3.11 environment made by uv (which it needs on PATH: https://docs.astral.sh/uv) with PyTorch (its CUDA build where there is an NVIDIA driver, about 8 GB, else CPU only, about 2 GB) and upstream Kimodo (nv-tlabs/kimodo at e1c219c, Apache-2.0), then the weights: Kimodo-SOMA-RP-v1 (1.1 GB, NVIDIA Open Model License), LLM2Vec's two adapters (0.3 GB, MIT) and Meta Llama 3 8B Instruct in bf16 (16 GB, Meta Llama 3 Community License, from NousResearch's ungated copy, checked file by file against Meta's SHA-256); about 26 GB in all. It says what this machine has and where each network runs: the denoiser on CUDA when there is an NVIDIA GPU, else the CPU; the text encoder beside it on a GPU of 18 GB or more, else the CPU";
fn number(args: &[String], name: &str, default: f64) -> R<f64> {
match flag(args, name) {
@@ -27,7 +29,7 @@ fn number(args: &[String], name: &str, default: f64) -> R<f64> {
}
fn line(args: &[String]) -> String {
const WITH_VALUE: [&str; 6] = ["--keys", "--seconds", "--frames", "--seed", "--steps", "-o"];
const WITH_VALUE: [&str; 7] = ["--keys", "--seconds", "--frames", "--seed", "--seeds", "--steps", "-o"];
let mut out = Vec::new();
let mut i = 1;
while i < args.len() {
@@ -50,6 +52,7 @@ struct Ask {
constraints: Option<serde_json::Value>,
frames: usize,
seed: u64,
seeds: usize,
steps: usize,
out: Option<String>,
}
@@ -64,15 +67,21 @@ pub fn motion(args: &[String]) -> R<String> {
Some(_) => number(args, "--frames", 150.0)? as usize,
None => (number(args, "--seconds", 5.0)? * 30.0).round() as usize,
};
if !(2..=600).contains(&frames) {
return Err(format!("a clip is 2 to 600 frames (20 s at 30 a second), asked {frames}"));
// Kimodo's own limit (its docs, key_concepts/limitations.md): past 10 s a clip drifts and breaks up (11-27: a
// 12.3 s talk clip's feet spread 47 -> 69 cm, shoulders rose 9 cm, the last half second glitched)
if !(2..=300).contains(&frames) {
return Err(format!(
"a clip is 2 to 300 frames (10 s at 30 a second, Kimodo's limit: longer clips drift and break up), asked {frames}; \
for longer, make 10 s clips one after another, each from --keys holding the last frames of the one before"
));
}
let constraints = match &keys {
Some(p) => Some(serde_json::from_str::<serde_json::Value>(&std::fs::read_to_string(p).map_err(|e| format!("{p}: {e}"))?).map_err(|e| format!("{p}: {e}"))?),
None => None,
};
let (seed, steps) = (number(args, "--seed", 1.0)? as u64, (number(args, "--steps", 100.0)? as usize).max(2));
make(Ask { words, keys, constraints, frames, seed, steps, out: flag(args, "-o") })
let seeds = (number(args, "--seeds", 1.0)? as usize).clamp(1, 32);
make(Ask { words, keys, constraints, frames, seed, seeds, steps, out: flag(args, "-o") })
}
/// -o, else a file named by the line's words in the working folder
@@ -83,6 +92,25 @@ fn out_path(out: Option<String>, clean: &str) -> PathBuf {
}))
}
/// the take with the lowest score of those made, its seed, and a line per take ("" for a single take)
fn keep_best(takes: Vec<(u64, raea_sys_kimodo::decode::Motion)>, sk: &raea_sys_kimodo::skeleton::Skeleton) -> (u64, raea_sys_kimodo::decode::Motion, Option<score::Score>, String) {
let one = takes.len() == 1;
let mut scored: Vec<(u64, raea_sys_kimodo::decode::Motion, score::Score)> = takes.into_iter().map(|(s, m)| { let sc = score::score(&m, sk); (s, m, sc) }).collect();
let report = if one { String::new() } else { scored.iter().map(|(s, _, sc)| format!("\n seed {s}: {}", sc.line())).collect::<String>() };
scored.sort_by(|a, b| a.2.total.total_cmp(&b.2.total));
let (s, m, sc) = scored.remove(0);
(s, m, Some(sc), report)
}
/// the kept take's score, written into the clip
fn with_score(mut clip: serde_json::Value, sc: &Option<score::Score>, tried: usize) -> serde_json::Value {
if let Some(sc) = sc {
clip["score"] = serde_json::json!({"total": sc.total, "foot_drift_cm": sc.foot_drift_cm, "shoulder_rise_cm": sc.shoulder_rise_cm,
"hip_drop_cm": sc.hip_drop_cm, "collision_cm": sc.collision_cm, "takes": tried});
}
clip
}
/// how far the hips end from where they start, on the ground
fn travel(m: &raea_sys_kimodo::decode::Motion) -> f32 {
let r = &m.root;
@@ -103,16 +131,23 @@ fn make(ask: Ask) -> R<String> {
let missing = t.missing();
if !missing.is_empty() {
return Err(format!(
"raea motion runs Kimodo on PyTorch on this machine (MLX is Apple silicon's), and its {} isn't set up in {} yet: raea setup motion makes it (uv, then about 26 GB: PyTorch, Kimodo's code and weights, Llama 3 8B Instruct for the text encoder)",
"raea make motion runs Kimodo on PyTorch on this machine (MLX is Apple silicon's), and its {} isn't set up in {} yet: raea setup motion makes it (uv, then about 26 GB: PyTorch, Kimodo's code and weights, Llama 3 8B Instruct for the text encoder)",
missing.join(", the "),
t.dir.display()
));
}
let keys = ask.keys.as_ref().map(std::path::Path::new);
let job = torch::Job { line: &ask.words, frames: ask.frames, seed: ask.seed, steps: ask.steps, keys, cfg: (2.0, 2.0) };
let made = t.make(&job).map_err(|e| format!("raea motion: {e}"))?;
let (stats, sk) = (Stats::load(&t.checkpoint).map_err(|e| format!("raea motion: {e}"))?, Skeleton::soma().map_err(|e| format!("raea motion: {e}"))?);
let motion = decode::decode(&made.features, &stats, &sk);
let mut takes = Vec::new();
let mut last = None;
for s in ask.seed..ask.seed + ask.seeds as u64 {
let job = torch::Job { line: &ask.words, frames: ask.frames, seed: s, steps: ask.steps, keys, cfg: (2.0, 2.0) };
let made = t.make(&job).map_err(|e| format!("raea motion: {e}"))?;
takes.push((s, decode::decode(&made.features, &stats, &sk)));
last = Some(made);
}
let made = last.ok_or("raea motion: no take")?;
let (seed, motion, sc, report) = keep_best(takes, &sk);
let info = &made.info;
let clean = info["line"].as_str().unwrap_or(&ask.words).to_string();
let (dev, text_dev) = (info["motion"].as_str().unwrap_or("?"), info["text"].as_str().unwrap_or("?"));
@@ -120,26 +155,28 @@ fn make(ask: Ask) -> R<String> {
Some(g) => format!("on PyTorch {} with CUDA ({g}; the text encoder on {text_dev}), upstream nv-tlabs/kimodo {}", info["torch"].as_str().unwrap_or("?"), &torch::KIMODO[..7]),
None => format!("on PyTorch {} on the CPU, upstream nv-tlabs/kimodo {}", info["torch"].as_str().unwrap_or("?"), &torch::KIMODO[..7]),
};
let clip = decode::clip_json_on(&motion, &sk, ask.seed, ask.steps, &clean, ask.constraints.is_some(), &on);
let clip = with_score(decode::clip_json_on(&motion, &sk, seed, ask.steps, &clean, ask.constraints.is_some(), &on), &sc, ask.seeds);
let out = out_path(ask.out, &clean);
std::fs::write(&out, serde_json::to_string(&clip).unwrap_or_default()).map_err(|e| format!("{}: {e}", out.display()))?;
// the hips as PyTorch decoded them against decode.rs's: the features were read as Kimodo wrote them
let ours: Vec<[f32; 3]> = motion.joints77.iter().map(|f| f[0]).collect();
let gap = torch::root_gap(&info["root"], &ours).map(|g| format!(", decoded here within {:.3} mm of PyTorch's own", g * 1000.0)).unwrap_or_default();
let gap = if ask.seeds > 1 { String::new() } else { torch::root_gap(&info["root"], &ours).map(|g| format!(", decoded here within {:.3} mm of PyTorch's own", g * 1000.0)).unwrap_or_default() };
let f = |k: &str| info[k].as_f64().unwrap_or(0.0);
let read = if f("read_s") > 0.0 { format!(", reading the line {:.1} s after {:.1} s loading its encoder", f("read_s"), f("text_load_s")) } else { String::new() };
Ok(format!(
"APPLIED motion {:?}{}, {} frames ({:.1} s), seed {}, {} steps -> {} (made {on} in {:.1} s after {:.1} s loading{read}; the hips end {:.2} m from where they start{gap})",
"APPLIED motion {:?}{}, {} frames ({:.1} s), seed {}{}, {} steps -> {} (made {on} in {:.1} s after {:.1} s loading{read}; the hips end {:.2} m from where they start{gap}; {}){report}",
clean,
if ask.keys.is_some() { " with keys" } else { "" },
ask.frames,
ask.frames as f64 / 30.0,
ask.seed,
seed,
if ask.seeds > 1 { format!(", the best of {} takes", ask.seeds) } else { String::new() },
ask.steps,
out.display(),
f("gen_s"),
f("load_s"),
travel(&motion),
sc.as_ref().map(|s| s.line()).unwrap_or_default(),
))
}
@@ -154,23 +191,29 @@ fn make(ask: Ask) -> R<String> {
let mut k = raea_sys_kimodo::Kimodo::fetch(&mut progress).map_err(|e| format!("raea motion: {e}"))?;
let (clean, emb) = k.encode(&ask.words).map_err(|e| format!("raea motion: {e}"))?;
let load_s = t0.elapsed().as_secs_f64();
let made_from = raea_sys_kimodo::Ask { line: &ask.words, frames: ask.frames, seed: ask.seed, steps: ask.steps, constraints: ask.constraints.as_ref(), cfg: (2.0, 2.0) };
let t1 = std::time::Instant::now();
let made = k.make(&made_from, emb.as_deref(), None).map_err(|e| format!("raea motion: {e}"))?;
let mut takes = Vec::new();
for s in ask.seed..ask.seed + ask.seeds as u64 {
let made_from = raea_sys_kimodo::Ask { line: &ask.words, frames: ask.frames, seed: s, steps: ask.steps, constraints: ask.constraints.as_ref(), cfg: (2.0, 2.0) };
takes.push((s, k.make(&made_from, emb.as_deref(), None).map_err(|e| format!("raea motion: {e}"))?.motion));
}
let gen_s = t1.elapsed().as_secs_f64();
let clip = raea_sys_kimodo::decode::clip_json(&made.motion, &k.skeleton, ask.seed, ask.steps, &clean, ask.constraints.is_some());
let (seed, motion, sc, report) = keep_best(takes, &k.skeleton);
let clip = with_score(raea_sys_kimodo::decode::clip_json(&motion, &k.skeleton, seed, ask.steps, &clean, ask.constraints.is_some()), &sc, ask.seeds);
let out = out_path(ask.out, &clean);
std::fs::write(&out, serde_json::to_string(&clip).unwrap_or_default()).map_err(|e| format!("{}: {e}", out.display()))?;
Ok(format!(
"APPLIED motion {:?}{}, {} frames ({:.1} s), seed {}, {} steps -> {} (made on this Mac in {gen_s:.1} s after {load_s:.1} s loading and reading the line; the hips end {:.2} m from where they start)",
"APPLIED motion {:?}{}, {} frames ({:.1} s), seed {}{}, {} steps -> {} (made on this Mac in {gen_s:.1} s after {load_s:.1} s loading and reading the line; the hips end {:.2} m from where they start; {}){report}",
clean,
if ask.keys.is_some() { " with keys" } else { "" },
ask.frames,
ask.frames as f64 / 30.0,
ask.seed,
seed,
if ask.seeds > 1 { format!(", the best of {} takes", ask.seeds) } else { String::new() },
ask.steps,
out.display(),
travel(&made.motion)
travel(&motion),
sc.as_ref().map(|s| s.line()).unwrap_or_default(),
))
}
@@ -190,7 +233,7 @@ fn disk(dir: &std::path::Path) -> String {
raea_io_home::disk_use(dir, true)
}
/// `raea setup motion [--check]`: what raea motion runs on here, made where missing (--check only says), and where it is.
/// `raea setup motion [--check]`: what raea make motion runs on here, made where missing (--check only says), and where it is.
pub fn setup(args: &[String]) -> R<String> {
let check = args.iter().any(|a| a == "--check");
if let Some(a) = args.iter().find(|a| *a != "--check") {
@@ -214,7 +257,7 @@ fn setup_here(check: bool) -> R<String> {
let state = match (had, has) {
(true, _) => "installed",
(false, true) => "installed now",
(false, false) => "not installed: raea setup motion fetches it (raea motion does too, the first time it needs it)",
(false, false) => "not installed: raea setup motion fetches it (raea make motion does too, the first time it needs it)",
};
lines.push(format!(" {name:<12} {state}; {what}\n {} ({})", dir.display(), if *has { disk(dir) } else { "-".into() }));
}
+111
View File
@@ -0,0 +1,111 @@
//! A take scored for the faults a body shows (sheet3d plan E3), so `raea make motion --seeds N` can keep the best of N:
//! a foot sliding while it's planted, the shoulders shrugging up, the hips sinking, and a hand or forearm inside the
//! torso or head. Read from the take's own joints (Kimodo's SOMA skeleton, metres, Y up) and its foot contacts.
//! Collision is a skeletal proxy: capsules round the spine and a sphere for the head, sized for SOMA's average adult;
//! the mesh check on the body a clip drives is the join's (sheet3d's join.py: head-in-body frames).
use raea_sys_kimodo::decode::Motion;
use raea_sys_kimodo::skeleton::Skeleton;
use glam::Vec3;
/// each fault in centimetres (collision: the deepest a hand or forearm point goes into the torso or head), and
/// their sum, each over its own allowance: 1 cm of drift, 3 cm of shrug, 5 cm of sinking, 1 cm into the body
pub struct Score {
pub foot_drift_cm: f32,
pub shoulder_rise_cm: f32,
pub hip_drop_cm: f32,
pub collision_cm: f32,
pub total: f32,
}
fn idx(sk: &Skeleton, n: &str) -> usize {
sk.names77.iter().position(|x| x == n).unwrap_or(0)
}
/// how far p is inside the capsule a-b of radius r (0 outside)
fn inside(p: [f32; 3], a: [f32; 3], b: [f32; 3], r: f32) -> f32 {
let (p, a, b) = (Vec3::from(p), Vec3::from(a), Vec3::from(b));
let ab = b - a;
let t = ((p - a).dot(ab) / ab.length_squared().max(1e-9)).clamp(0.0, 1.0);
(r - p.distance(a + t * ab)).max(0.0)
}
fn median(mut v: Vec<f32>) -> f32 {
if v.is_empty() {
return 0.0;
}
v.sort_by(|a, b| a.total_cmp(b));
v[v.len() / 2]
}
pub fn score(m: &Motion, sk: &Skeleton) -> Score {
let j = &m.joints77;
let n = j.len();
// a foot planted: its horizontal travel over each run of contact frames, the worst run
let feet = [("LeftFoot", 0), ("LeftToeBase", 1), ("RightFoot", 3), ("RightToeBase", 4)];
let mut drift = 0f32;
for (name, c) in feet {
let k = idx(sk, name);
let mut start: Option<usize> = None;
for f in 0..=n {
let on = f < n && m.contacts[f][c];
match (on, start) {
(true, None) => start = Some(f),
(false, Some(s)) => {
let mut far = 0f32;
for g in s..f {
let d = Vec3::from(j[g][k]) - Vec3::from(j[s][k]);
far = far.max(d.x.hypot(d.z));
}
drift = drift.max(far);
start = None;
}
_ => {}
}
}
}
// shoulders above the chest: the highest against the take's own usual, both sides
let chest = idx(sk, "Chest");
let mut rise = 0f32;
for s in ["LeftShoulder", "RightShoulder"] {
let k = idx(sk, s);
let h: Vec<f32> = j.iter().map(|f| f[k][1] - f[chest][1]).collect();
let med = median(h.clone());
rise = rise.max(h.iter().fold(f32::MIN, |a, &b| a.max(b)) - med);
}
// hips below where they stand: the lowest against the first second's median
let hips = idx(sk, "Hips");
let stand = median(j.iter().take(30).map(|f| f[hips][1]).collect());
let drop = (stand - j.iter().fold(f32::MAX, |a, f| a.min(f[hips][1]))).max(0.0);
// hands and forearms against the torso (hips to chest, chest to neck) and the head
let (spine1, neck, head) = (idx(sk, "Spine1"), idx(sk, "Neck1"), idx(sk, "Head"));
let limbs: Vec<usize> = ["LeftHand", "RightHand", "LeftHandMiddle1", "RightHandMiddle1"].iter().map(|x| idx(sk, x)).collect();
let fore = [("LeftArm", "LeftForeArm", "LeftHand"), ("RightArm", "RightForeArm", "RightHand")];
let mut deep = 0f32;
for f in j {
let mut pts: Vec<[f32; 3]> = limbs.iter().map(|&k| f[k]).collect();
for (_, e, h) in fore {
let (a, b) = (f[idx(sk, e)], f[idx(sk, h)]);
pts.push([(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0, (a[2] + b[2]) / 2.0]);
}
for p in pts {
let d = inside(p, f[hips], f[spine1], 0.12)
.max(inside(p, f[spine1], f[chest], 0.13))
.max(inside(p, f[chest], f[neck], 0.11))
.max(inside(p, f[head], f[head], 0.09));
deep = deep.max(d);
}
}
let (d, r, h, c) = (drift * 100.0, rise * 100.0, drop * 100.0, deep * 100.0);
Score { foot_drift_cm: d, shoulder_rise_cm: r, hip_drop_cm: h, collision_cm: c, total: d / 1.0 + r / 3.0 + h / 5.0 + c / 1.0 }
}
impl Score {
pub fn line(&self) -> String {
format!(
"score {:.2} (foot drift {:.1} cm, shoulder rise {:.1} cm, hip drop {:.1} cm, hand into body {:.1} cm)",
self.total, self.foot_drift_cm, self.shoulder_rise_cm, self.hip_drop_cm, self.collision_cm
)
}
}
+17
View File
@@ -0,0 +1,17 @@
[package]
name = "raea-app-playable"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "`raea playable`: a raea game exported as a playable ad, one page or ZIP per ad network (docs/playables.feature)"
[dependencies]
dunce = "1"
# the game and sdk/playable's host bundled into one page by raea's own bundler (Rolldown, in process)
raea-runtime-bundle = { path = "../../runtime/bundle" }
# where raea's files are: an install's share/raea, else this checkout
raea-io-home = { path = "../../io/home" }
regex = "1"
serde_json = "1"
zip = { version = "9", default-features = false, features = ["deflate-flate2"] }
+102
View File
@@ -0,0 +1,102 @@
//! `raea playable GAME.tsx -o DIR`: a raea game exported as a playable ad (docs/playables.feature PA13). The same TSX
//! that renders with `raea render` as the video ad (it plays itself) is linted (lint.rs), bundled once with
//! sdk/playable's browser host by raea's own bundler (Rolldown, in process: minified, its pictures and tables carried
//! in the script, one three.js), and written as each network's page or ZIP (pages.rs), each checked against its cap.
mod lint;
mod pages;
use std::path::{Path, PathBuf};
type R<T> = Result<T, String>;
pub const USAGE: &str = "raea playable GAME.tsx -o DIR [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both]";
pub const ABOUT: &str = "a game as a playable ad: one page or ZIP per network (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff, preview), each under its 5 MB cap, from the TSX that renders as the video ad";
/// A path as an import specifier (no Windows verbatim prefix, which Rolldown can't open): raea-bundle's own
pub(crate) use raea_runtime_bundle::spec;
fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
}
/// The folder whose node_modules holds the three.js a playable draws with: the project's own (`raea add [email protected]`),
/// else the copy beside sdk/playable or sdk/r3f in raea's own files
fn three_dir(game: &Path, home: &Path) -> R<PathBuf> {
let mut d = game.parent();
while let Some(dir) = d {
if dir.join("node_modules/three/package.json").is_file() {
return Ok(dir.to_path_buf());
}
d = dir.parent();
}
["sdk/playable", "sdk/r3f"]
.iter()
.map(|p| home.join(p))
.find(|d| d.join("node_modules/three/package.json").is_file())
.ok_or_else(|| "a playable draws its 3D with three.js, which this project doesn't have: `raea add [email protected]` in it".into())
}
/// The game and the host in one minified script that carries its files
fn bundle(game: &Path, home: &Path) -> R<String> {
let host = home.join("sdk/playable/src/host/main.tsx");
if !host.is_file() {
return Err(format!("{}: raea's playable host isn't there", host.display()));
}
let three = three_dir(game, home)?;
let out = std::env::temp_dir().join(format!("raea-playable-{}.js", std::process::id()));
let entry = format!("import {:?};\nimport {:?};\n", spec(game), spec(&host));
let alias = format!("three/={}", three.display());
let r = raea_runtime_bundle::bundle_entry(&entry, &out, &["--minify", "1", "--inline", "1", "--alias", &alias]);
let js = r.and_then(|_| std::fs::read_to_string(&out).map_err(|e| e.to_string()));
let _ = std::fs::remove_file(&out);
js
}
pub fn cli(args: &[String]) -> R<String> {
let game = args.get(1).filter(|a| !a.starts_with('-')).ok_or(USAGE)?;
let game = dunce::canonicalize(game).map_err(|e| format!("{game}: {e}"))?;
let out = PathBuf::from(flag(args, "-o").ok_or(format!("-o DIR is required: {USAGE}"))?);
let networks: Vec<&str> = flag(args, "--networks").map(|n| n.split(',').filter(|s| !s.is_empty()).collect()).unwrap_or_else(|| pages::NETWORKS.to_vec());
if let Some(bad) = networks.iter().find(|n| !pages::NETWORKS.contains(n)) {
return Err(format!("raea playable: no network {bad} (one of {})", pages::NETWORKS.join(", ")));
}
let orientation = flag(args, "--orientation").unwrap_or("both");
if !["portrait", "landscape", "both"].contains(&orientation) {
return Err("--orientation is portrait, landscape or both".into());
}
let store = serde_json::json!({"ios": flag(args, "--ios").unwrap_or(""), "android": flag(args, "--android").unwrap_or("")}).to_string();
let card = serde_json::json!({"title": flag(args, "--title").unwrap_or(""), "cta": flag(args, "--cta").unwrap_or("Play now")}).to_string();
let name = game.file_stem().and_then(|s| s.to_str()).unwrap_or("playable").to_string();
let mut report = Vec::new();
let found = lint::lint(&game)?;
report.push(format!("3D kinds: {}", if found.kinds.is_empty() { "none".into() } else { found.kinds.join(", ") }));
for c in &found.comps {
let shape = if c.height > c.width { "portrait" } else { "landscape" };
report.push(format!("composition {}: {}x{} {shape}, {} fps, {:.0} s", c.id, c.width, c.height, c.fps, c.frames as f64 / c.fps.max(1.0)));
}
report.extend(found.notes.iter().map(|n| format!("note: {n}")));
if !found.refusals.is_empty() {
// the reasons first: the CLI marks an error's first line REFUSED
let mut why = found.refusals.clone();
why.extend(report);
return Err(why.join("\n"));
}
let js = bundle(&game, &raea_io_home::home())?;
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
let mut over = false;
for net in networks {
let script = format!("{}\n{js}", pages::preamble(net, &store, &card));
let w = pages::write(net, &name, &script, &out, orientation)?;
let ok = w.bytes <= pages::CAP;
over |= !ok;
report.push(format!("{:<10} {:<40} {:>6} KB / {} KB {}", w.network, w.file.display(), w.bytes / 1024, pages::CAP / 1024, if ok { "ok" } else { "OVER" }));
}
if over {
report.insert(0, format!("a page is over its network's {} KB cap", pages::CAP / 1024));
return Err(report.join("\n"));
}
report.push(format!("APPLIED {name} exported as a playable to {}", out.display()));
Ok(report.join("\n"))
}
+104
View File
@@ -0,0 +1,104 @@
//! What a playable can't have, refused before it is bundled (docs/playables.feature PA4): the source read for files
//! from disk, the network and the native engine's modules; the compositions rendered (sdk/playable/src/export/walk.ts,
//! through `raea run` in a process of its own) for their shapes and the 3D kinds the host doesn't draw.
use super::R;
use serde_json::Value;
use std::path::Path;
/// One composition the game registers
pub struct Comp {
pub id: String,
pub width: u32,
pub height: u32,
pub fps: f64,
pub frames: u64,
}
/// What the lint found: refusals stop the export, notes don't
pub struct Found {
pub comps: Vec<Comp>,
pub kinds: Vec<String>,
pub notes: Vec<String>,
pub refusals: Vec<String>,
}
const SOURCE_RULES: &[(&str, &str)] = &[
(r"\bstaticFile\s*\(", "staticFile() reads the edit's folder at render time; import the file instead (`import icon from \"./icon.png\"`), which the export carries in the page"),
(r"https?://", "a URL in the source: a playable makes no network requests (every network refuses one)"),
(r"\bfetch\s*\(|XMLHttpRequest|WebSocket", "fetch/XHR/WebSocket: a playable makes no network requests"),
(r#"from\s+["']raea/(native|ml|character|physics|media|matchmove|modelling)["']"#, "a module that needs the native engine (native calls, models, physics, footage)"),
(r"<(Video|Audio)\b", "<Video>/<Audio> play through the native media stack; a playable's sound is PA6 (not yet)"),
];
/// The game's source and its compositions, judged
pub fn lint(game: &Path) -> R<Found> {
let src = std::fs::read_to_string(game).map_err(|e| format!("{}: {e}", game.display()))?;
let mut refusals = Vec::new();
let mut notes = Vec::new();
// a URL the SVG namespace names is a name, not a request
let src_no_ns = src.replace("http://www.w3.org", "");
for (re, why) in SOURCE_RULES {
if regex::Regex::new(re).map_err(|e| e.to_string())?.is_match(&src_no_ns) {
refusals.push(why.to_string());
}
}
if !src.contains("raea/playable") {
notes.push("no raea/playable import: the game never opens the store itself (add an <EndCard> or <InstallButton>); the host's own end card shows at the last frame".into());
}
let walked = match walk(game) {
Ok(w) => w,
// what the source can't have (a fetch, a URL) often stops the render too: the refusal says why, the render's end doesn't
Err(_) if !refusals.is_empty() => return Ok(Found { comps: vec![], kinds: vec![], notes, refusals }),
Err(e) => return Err(e),
};
let comps: Vec<Comp> = walked["comps"]
.as_array()
.into_iter()
.flatten()
.map(|c| Comp {
id: c["id"].as_str().unwrap_or("").into(),
width: c["width"].as_u64().unwrap_or(0) as u32,
height: c["height"].as_u64().unwrap_or(0) as u32,
fps: c["fps"].as_f64().unwrap_or(30.0),
frames: c["frames"].as_u64().unwrap_or(0),
})
.collect();
let strings = |k: &str| walked[k].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(String::from)).collect::<Vec<_>>();
if comps.is_empty() {
refusals.push("no composition registered (registerRoot)".into());
}
if comps.len() == 1 {
notes.push("one composition: the other orientation is letterboxed (Unity, AppLovin, Moloco and Mintegral want both; register a second one at the other shape)".into());
}
for k in strings("refused") {
refusals.push(format!("3D kind {k} isn't drawn in a playable"));
}
Ok(Found { comps, kinds: strings("kinds"), notes, refusals })
}
/// sdk/playable's walk run on the engine (`raea run`) after the game, in a process of its own so the game's React stays
/// out of this one; its answer is the JSON it prints
fn walk(game: &Path) -> R<Value> {
let walk = raea_io_home::home().join("sdk/playable/src/export/walk.ts");
if !walk.is_file() {
return Err(format!("{}: raea's playable SDK isn't there", walk.display()));
}
let work = std::env::temp_dir().join(format!("raea-playable-lint-{}", std::process::id()));
std::fs::create_dir_all(&work).map_err(|e| e.to_string())?;
let entry = work.join("lint.ts");
std::fs::write(&entry, format!("import {:?};\nexport {{ default }} from {:?};\n", super::spec(game), super::spec(&walk))).map_err(|e| e.to_string())?;
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let run = std::process::Command::new(exe).arg("run").arg(&entry).output().map_err(|e| format!("raea run: {e}"));
let _ = std::fs::remove_dir_all(&work);
let run = run?;
let out = String::from_utf8_lossy(&run.stdout);
if !run.status.success() {
let err = String::from_utf8_lossy(&run.stderr);
let said: Vec<&str> = err.lines().chain(out.lines()).filter(|l| !l.trim().is_empty()).collect();
// the line that names the error, else the last one ("… ended with exit 1" says nothing)
let why = said.iter().find(|l| l.contains("Error") || l.contains("error:")).or(said.last()).unwrap_or(&"").trim().to_string();
return Err(format!("the game didn't render for the lint: {why}"));
}
let at = out.find('{').ok_or("the lint's walk printed no answer")?;
serde_json::from_str(&out[at..]).map_err(|e| format!("the lint's walk: {e}"))
}
+100
View File
@@ -0,0 +1,100 @@
//! Each network's package around the one script (docs/playables.feature, the Background's table): the page every
//! network gets, with that network's own tags, as one HTML file or a ZIP, checked against its cap.
use super::R;
use std::io::Write;
use std::path::{Path, PathBuf};
pub const NETWORKS: &[&str] = &["applovin", "unity", "google", "meta", "moloco", "mintegral", "tiktok", "liftoff", "preview"];
/// Every network's cap, 5 MB (TikTok's counted zipped, which is what's written)
pub const CAP: u64 = 5 * 1024 * 1024;
/// What one network got: the file and its size
pub struct Written {
pub network: String,
pub file: PathBuf,
pub bytes: u64,
}
/// The settings a page starts with, as the globals the host reads (sdk/playable network.ts, host/main.tsx): the network,
/// the store links, the end card's words
pub fn preamble(network: &str, store: &str, card: &str) -> String {
format!("var __RAEA_NETWORK__={},__RAEA_STORE__={store},__RAEA_PLAYABLE__={card};", serde_json::to_string(network).unwrap_or_default())
}
/// The page: the network's head and body tags, then the script (a page's inline script ends at the first "</script")
pub fn page(title: &str, head: &str, body: &str, script: &str) -> String {
let title = title.replace('&', "&amp;").replace('<', "&lt;");
format!(
"<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover\">\n<title>{title}</title>\n{head}\n</head>\n<body>\n{body}\n<script>\n{}\n</script>\n</body>\n</html>\n",
script.replace("</script", "<\\/script")
)
}
fn zip(file: &Path, entries: &[(String, String)]) -> R<()> {
let f = std::fs::File::create(file).map_err(|e| format!("{}: {e}", file.display()))?;
let mut w = zip::ZipWriter::new(f);
let o = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
for (name, text) in entries {
w.start_file(name.as_str(), o).map_err(|e| e.to_string())?;
w.write_all(text.as_bytes()).map_err(|e| e.to_string())?;
}
w.finish().map_err(|e| e.to_string())?;
Ok(())
}
/// `network`'s package of `script` (its preamble already first) written into `out` as NAME-NETWORK.html or .zip
pub fn write(network: &str, name: &str, script: &str, out: &Path, orientation: &str) -> R<Written> {
let html = |head: &str, body: &str| page(name, head, body, script);
let file = match network {
// a ZIP with index.html; exitapi.js and the orientation tag in the head (Google Ads help 9981650)
"google" => {
let o = if orientation == "both" { "portrait,landscape" } else { orientation };
let head = format!("<meta name=\"ad.orientation\" content=\"{o}\">\n<script type=\"text/javascript\" src=\"https://tpc.googlesyndication.com/pagead/gadgets/html5/api/exitapi.js\"></script>");
let f = out.join(format!("{name}-google.zip"));
zip(&f, &[("index.html".into(), html(&head, ""))])?;
f
}
// a ZIP with index.html and config.json; TikTok's playable SDK before the game's script (TikTok Ads help)
"tiktok" => {
let o = match orientation {
"portrait" => 1,
"landscape" => 2,
_ => 0,
};
let body = "<script src=\"https://sf16-muse-va.ibytedtos.com/obj/union-fe-nc-i18n/playable/sdk/playable-sdk.js\"></script>";
let f = out.join(format!("{name}-tiktok.zip"));
zip(&f, &[("index.html".into(), html("", body)), ("config.json".into(), format!("{{\"playable_orientation\": {o}}}\n"))])?;
f
}
// a ZIP holding a folder and a page of the same name
"mintegral" => {
let f = out.join(format!("{name}-mintegral.zip"));
zip(&f, &[(format!("{name}/{name}.html"), html("", ""))])?;
f
}
// one HTML file, everything inlined; MRAID is injected by the network's webview (Meta: data URIs only)
"applovin" | "unity" | "meta" | "moloco" | "liftoff" | "preview" => {
let f = out.join(format!("{name}-{network}.html"));
std::fs::write(&f, html("", "")).map_err(|e| format!("{}: {e}", f.display()))?;
f
}
other => return Err(format!("raea playable: no network {other} (one of {})", NETWORKS.join(", "))),
};
let bytes = std::fs::metadata(&file).map(|m| m.len()).unwrap_or(0);
Ok(Written { network: network.into(), file, bytes })
}
#[cfg(test)]
mod tests {
#[test]
fn a_script_cannot_end_its_page_early() {
let p = super::page("t", "", "", "a('</script>')");
assert_eq!(p.matches("</script").count(), 1, "{p}");
}
#[test]
fn the_preamble_names_the_network_as_a_string() {
assert_eq!(super::preamble("applovin", "{}", "{}"), "var __RAEA_NETWORK__=\"applovin\",__RAEA_STORE__={},__RAEA_PLAYABLE__={};");
}
}
+13 -1
View File
@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "raea scene lint|explain|light|stage: a composition's frames stepped without drawing and held to the contact, light and stage checks"
description = "raea scene lint|explain|faults|light|stage|lod: a composition's frames stepped without drawing and held to the contact, light and stage checks"
[dependencies]
raea-runtime-bundle = { path = "../../runtime/bundle" }
@@ -12,7 +12,19 @@ raea-runtime-export = { path = "../../runtime/export" }
raea-sys-contact = { path = "../../systems/contact" }
raea-sys-light-meter = { path = "../../systems/light-meter" }
raea-sys-stage = { path = "../../systems/stage" }
# raea scene faults: whether a viewer would notice each lint finding, and the judge learning from verdicts
raea-sys-notice = { path = "../../systems/notice" }
# raea scene faults --clip: a character's motion held to what a body does
raea-sys-motionfaults = { path = "../../systems/motionfaults" }
raea-sys-body = { path = "../../systems/body" }
# each part's planned detail beside how large the frames show it (MK21, MK23)
raea-runtime-lod-plan = { path = "../../runtime/lod-plan" }
# its results as Findings (docs/direction.feature DR3)
raea-core-facts = { path = "../../core/facts" }
# camera clearance (MK16): the parts, their models' triangles, and the camera's point in space
raea-core-scene = { path = "../../core/scene" }
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
dunce = "1"
# --ask: the fault ringed on its frame for the vision model
image = { version = "0.25", default-features = false, features = ["png"] }
serde_json = "1"
+109
View File
@@ -0,0 +1,109 @@
//! `raea scene faults EDIT.tsx --composition ID --ask N` (docs/notice.feature NT12): a vision model asked only what
//! geometry can't say, whether a likely fault is meant. The judge has already found it, measured it and found the
//! frame it shows largest on; that frame is rendered, the fault's spots ringed on it, and `raea ask` (clef-omni) is
//! handed the picture with the scene's own words for it: which part, what it's on or in, by how much. Its answer,
//! meant or a mistake, is kept as a verdict (`by: "ask"`) when it's SURE or more, and any person's verdict on the same
//! finding outranks it.
//! The ringed pictures stay in the project's review/faults-ask/ for a person to look at.
use std::path::Path;
use std::process::Command;
use serde_json::Value;
use raea_sys_notice::{FAULT, Judged, labels};
/// Rendered this wide (its height kept to the composition's shape).
const WIDE: u32 = 960;
/// An answer this sure or more is kept as a verdict; under it, said as unsure and kept out of training. On room
/// 106's shot-window (2026-11-27) the model was 0.52-0.65 sure on chair feet pressed into carpet and a leg through a
/// strap, and 0.72-0.78 on a sunk kit, a floating hat and a part sunk into a door.
const SURE: f64 = 0.7;
/// One ring around every spot of the fault on the picture, a little out from them, in red.
fn ring(png: &Path, marks: &[[f32; 2]]) -> Result<(), String> {
let mut img = image::open(png).map_err(|e| format!("{}: {e}", png.display()))?.to_rgb8();
let (w, h) = (img.width() as f32, img.height() as f32);
let pts: Vec<(f32, f32)> = marks.iter().map(|m| ((m[0] + 1.0) * 0.5 * w, (1.0 - m[1]) * 0.5 * h)).collect();
let (cx, cy) = (pts.iter().map(|p| p.0).sum::<f32>() / pts.len() as f32, pts.iter().map(|p| p.1).sum::<f32>() / pts.len() as f32);
let r = pts.iter().map(|p| (p.0 - cx).hypot(p.1 - cy)).fold(0.0f32, f32::max) + 0.03 * w;
for y in 0..img.height() {
for x in 0..img.width() {
let d = (x as f32 - cx).hypot(y as f32 - cy);
if (d - r).abs() <= 2.5 {
img.put_pixel(x, y, image::Rgb([255, 30, 30]));
}
}
}
img.save(png).map_err(|e| format!("{}: {e}", png.display()))
}
fn question(j: &Judged) -> String {
let f = &j.fault;
let what = match &f.into {
Some(into) => format!("{} (against {into})", f.part),
None => f.part.clone(),
};
format!(
"This is a frame of a 3D scene. Inside the red ring is {what}. A geometry check measured: {}. Judge only what is inside the ring. Is it meant to be like this (cloth draped over an edge, something hung, feet pressed into soft carpet, something set into a wall), or a mistake a viewer would notice (something floating, sunk into something, passing through something, faces flickering)?",
f.says
)
}
/// The likeliest `n` faults asked about, their answers kept as verdicts.
#[allow(clippy::too_many_arguments)]
pub fn run(tsx: &Path, shot: &str, judged: &[Judged], frames: &[i64], w: u32, h: u32, n: usize, dry: bool) -> Result<String, String> {
let project = labels::project_of(tsx);
let dir = project.join("review").join("faults-ask");
std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let me = std::env::current_exe().map_err(|e| e.to_string())?;
let tall = ((WIDE as f32 * h as f32 / w as f32 / 2.0).round() as u32 * 2).max(2);
let (mut out, mut rows) = (Vec::new(), Vec::new());
for j in judged.iter().filter(|j| j.p >= FAULT && j.seen.best.is_some() && !j.seen.marks.is_empty()).take(n) {
let frame = frames[j.seen.best.unwrap()];
let name = format!("{shot}-{}", j.fault.key).replace(|c: char| !(c.is_ascii_alphanumeric() || c == '-'), "_");
let (png, mp4) = (dir.join(format!("{name}.png")), dir.join(format!("{name}.mp4")));
// the frame as the render draws it, its own end checks left out (they'd judge the scene again)
let drawn = Command::new(&me)
.args(["render", &tsx.to_string_lossy(), "--composition", shot, "--frame", &frame.to_string(), "--w", &WIDE.to_string(), "--h", &tall.to_string(), "-o", &png.to_string_lossy()])
.env("RAEA_FAULTS_CHECK", "0")
.env("RAEA_CLIP_CHECK", "0")
.output()
.map_err(|e| format!("raea render: {e}"))?;
if !drawn.status.success() {
return Err(format!("raea render frame {frame}: {}", String::from_utf8_lossy(&drawn.stderr).lines().last().unwrap_or("")));
}
ring(&png, &j.seen.marks)?;
// raea ask watches a picture move: the still as a second of video
let made = Command::new("ffmpeg").args(["-y", "-loglevel", "error", "-loop", "1", "-i", &png.to_string_lossy(), "-t", "1", "-r", "10", "-pix_fmt", "yuv420p", &mp4.to_string_lossy()]).status().map_err(|e| format!("ffmpeg: {e}"))?;
if !made.success() {
return Err(format!("ffmpeg couldn't make {}", mp4.display()));
}
let mut cmd = Command::new(&me);
cmd.args(["ask", &mp4.to_string_lossy(), &question(j), "--choose", "meant,mistake", "--brief", "none", "--json"]);
if dry {
cmd.arg("--dry");
}
let asked = cmd.output().map_err(|e| format!("raea ask: {e}"))?;
let text = String::from_utf8_lossy(&asked.stdout);
let first: Value = text.lines().find_map(|l| serde_json::from_str::<Value>(l).ok()).unwrap_or(Value::Null);
let choice = first["choice"].as_str().or_else(|| first["answer"].as_str()).map(str::to_lowercase);
let says = first["says"].as_str().unwrap_or("").to_string();
let sure = first["value"].as_f64().unwrap_or(0.0);
match choice.as_deref() {
Some(c) if (c.contains("mistake") || c.contains("meant")) && sure < SURE => {
out.push(format!("{:.2} {} -> unsure ({says}), not kept (frame {frame}, {})", j.p, j.fault.key, png.display()));
}
Some(c) if c.contains("mistake") || c.contains("meant") => {
let real = c.contains("mistake");
rows.push(labels::row(&j.fault.key, real, "ask", shot, &j.x, &j.toks));
out.push(format!("{:.2} {} -> {}{} (frame {frame}, {})", j.p, j.fault.key, if real { "a mistake" } else { "meant" }, if says.is_empty() { String::new() } else { format!(": {says}") }, png.display()));
}
_ if dry => out.push(format!("{:.2} {} would be asked on frame {frame} ({})", j.p, j.fault.key, png.display())),
_ => out.push(format!("{:.2} {} not answered: {}", j.p, j.fault.key, first["not_asked"].as_str().or(first["problem"].as_str()).unwrap_or(text.lines().next().unwrap_or("")))),
}
}
labels::append(&project, &rows)?;
out.push(format!("{} asked, {} answers kept as verdicts (by ask; a person's verdict outranks them) in {}", out.len(), rows.len(), project.join("review").join("faults.labels.jsonl").display()));
Ok(out.join("\n"))
}
+164
View File
@@ -0,0 +1,164 @@
//! `raea scene faults EDIT.tsx --composition ID --motion`: the composition's characters held to what a body does
//! (raea-sys-motionfaults), read from the scene itself, with no clip written out. raea/character's `<Character>` draws
//! each joint as a marker part named `<name>-<joint>` (its joint.glb) at the joint's place and turn, and every joint's
//! rest frame is the world's, so a joint's turn from rest against its parent is its parent's world turn undone from its
//! own: each frame's pose comes back exactly. The skeleton is the body's skeleton.json beside its joint.glb.
//!
//! And the hands against the scene: each finger bone, the thumb's too, as a segment from its joint toward its tip,
//! tested against every other part's real triangles (raea-sys-notice's BVH). A bone that crosses a surface has gone in
//! at least a finger's half thickness: a thumb through a grip, fingers through a mug's wall. And the other way: while
//! two or more fingertips rest on a surface (the hand holds something), a tip left 3 cm or more off it hasn't closed:
//! the thumb not wrapping round a post.
use std::path::{Path, PathBuf};
use bevy::math::{Quat, Vec3};
use raea_core_scene::Item;
use raea_sys_body::rig::{FINGERS, Pose, Side, Skeleton};
use raea_sys_motionfaults::{Clip, Fault, Hit, grip, stretches};
use serde_json::Value;
/// A distal bone is tested this far toward its tip (its tip is the skin's end, which rests on what it touches).
const ALONG: f32 = 0.85;
fn name(it: &Item) -> Option<&str> {
it.props.get("name").and_then(Value::as_str)
}
/// The characters on a frame: each one's name and the folder its joint.glb is in.
fn characters(its: &[Item]) -> Vec<(String, String)> {
let mut out: Vec<(String, String)> = Vec::new();
for it in its {
let (Some(n), Some(src)) = (name(it), it.props.get("src").and_then(Value::as_str)) else { continue };
if let (Some(body), true) = (n.strip_suffix("-body"), src.ends_with("/body.glb")) {
let folder = src.trim_end_matches("/body.glb").to_string();
if !out.iter().any(|o| o.0 == body) {
out.push((body.to_string(), folder));
}
}
}
out
}
/// The body's skeleton.json, its folder as the scene names it found from the composition's folder up.
fn skeleton(dir: &Path, folder: &str) -> Option<(PathBuf, Skeleton)> {
let rel = folder.trim_start_matches('/');
for up in dir.ancestors().take(4) {
for sub in ["", "media", "assets", "public", "compositions/media"] {
let p = up.join(sub).join(rel).join("skeleton.json");
if let Ok(t) = std::fs::read_to_string(&p) {
return Skeleton::from_json(&t).ok().map(|s| (p, s));
}
}
}
None
}
/// A part's place and turn (its scale taken out).
fn placed(it: &Item) -> (Vec3, Quat) {
let (_, r, t) = it.world.to_scale_rotation_translation();
(t, r)
}
/// One character's frames as a clip, and each frame's joint places in the scene (for the hands against it).
fn clip_of(skel: &Skeleton, who: &str, frames: &[Vec<Item>], fps: f32) -> (Clip, Vec<Vec<Option<(Vec3, Quat)>>>) {
let (mut poses, mut places) = (Vec::new(), Vec::new());
for its in frames {
let at: Vec<Option<(Vec3, Quat)>> = skel.joints.iter().map(|j| its.iter().find(|it| name(it) == Some(&format!("{who}-{}", j.name))).map(placed)).collect();
let mut p: Pose = skel.rest();
for (i, j) in skel.joints.iter().enumerate() {
let Some((pos, rot)) = at[i] else { continue };
match j.parent.and_then(|q| at[q]) {
Some((_, prot)) => p.turns[i] = (prot.inverse() * rot).normalize(),
None if j.parent.is_none() => {
p.turns[i] = rot;
p.root = pos;
}
None => {}
}
}
poses.push(p);
places.push(at);
}
(Clip { skel: skel.clone(), fps, poses, held: None }, places)
}
/// The hands against the scene's other parts, frame by frame: finger bones through a surface (`through`), and tips
/// left off what the hand holds (`grip`), as faults over the stretches they last.
fn hands(skel: &Skeleton, who: &str, frames: &[Vec<Item>], places: &[Vec<Option<(Vec3, Quat)>>], numbers: &[i64]) -> Vec<Fault> {
let mut hits: Vec<Hit> = Vec::new();
let bones: Vec<usize> = Side::BOTH.iter().flat_map(|&s| FINGERS.iter().filter_map(move |f| skel.finger(f, s))).flatten().collect();
let tips: Vec<Vec<usize>> = Side::BOTH.iter().map(|&s| FINGERS.iter().filter_map(|f| skel.finger(f, s).map(|b| b[2])).collect()).collect();
for (k, its) in frames.iter().enumerate() {
// the scene but the character itself (its skin is drawn at its bind pose in the parts, its markers are specks)
let mine = format!("{who}-");
let others: Vec<Item> = its.iter().filter(|it| !name(it).is_some_and(|n| n.starts_with(&mine))).cloned().collect();
// every part: a mesh's place is often in its own vertices, its transform the world's origin (gambit's ladder lab),
// so nothing can be left out by where its transform sits
if bones.iter().all(|&i| places[k][i].is_none()) {
continue;
}
let near: Vec<Item> = others.into_iter().filter(|it| it.kind != "camera").collect();
let scene = raea_sys_notice::Scene::of(&near);
let bone = |i: usize, along: f32| places[k][i].map(|(a, rot)| (a, a + rot * ((skel.joints[i].tail - skel.joints[i].head) * along)));
for &i in &bones {
if let Some((a, b)) = bone(i, ALONG)
&& scene.blocked(a, b, 0.0)
{
hits.push(Hit { check: "through", joint: skel.joints[i].name.clone(), f: k, value: 0.0, unit: "m", what: String::new() });
}
}
for side in &tips {
let off: Vec<(usize, f32)> = side.iter().filter_map(|&i| bone(i, 1.0).map(|(_, tip)| (i, scene.reach(tip, grip::LOOK)))).collect();
for o in grip::open(&off.iter().map(|o| o.1).collect::<Vec<_>>()) {
hits.push(Hit { check: "grip", joint: skel.joints[off[o].0].name.clone(), f: k, value: off[o].1, unit: "m", what: String::new() });
}
}
}
// one fault per check and joint while the frames run on, as a clip's are (motionfaults' stretches)
let mut out = stretches(hits);
for f in &mut out {
(f.from, f.to, f.peak) = (numbers[f.from] as usize, numbers[f.to] as usize, numbers[f.peak] as usize);
f.says = match f.check {
"grip" => format!("{} is {:.0} mm off what the hand holds (it hasn't closed on it), frames {}-{}", f.joint, f.value * 1000.0, f.from, f.to),
_ => format!("{} passes through a part of the scene, frames {}-{}", f.joint, f.from, f.to),
};
}
out
}
/// One character's findings over the composition's frames.
pub struct Found {
pub who: String,
pub skeleton: PathBuf,
pub frames: usize,
pub faults: Vec<Fault>,
}
/// Every character's motion faults over the frames given (their numbers alongside); a character whose skeleton.json
/// can't be found is said in the second list.
pub fn run(dir: &Path, frames: &[(i64, Vec<Item>)], fps: f32) -> Result<(Vec<Found>, Vec<String>), String> {
let Some((_, first)) = frames.first() else { return Err("no frames".into()) };
let found = characters(first);
if found.is_empty() {
return Err("no characters in the composition (a <Character> draws <name>-body and <name>-<joint> parts)".into());
}
let numbers: Vec<i64> = frames.iter().map(|f| f.0).collect();
let items: Vec<Vec<Item>> = frames.iter().map(|f| f.1.clone()).collect();
let (mut out, mut missing) = (Vec::new(), Vec::new());
for (who, folder) in found {
let Some((path, skel)) = skeleton(dir, &folder) else {
missing.push(format!("{who}: no skeleton.json for {folder}, not checked"));
continue;
};
let (clip, places) = clip_of(&skel, &who, &items, fps);
let mut faults = raea_sys_motionfaults::check(&clip);
// the clip's frames are the composition's from its first
for f in &mut faults {
(f.from, f.to, f.peak) = (numbers[f.from] as usize, numbers[f.to.min(numbers.len() - 1)] as usize, numbers[f.peak] as usize);
}
faults.extend(hands(&skel, &who, &items, &places, &numbers));
out.push(Found { who, skeleton: path, frames: clip.poses.len(), faults });
}
Ok((out, missing))
}
+226
View File
@@ -0,0 +1,226 @@
//! Camera clearance (docs/goal.feature MK16, from AnyShot's clearance pass): every frame, how near the camera passes to
//! each solid part, and where it comes closer than a person carrying it could (0.45 m by default). A camera that
//! grazes a door frame or pushes into a desk draws the inside of the part, or a wall filling the frame; the boxes the
//! stage keeps say it without drawing. Only solids count: volumes, decals, footage, 2D, see-through parts (glass) and
//! anything under 5 cm across are passed over. A part's box answers first; a model whose box comes close is measured
//! on its triangles (a room model round the camera, a tree's box that's mostly air).
use std::collections::HashMap;
use bevy::math::{Mat4, Vec3};
use raea_core_facts::{Finding, Level};
use raea_core_scene::Item;
use serde_json::Value;
use raea_sys_stage::{View, called, model_box, own_box};
/// Parts smaller than this across (metres) are passed over: a pen the camera brushes isn't a collision.
const SMALL: f32 = 0.05;
/// Clearance the shot language asks of a carried camera, metres.
pub const DEFAULT: f32 = 0.45;
fn see_through(it: &Item) -> bool {
let props = it.material.as_ref().map(|m| &m.props);
let n = |k: &str| props.and_then(|p| p.get(k)).or(it.props.get(k)).and_then(Value::as_f64);
n("specular_transmission").or(n("transmission")).is_some_and(|t| t > 0.3) || n("opacity").is_some_and(|o| o < 0.5)
}
/// The nearest distance from `p` (world) to a box [lo, hi] in a part's own space under `world`, in world metres.
pub fn to_box(world: &Mat4, lo: Vec3, hi: Vec3, p: Vec3) -> f32 {
let local = world.inverse().transform_point3(p);
let near = local.clamp(lo, hi);
world.transform_point3(near).distance(p)
}
/// The nearest distance from `p` to a triangle.
pub fn to_tri(p: Vec3, t: &[Vec3; 3]) -> f32 {
let (a, b, c) = (t[0], t[1], t[2]);
let (ab, ac, ap) = (b - a, c - a, p - a);
let (d1, d2) = (ab.dot(ap), ac.dot(ap));
if d1 <= 0.0 && d2 <= 0.0 {
return p.distance(a);
}
let bp = p - b;
let (d3, d4) = (ab.dot(bp), ac.dot(bp));
if d3 >= 0.0 && d4 <= d3 {
return p.distance(b);
}
let vc = d1 * d4 - d3 * d2;
if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 {
return p.distance(a + ab * (d1 / (d1 - d3)));
}
let cp = p - c;
let (d5, d6) = (ab.dot(cp), ac.dot(cp));
if d6 >= 0.0 && d5 <= d6 {
return p.distance(c);
}
let vb = d5 * d2 - d1 * d6;
if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 {
return p.distance(a + ac * (d2 / (d2 - d6)));
}
let va = d3 * d6 - d5 * d4;
if va <= 0.0 && (d4 - d3) >= 0.0 && (d5 - d6) >= 0.0 {
return p.distance(b + (c - b) * ((d4 - d3) / ((d4 - d3) + (d5 - d6))));
}
let denom = 1.0 / (va + vb + vc);
p.distance(a + ab * (vb * denom) + ac * (vc * denom))
}
/// A frame's nearest solid parts to its camera: (part, distance) for each closer than `min`.
pub fn near_parts(its: &[Item], eye: Vec3, min: f32, boxes: &mut HashMap<String, Option<(Vec3, Vec3)>>, tris: &mut HashMap<String, Option<Vec<[Vec3; 3]>>>) -> Vec<(String, f32)> {
let mut out = Vec::new();
for it in its {
if !matches!(it.kind, "mesh" | "model") || it.at.is_some() || see_through(it) {
continue;
}
let bx = if it.kind == "mesh" { own_box(it, boxes) } else { model_box(it, boxes) };
let Some((lo, hi)) = bx else { continue };
let ext = (hi - lo) * it.world.to_scale_rotation_translation().0.abs();
if ext.max_element() < SMALL {
continue;
}
let mut d = to_box(&it.world, lo, hi, eye);
if d >= min {
continue;
}
if it.kind == "model" {
let Some(src) = it.props.get("src").and_then(Value::as_str).map(raea_core_scene::src_path) else { continue };
let t = tris.entry(src.clone()).or_insert_with(|| raea_core_scene::gltf_tris(&src).ok().map(|(g, _)| g.into_iter().flat_map(|(_, t)| t).collect()));
if let Some(t) = t {
let local = it.world.inverse().transform_point3(eye);
// nearest in the model's own space, then measured in the world's (a scaled model's metres)
if let Some(best) = t.iter().min_by(|a, b| to_tri(local, a).total_cmp(&to_tri(local, b))) {
let near = nearest_on(local, best);
d = it.world.transform_point3(near).distance(eye);
}
}
}
if d < min {
out.push((called(it), d));
}
}
out
}
/// The point on a triangle nearest `p` (by projecting and clamping through `to_tri`'s regions, sampled finely enough
/// to measure a clearance to the millimetre).
fn nearest_on(p: Vec3, t: &[Vec3; 3]) -> Vec3 {
let (a, b, c) = (t[0], t[1], t[2]);
let n = (b - a).cross(c - a);
let l2 = n.length_squared();
if l2 > 1e-14 {
let q = p - n * ((p - a).dot(n) / l2);
// barycentric: inside, the projection is the nearest point
let (v0, v1, v2) = (b - a, c - a, q - a);
let (d00, d01, d11, d20, d21) = (v0.dot(v0), v0.dot(v1), v1.dot(v1), v2.dot(v0), v2.dot(v1));
let den = d00 * d11 - d01 * d01;
if den.abs() > 1e-14 {
let v = (d11 * d20 - d01 * d21) / den;
let w = (d00 * d21 - d01 * d20) / den;
if v >= 0.0 && w >= 0.0 && v + w <= 1.0 {
return q;
}
}
}
// outside: the nearest point of the three edges
let seg = |x: Vec3, y: Vec3| {
let d = y - x;
x + d * ((p - x).dot(d) / d.length_squared().max(1e-14)).clamp(0.0, 1.0)
};
[seg(a, b), seg(b, c), seg(c, a)].into_iter().min_by(|u, v| u.distance(p).total_cmp(&v.distance(p))).unwrap_or(a)
}
/// Every frame's camera held `min` metres off every solid part: a finding for each part and run of frames it comes
/// closer, with the nearest it gets.
pub fn clearance(all: &[Vec<Item>], frames: &[i64], w: u32, h: u32, fps: f64, min: f32, by: &str) -> Vec<Finding> {
let (mut boxes, mut tris) = (HashMap::new(), HashMap::new());
// part -> runs of (first frame index, last, nearest)
let mut runs: Vec<(String, usize, usize, f32)> = Vec::new();
let mut open: HashMap<String, usize> = HashMap::new();
for (k, its) in all.iter().enumerate() {
let Some(v) = View::of(its, w, h) else { continue };
let near = near_parts(its, v.eye, min, &mut boxes, &mut tris);
let names: Vec<&String> = near.iter().map(|n| &n.0).collect();
open.retain(|name, _| names.contains(&name));
for (name, d) in near {
match open.get(&name).copied() {
Some(r) if runs[r].2 + 1 == k && frames[k] == frames[runs[r].2] + 1 => {
runs[r].2 = k;
runs[r].3 = runs[r].3.min(d);
}
_ => {
runs.push((name.clone(), k, k, d));
open.insert(name, runs.len() - 1);
}
}
}
}
runs.into_iter()
.map(|(name, a, b, d)| {
let (fa, fb) = (frames[a], frames[b]);
let when = if a == b { format!("at frame {fa} ({:.2} s)", fa as f64 / fps) } else { format!("over frames {fa}-{fb} ({:.2}-{:.2} s)", fa as f64 / fps, fb as f64 / fps) };
let says = if d < 1e-3 {
format!("the camera is inside `{name}` {when}: move the path out of it, or the part")
} else {
format!("the camera passes {d:.2} m from `{name}` {when}, under the {min:.2} m a carried camera keeps: move the path or the part, or pass a smaller --clearance for a camera on a rig")
};
Finding::new("camera-clearance", Level::Error, says, by).frames(fa, fb + 1)
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::{Value, json};
use std::sync::Arc;
fn item(kind: &'static str, props: Value, world: Mat4) -> Item {
Item { kind, props: Arc::new(props.as_object().cloned().unwrap_or_default()), shape: None, at: None, material: None, world }
}
/// A camera at `eye` looking at `at`, 50 degrees.
fn cam(eye: [f32; 3], at: [f32; 3]) -> Item {
item("camera", json!({"position": eye, "lookAt": at, "fov": 50}), Mat4::IDENTITY)
}
#[test]
fn distances_to_a_box_and_a_triangle() {
let w = Mat4::from_translation(Vec3::new(0.0, 0.5, 0.0));
let (lo, hi) = (Vec3::splat(-0.5), Vec3::splat(0.5));
assert!((to_box(&w, lo, hi, Vec3::new(0.0, 0.5, 1.5)) - 1.0).abs() < 1e-5);
assert_eq!(to_box(&w, lo, hi, Vec3::new(0.0, 0.5, 0.0)), 0.0);
let t = [Vec3::ZERO, Vec3::X, Vec3::Z];
assert!((to_tri(Vec3::new(0.25, 0.3, 0.25), &t) - 0.3).abs() < 1e-5);
assert!((to_tri(Vec3::new(-1.0, 0.0, 0.0), &t) - 1.0).abs() < 1e-5);
assert!((nearest_on(Vec3::new(0.25, 0.3, 0.25), &t) - Vec3::new(0.25, 0.0, 0.25)).length() < 1e-5);
}
fn solid(name: &str, size: [f32; 3], at: [f32; 3]) -> Item {
let mut it = item("mesh", json!({"name": name}), Mat4::from_translation(Vec3::from(at)));
it.shape = Some(format!("box({}, {}, {})", size[0], size[1], size[2]).into());
it
}
#[test]
fn a_camera_pushing_into_a_desk_is_found_and_a_small_or_glass_part_is_not() {
// a desk 1.6 x 0.75 x 0.8 m standing at the origin; the camera pushes in from 2 m to 0.1 m off its front face
let desk = solid("desk", [1.6, 0.75, 0.8], [0.0, 0.375, 0.0]);
let pen = solid("pen", [0.04, 0.01, 0.01], [0.0, 1.0, 0.45]);
let mut glass = solid("pane", [1.0, 1.0, 0.01], [0.0, 1.0, 0.3]);
glass.props = Arc::new(json!({"name": "pane", "specular_transmission": 0.9}).as_object().cloned().unwrap());
let zs = [2.4, 1.6, 1.0, 0.7, 0.5, 2.4];
let all: Vec<Vec<Item>> = zs.iter().map(|z| vec![cam([0.0, 0.6, *z], [0.0, 0.4, 0.0]), desk.clone(), pen.clone(), glass.clone()]).collect();
let frames: Vec<i64> = (0..zs.len() as i64).collect();
let f = clearance(&all, &frames, 640, 360, 30.0, DEFAULT, "t");
// the desk's face is at z 0.4: frames 3 and 4 come within 0.3 and 0.1 m; one run, its nearest said
assert_eq!(f.len(), 1, "{f:?}");
assert!(f[0].says.contains("0.10 m from `desk` over frames 3-4"), "{}", f[0].says);
assert_eq!(f[0].level, Level::Error);
// a rig's camera may come closer
assert!(clearance(&all, &frames, 640, 360, 30.0, 0.05, "t").is_empty());
// inside it, said so
let inside = vec![vec![cam([0.0, 0.3, 0.0], [0.0, 0.3, -1.0]), desk.clone()]];
assert!(clearance(&inside, &[0], 640, 360, 30.0, DEFAULT, "t")[0].says.contains("inside `desk`"));
}
}
+172
View File
@@ -0,0 +1,172 @@
//! `raea scene faults EDIT.tsx`: the lint's findings judged as a viewer of the shot would see them (raea-sys-notice):
//! every frame's camera asked where each one shows and how large, a small model saying how likely it is to read as a
//! fault, the likeliest first. Hidden ones (walls meeting the ceiling inside the slab) are counted, not listed.
//!
//! It learns: `--real KEY` and `--fine KEY` keep a verdict on a finding beside the project (review/
//! faults.labels.jsonl), and a finding the last run said that's gone while both its parts remain is kept as fixed,
//! so real. `raea scene faults train [FOLDER]` fits the model to every project's verdicts under FOLDER.
use serde_json::{Value, json};
use raea_runtime_bundle::{bundle_composition, comp_opts};
use raea_runtime_export::{frame_of, items};
use raea_sys_notice::{FAULT, Judged, Model, labels};
/// The most frames whose cameras are asked (evenly over the shot).
const CAMERAS: usize = 48;
pub fn cli(args: &[String]) -> Result<String, String> {
let Some(edit) = args.get(2) else { return Err(crate::USAGE.into()) };
if edit == "train" {
return train(args.get(3).map(String::as_str));
}
if edit == "--clip" {
return crate::motion::cli(args);
}
let tsx = dunce::canonicalize(std::path::PathBuf::from(edit)).map_err(|e| format!("{edit}: {e}"))?;
let dir = tsx.parent().unwrap().to_path_buf();
let frame = frame_of(args)?;
let opts = comp_opts(args)?;
let shot = opts.composition.clone().unwrap_or_default();
let js = std::env::temp_dir().join(format!("raea-faults-{}.js", std::process::id()));
bundle_composition(&tsx, &js, &opts, None)?;
let got = raea_runtime_export::scene_frames(&js, &dir, 0, true, &[]);
let _ = std::fs::remove_file(&js);
let (frames, w, h, fps) = got?.ok_or("the composition has no 3D")?;
// the composition's characters held to what a body does, read from the scene (chars.rs)
if args.iter().any(|a| a == "--motion") {
let all: Vec<(i64, Vec<raea_core_scene::Item>)> = frames.iter().map(|fr| (fr.0, items(&fr.1))).collect();
let (text, v, n) = crate::motion::composition(&tsx, &shot, &dir, &all, fps as f32, args)?;
return finish(if args.iter().any(|a| a == "--json") { serde_json::to_string_pretty(&v).unwrap_or_default() } else { text }, n);
}
let k = frames.iter().position(|(f, _)| *f == frame).ok_or_else(|| format!("no frame {frame}"))?;
let other = if k + 1 < frames.len() { k + 1 } else { k.saturating_sub(1) };
let (now, next) = (items(&frames[k].1), items(&frames[other].1));
let (found, _) = raea_sys_contact::lint(&now, &next);
// the cameras: the frame's own and evenly over the rest of the shot
let step = frames.len().div_ceil(CAMERAS).max(1);
// and each view's frame number, for the frame a fault shows largest on (--ask)
let (mut views, mut view_frames) = (vec![now.clone()], vec![frame]);
for (i, (f, fr)) in frames.iter().enumerate() {
if i != k && i % step == 0 {
views.push(items(fr));
view_frames.push(*f);
}
}
let model = Model::load();
let judged = raea_sys_notice::judge(&found, &views, w, h, &model);
// faults of known size planted and judged: the judge measured, nothing kept (seed.rs)
if let Some(n) = raea_runtime_bundle::flag(args, "--seed") {
let n = n.parse::<usize>().map_err(|_| "--seed takes how many faults to plant")?;
return Ok(crate::seed::run(&now, &next, &views, &found, w, h, &model, n));
}
// a vision model asked whether the likeliest faults are meant (ask.rs), its answers kept as verdicts
if let Some(n) = raea_runtime_bundle::flag(args, "--ask") {
let n = n.parse::<usize>().map_err(|_| "--ask takes how many of the likeliest faults to ask about")?;
return crate::ask::run(&tsx, &shot, &judged, &view_frames, w, h, n, args.iter().any(|a| a == "--dry"));
}
// what it learns from: this run against the last, and any verdict given now
let project = labels::project_of(&tsx);
let keys: Vec<String> = judged.iter().map(|j| j.fault.key.clone()).collect();
let parts: Vec<String> = found.iter().flat_map(|v| ["part", "on", "into"].into_iter().filter_map(move |n| v[n].as_str())).map(String::from).collect();
let mut rows = labels::fixed(&labels::last(&project, &shot), &keys, &parts);
let fixed = rows.len();
for (name, real) in [("--real", true), ("--fine", false)] {
for key in raea_runtime_bundle::flags(args, name) {
let j = judged.iter().find(|j| j.fault.key == key).ok_or_else(|| format!("{name} {key}: no finding by that key on this shot (keys are listed with --json, or after each line)"))?;
rows.push(labels::row(&key, real, "marked", &shot, &j.x, &j.toks));
}
}
labels::append(&project, &rows)?;
let last: Vec<Value> = judged.iter().map(|j| json!({"key": j.fault.key, "part": j.fault.part, "into": j.fault.into, "x": j.x, "toks": j.toks, "shot": shot})).collect();
labels::keep_last(&project, &shot, last)?;
let faults: Vec<&Judged> = judged.iter().filter(|j| j.p >= FAULT).collect();
let hidden = judged.iter().filter(|j| j.seen.shown == 0).count();
if args.iter().any(|a| a == "--json") {
let rows: Vec<Value> = judged
.iter()
.map(|j| json!({"key": j.fault.key, "check": j.fault.check, "part": j.fault.part, "into": j.fault.into, "p": (j.p * 1e3).round() / 1e3, "fault": j.p >= FAULT,
"seen": {"frames": j.seen.frames, "shown": j.seen.shown, "px": (j.seen.px * 10.0).round() / 10.0, "near": (j.seen.near * 1e3).round() / 1e3}, "says": j.fault.says}))
.collect();
let text = serde_json::to_string_pretty(&json!({"frame": frame, "model": model.from, "labels": model.labels, "findings": rows, "faults": faults.len(), "hidden": hidden, "fixed": fixed})).unwrap_or_default();
return finish(text, faults.len());
}
let mut out: Vec<String> = Vec::new();
for j in &judged {
if j.seen.shown == 0 && j.p < FAULT {
continue;
}
let tag = if j.p >= FAULT { "FAULT" } else { "maybe" };
out.push(format!("{:.2} {tag} {} (seen on {}/{} frames, {:.1} px, {:.2} m off) key: {}", j.p, j.fault.says, j.seen.shown, j.seen.frames, j.seen.px, j.seen.near, j.fault.key));
}
out.push(format!(
"frame {frame}: {} findings, {} likely faults, {} seen but likely fine, {hidden} no camera sees; judged by {} ({} labels){}",
judged.len(),
faults.len(),
judged.len() - faults.len() - judged.iter().filter(|j| j.seen.shown == 0 && j.p < FAULT).count(),
model.from,
model.labels,
if fixed > 0 { format!("; {fixed} fixed since the last run, kept as real") } else { String::new() }
));
finish(out.join("\n"), faults.len())
}
/// Faults fail it, as the lint's errors do.
fn finish(text: String, faults: usize) -> Result<String, String> {
if faults > 0 {
println!("{text}");
std::process::exit(1);
}
Ok(text)
}
/// `raea scene faults train [FOLDER]`: every project's verdicts under FOLDER (default: here) fitted, the model kept in
/// raea's models folder for every run after.
fn train(root: Option<&str>) -> Result<String, String> {
let root = std::path::PathBuf::from(root.unwrap_or("."));
let files = labels::files(&root, 4);
let ex: Vec<_> = files.iter().flat_map(|f| labels::examples(f)).collect();
if ex.is_empty() {
return Err(format!("no verdicts under {} (review/faults.labels.jsonl: --real KEY, --fine KEY, and fixes)", root.display()));
}
let m = Model::fit(&ex);
let right = ex.iter().filter(|(x, t, y)| (m.score(x, t) >= FAULT) == (*y >= 0.5)).count();
let before = ex.iter().filter(|(x, t, y)| (Model::prior().score(x, t) >= FAULT) == (*y >= 0.5)).count();
let p = raea_sys_notice::model::path();
std::fs::create_dir_all(p.parent().unwrap()).map_err(|e| e.to_string())?;
std::fs::write(&p, serde_json::to_string_pretty(&m.to_json()).unwrap_or_default()).map_err(|e| format!("{}: {e}", p.display()))?;
let real = ex.iter().filter(|e| e.2 >= 0.5).count();
// held out: each finding (one finding judged on two shots shares its words) fitted without, then asked
let (held, finds) = held_out(&ex.iter().map(|e| (e.1.clone(), e.0.clone(), e.1.clone(), e.2)).collect::<Vec<_>>());
// and a shot at a time (each project's own shot names, so a shot is a project's view): a scene it has never seen
let by_shot: Vec<_> = files.iter().enumerate().flat_map(|(n, f)| labels::shots(f).into_iter().map(move |(s, x, t, y)| (format!("{n}/{s}"), x, t, y))).collect();
let (unseen, names) = held_out(&by_shot);
Ok(format!(
"{} verdicts on {} findings from {} projects ({real} real, {} fine): the prior agreed with {before}, the fitted judge with {right}, with {held} each fitted without its own finding (held out), and with {unseen} each fitted without its whole shot ({} shots, a scene it hasn't seen); kept in {}\n{}",
ex.len(),
finds,
files.len(),
ex.len() - real,
names,
p.display(),
crate::motion::train()?
))
}
/// Verdicts a judge gets right fitted without their own group (a finding's words, a shot): each group left out in
/// turn, fitted on the rest, then asked. With how many groups there were.
fn held_out<K: Ord>(rows: &[(K, Vec<f32>, Vec<String>, f32)]) -> (usize, usize) {
let mut groups: Vec<&K> = rows.iter().map(|r| &r.0).collect();
groups.sort();
groups.dedup();
let (mut right, n) = (0, groups.len());
for g in groups {
let rest: Vec<_> = rows.iter().filter(|r| &r.0 != g).map(|r| (r.1.clone(), r.2.clone(), r.3)).collect();
let m = Model::fit(&rest);
right += rows.iter().filter(|r| &r.0 == g && (m.score(&r.1, &r.2) >= FAULT) == (r.3 >= 0.5)).count();
}
(right, n)
}
+17 -3
View File
@@ -1,16 +1,28 @@
//! `raea scene lint|explain|light|stage`: a composition's frames stepped without drawing and handed to raea-sys-contact
//! `raea scene lint|explain|light|stage|lod`: a composition's frames stepped without drawing and handed to raea-sys-contact
//! (what each part rests on, and parts that clip), raea-sys-light-meter (the light on a subject) and raea-sys-stage (3D
//! type that can't be read, parts that snap, a camera that lurches, empty frames: docs/stage-guards.feature).
//! type that can't be read, parts that snap, a camera that lurches, empty frames: docs/stage-guards.feature). `lod` is
//! each part's planned detail beside how large the frames show it (docs/goal.feature MK23).
use serde_json::json;
use raea_runtime_bundle::{bundle_composition, comp_opts};
use raea_runtime_export::{frame_of, items};
// how near the camera passes to each solid part, every frame (`--clearance M`, MK16)
pub mod clearance;
// the lint's findings judged as a viewer of the shot would see them, learning from verdicts (raea-sys-notice)
mod ask;
mod chars;
mod faults;
mod motion;
// faults of known size planted, to measure the judge (`faults --seed N`)
mod seed;
mod light;
// each part's planned detail beside how large the frames show it (MK23)
pub mod lod;
mod stage;
pub const USAGE: &str = "raea scene lint|explain|light|stage EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--json]";
pub const USAGE: &str = "raea scene lint|explain|faults|light|stage|lod EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--real KEY] [--fine KEY] [--seed N] [--ask N [--dry]] [--motion] [--json] | raea scene faults train [FOLDER] | raea scene faults --clip CLIP.json|FOLDER [--real KEY] [--fine KEY] [--fine-from N] [--fine-upto N] [--real-from N] [--real-upto N] [--by NAME] [--seed N] [--json]";
/// `raea scene lint|explain EDIT.tsx [--composition ID] [--frame N] [--json]`: the frame's parts measured
/// (frame 0 by default). `lint` says the faults (errors fail it: floating, sunk, clipping; warnings: in the air,
@@ -22,6 +34,8 @@ pub fn cli(args: &[String]) -> Result<String, String> {
match mode {
"light" => return light::cli(args),
"stage" => return stage::cli(args),
"lod" => return lod::cli(args),
"faults" => return faults::cli(args),
"lint" | "explain" => {}
_ => return Err(usage.into()),
}
+37
View File
@@ -0,0 +1,37 @@
//! `raea scene lod EDIT.tsx [--composition ID] [--from N] [--to N] [--json]` (docs/goal.feature MK23): every part's
//! planned detail beside how large the frames show it. A part's plan is its own `lod` (0 the hero to 4 far), else its
//! name's on the job's plan (`lod` on brief.ts's make objects); what a frame shows is how much of it the part's box
//! spans (raea-runtime-lod-plan). The table lists the planned parts first, the ones seen closer than planned on top,
//! then the parts nobody planned by how large they get, so a part forgotten since the plan was written is found by
//! reading down it. A part seen two or more levels finer than planned fails it, as it fails a render.
use raea_core_facts::{Finding, Level, finding};
use raea_runtime_lod_plan::{ordered, table};
use serde_json::json;
pub(crate) fn cli(args: &[String]) -> Result<String, String> {
let crate::stage::Stepped { items, nums, size: (w, h, fps), dir } = crate::stage::stepped(args, "raea scene lod EDIT.tsx [--composition ID] [--from N] [--to N] [--json]")?;
let (first, last) = (nums[0], nums[nums.len() - 1]);
let plan = raea_runtime_lod_plan::plan::lods(&dir);
let mut unseen: Vec<String> = plan.keys().cloned().collect();
let (seen, fs) = raea_runtime_lod_plan::lods(&items, &nums, w, h, fps, "raea scene lod", plan);
let seen = ordered(seen);
// a level the plan gives a name no part in these frames goes by holds nothing: said, so the part gets its name
unseen.retain(|n| !seen.iter().any(|s| s.planned.is_some() && (s.name == *n || s.name.starts_with(&format!("{n} (lod ")))));
unseen.sort();
let text = if args.iter().any(|a| a == "--json") {
let parts: Vec<_> = seen.iter().map(|s| json!({"part": s.name, "planned": s.planned, "seen": s.level(), "largest": s.finest.map(|f| f.1), "at": s.finest.map(|f| f.0), "frames": s.frames, "closer": s.closer})).collect();
serde_json::to_string_pretty(&json!({"frames": [first, last], "parts": parts, "unseen": unseen, "findings": fs})).unwrap_or_default()
} else {
let levels = "levels, by how much of the frame a part spans: 0 hero 50%+, 1 featured 20%+, 2 dressing 8%+, 3 background 2%+, 4 far";
let none = seen.iter().filter(|s| s.planned.is_none()).count();
let missing = (!unseen.is_empty()).then(|| format!("planned in brief.ts, but no part of that name is in these frames (name the part as its object's id, or its plan holds nothing): {}", unseen.join(", ")));
let sum = format!("frames {first} to {last}: {} parts, {none} with no plan; {}", seen.len(), finding::count(&fs));
table(&seen).into_iter().chain(fs.iter().map(Finding::line)).chain(missing).chain([levels.to_string(), sum]).collect::<Vec<_>>().join("\n")
};
if fs.iter().any(|f| f.level == Level::Error) {
println!("{text}");
std::process::exit(1);
}
Ok(text)
}
+245
View File
@@ -0,0 +1,245 @@
//! `raea scene faults --clip CLIP.json|FOLDER [--clip ...]`: a character's motion held to what a body does, frame by frame
//! (raea-sys-motionfaults): knees that buckle while the foot stands, feet that skate, joints past their range, fingers
//! twisted or bent back, jolts, and fingers through what the hand holds. A clip is the skeleton's `joints` (and its
//! `surface`, for the palm), `fps`, and `frames` of `{ root, turns }` (with `thing` for what the hand holds).
//!
//! It learns: `--fine KEY` and `--real KEY` on a clip's finding (each line ends with its key: check and joint role)
//! move that key's line for every run after (raea-sys-motionfaults' verdicts, kept beside the scene judge's model).
use raea_sys_motionfaults::critic;
use serde_json::{Value, json};
pub fn cli(args: &[String]) -> Result<String, String> {
// each --clip a clip's JSON, or a folder of them
let mut files: Vec<String> = Vec::new();
for given in args.windows(2).filter(|w| w[0] == "--clip").map(|w| &w[1]) {
match std::fs::read_dir(given) {
Ok(dir) => {
let mut v: Vec<String> = dir.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "json")).map(|p| p.to_string_lossy().into()).collect();
v.sort();
files.extend(v);
}
Err(_) => files.push(given.clone()),
}
}
if let Some(n) = args.windows(2).find(|w| w[0] == "--seed").map(|w| &w[1]) {
let n = n.parse::<usize>().map_err(|_| "--seed takes how many faults of each kind to plant in each clip")?;
return seed(&files, n);
}
let as_json = args.iter().any(|a| a == "--json");
let (mut text, mut out, mut faults) = (String::new(), Vec::new(), 0);
let store = verdicts_path();
let mut verdicts = raea_sys_motionfaults::verdicts::Verdicts::load(&store);
let (cpath, epath) = critic::paths(&store);
let judge = critic::Critic::load(&cpath);
let mut examples = Vec::new();
let (mut given, mut held) = (0usize, 0usize);
for file in &files {
let v: Value = serde_json::from_str(&std::fs::read_to_string(file).map_err(|e| format!("{file}: {e}"))?).map_err(|e| format!("{file}: {e}"))?;
let clip = raea_sys_motionfaults::clip_of(&v).map_err(|e| format!("{file}: {e}"))?;
let mut found = raea_sys_motionfaults::check(&clip);
// verdicts given now, on this clip's findings by key, then every verdict's lines applied
for (flag, real) in [("--real", true), ("--fine", false)] {
for k in args.windows(2).filter(|w| w[0] == flag).map(|w| &w[1]) {
let hit: Vec<_> = found.iter().filter(|f| raea_sys_motionfaults::verdicts::key(f) == *k).collect();
if hit.is_empty() {
return Err(format!("{file}: no finding has the key {k} (each line ends with its key)"));
}
let (from, upto) = sizes(args, real);
for f in hit {
if f.value < from || f.value > upto {
continue;
}
verdicts.give(f, real);
examples.push(critic::row(f, real, by(args)));
given += 1;
}
}
}
let before = found.len();
found.retain(|f| stands(f, &verdicts, &judge));
held += before - found.len();
faults += found.len();
let name = std::path::Path::new(file).file_stem().map_or(file.to_string(), |s| s.to_string_lossy().into());
text += &format!("{name}: {} frames, {} fault{}\n", clip.poses.len(), found.len(), if found.len() == 1 { "" } else { "s" });
for f in &found {
text += &format!(" {:<8} {} key: {}\n", f.check, f.says, raea_sys_motionfaults::verdicts::key(f));
}
out.push(json!({"clip": file, "frames": clip.poses.len(), "faults": found.iter().map(|f| f.to_json()).collect::<Vec<_>>()}));
}
if out.is_empty() {
return Err("--clip takes a clip's JSON (joints, fps, frames of root and turns)".into());
}
if given > 0 {
if let Some(dir) = store.parent() {
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
}
std::fs::write(&store, serde_json::to_string_pretty(&verdicts.to_json()).unwrap()).map_err(|e| format!("{}: {e}", store.display()))?;
critic::append(&epath, &examples)?;
text += &format!("{given} verdict{} kept in {}\n", if given == 1 { "" } else { "s" }, store.display());
}
if held > 0 {
text += &format!("{held} finding{} held back by earlier verdicts (fine at that size)\n", if held == 1 { " is" } else { "s are" });
}
if as_json {
return Ok(serde_json::to_string_pretty(&json!({"clips": out, "faults": faults, "held": held})).unwrap());
}
if faults > 0 {
eprint!("{text}");
return Err(format!("{faults} motion fault{} in {} clip{}", if faults == 1 { "" } else { "s" }, out.len(), if out.len() == 1 { "" } else { "s" }));
}
Ok(text)
}
/// Faults of each kind planted in every clip (raea-sys-motionfaults' plant), and how many `check` finds: one that is
/// new against the clip's own faults, of its kind, on its joint (any joint for a grip), over its frame.
fn seed(files: &[String], n: usize) -> Result<String, String> {
use raea_sys_motionfaults::plant::{KINDS, Rng, plant};
use std::collections::BTreeMap;
let mut tally: BTreeMap<&str, (usize, usize, Vec<f32>, Vec<f32>)> = BTreeMap::new();
let mut text = String::new();
for (k, file) in files.iter().enumerate() {
let v: Value = serde_json::from_str(&std::fs::read_to_string(file).map_err(|e| format!("{file}: {e}"))?).map_err(|e| format!("{file}: {e}"))?;
let clip = raea_sys_motionfaults::clip_of(&v).map_err(|e| format!("{file}: {e}"))?;
let own = raea_sys_motionfaults::check(&clip);
let mut rng = Rng(0x9e37_79b9_7f4a_7c15 ^ (k as u64 + 1) * 0x1000_0001);
for kind in KINDS {
for _ in 0..n {
let Some((moved, p)) = plant(&clip, kind, &mut rng) else { continue };
let near = |f: &raea_sys_motionfaults::Fault| f.check == p.check && (p.check == "through" || p.check == "skate" || f.joint == p.joint) && f.from <= p.frame + 2 && p.frame <= f.to + 2;
let found = raea_sys_motionfaults::check(&moved);
let caught = found.iter().any(|f| near(f) && !own.iter().any(|o| o.check == f.check && o.joint == f.joint && o.from <= f.to && f.from <= o.to));
let t = tally.entry(p.check).or_default();
t.0 += 1;
if caught {
t.1 += 1;
t.2.push(p.size);
} else {
t.3.push(p.size);
let name = std::path::Path::new(file).file_stem().map_or(String::new(), |s| s.to_string_lossy().into());
text += &format!(" missed in {name}: {}\n", p.says);
}
}
}
}
let mut out = format!("planted in {} clips:\n", files.len());
for (kind, (planted, caught, got, missed)) in &tally {
out += &format!(" {kind:<8} {caught}/{planted} caught{}{}\n", if got.is_empty() { String::new() } else { format!(", smallest caught {:.3}", raea_sys_motionfaults::bounds(got).0) }, if missed.is_empty() { String::new() } else { format!(", smallest missed {:.3}", raea_sys_motionfaults::bounds(missed).0) });
}
Ok(out + text.as_str())
}
/// Where the motion verdicts are kept: beside the scene judge's model (notice/motion.json), or RAEA_NOTICE_MOTION.
/// `raea scene faults EDIT.tsx --composition ID --motion`: the composition's characters (chars.rs) held to the motion
/// checks, verdicts given (`--real`/`--fine KEY`) and applied as `--clip`'s are. And what a change shows: each run's
/// findings are kept (review/motion.last/<shot>.json), and one the last run reported that's gone now, the character
/// and its frames the same, was fixed, so it's kept as a real verdict at its size (raea-sys-motionfaults `fixed`).
pub fn composition(tsx: &std::path::Path, shot: &str, dir: &std::path::Path, frames: &[(i64, Vec<raea_core_scene::Item>)], fps: f32, args: &[String]) -> Result<(String, Value, usize), String> {
use raea_sys_motionfaults::verdicts::{fixed, key, record};
let (found, missing) = crate::chars::run(dir, frames, fps)?;
let store = verdicts_path();
let mut verdicts = raea_sys_motionfaults::verdicts::Verdicts::load(&store);
let (cpath, epath) = critic::paths(&store);
let judge = critic::Critic::load(&cpath);
let mut examples = Vec::new();
let lastp = raea_sys_notice::labels::project_of(tsx).join("review").join("motion.last").join(format!("{shot}.json"));
let last: Value = std::fs::read_to_string(&lastp).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(Value::Null);
let (mut text, mut rows, mut total, mut given, mut fixes, mut held) = (missing.join("\n"), Vec::new(), 0, 0, 0, 0);
let mut keep = serde_json::Map::new();
for c in &found {
for (flag, real) in [("--real", true), ("--fine", false)] {
for k in args.windows(2).filter(|w| w[0] == flag).map(|w| &w[1]) {
let (from, upto) = sizes(args, real);
for f in c.faults.iter().filter(|f| key(f) == *k && f.value >= from && f.value <= upto) {
verdicts.give(f, real);
examples.push(critic::row(f, real, by(args)));
given += 1;
}
}
}
let mut lines = String::new();
let was = &last["characters"][&c.who];
if was["frames"].as_u64() == Some(c.frames as u64) && last["checks"] == raea_sys_motionfaults::CHECKS {
for (k, v, n) in fixed(was["faults"].as_array().map(Vec::as_slice).unwrap_or(&[]), &c.faults) {
verdicts.give_at(&k, v, true);
let (check, joint) = k.split_once(':').unwrap_or((&k, ""));
examples.push(critic::row_of(check, joint, v, n, true, "fixed"));
fixes += 1;
lines += &format!(" fixed {k} at {v:.3}: gone since the last run, kept as real\n");
}
}
keep.insert(c.who.clone(), json!({"frames": c.frames, "faults": c.faults.iter().map(record).collect::<Vec<_>>()}));
let mut stand: Vec<&raea_sys_motionfaults::Fault> = Vec::new();
for f in &c.faults {
if stands(f, &verdicts, &judge) {
stand.push(f);
}
}
held += c.faults.len() - stand.len();
total += stand.len();
for f in &stand {
lines += &format!(" {:<8} {} key: {}\n", f.check, f.says, key(f));
}
text += &format!("{} ({}): {} frames, {} fault{}\n{lines}", c.who, c.skeleton.display(), c.frames, stand.len(), if stand.len() == 1 { "" } else { "s" });
rows.push(json!({"character": c.who, "skeleton": c.skeleton, "frames": c.frames, "faults": stand.iter().map(|f| f.to_json()).collect::<Vec<_>>()}));
}
if given + fixes > 0 {
std::fs::create_dir_all(store.parent().unwrap_or(std::path::Path::new("."))).map_err(|e| e.to_string())?;
std::fs::write(&store, serde_json::to_string_pretty(&verdicts.to_json()).unwrap_or_default()).map_err(|e| format!("{}: {e}", store.display()))?;
}
critic::append(&epath, &examples)?;
if let Some(dir) = lastp.parent() {
std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
}
std::fs::write(&lastp, serde_json::to_string_pretty(&json!({"checks": raea_sys_motionfaults::CHECKS, "characters": keep})).unwrap_or_default()).map_err(|e| format!("{}: {e}", lastp.display()))?;
text += &format!("{held} held back by verdicts and the critic ({} labels), {given} verdicts given, {fixes} fixed since the last run (kept as real) in {}", judge.labels, store.display());
Ok((text, json!({"characters": rows, "faults": total, "held": held, "fixed": fixes}), total))
}
/// `--fine-upto N` / `--fine-from N` (`--real-upto`, `--real-from`): that call's verdicts only on findings of the key
/// within those sizes, in the finding's own units (degrees past the range for a finger or a limit): a pinky's small
/// bends fine, its big one real.
/// A fault that stands: marked real, or not marked fine and scored a fault by the judge.
fn stands(f: &raea_sys_motionfaults::Fault, verdicts: &raea_sys_motionfaults::verdicts::Verdicts, judge: &critic::Critic) -> bool {
verdicts.real_at(f) || (verdicts.stands(f) && judge.score(f) >= critic::SAY)
}
fn sizes(args: &[String], real: bool) -> (f32, f32) {
let (a, b) = if real { ("--real-from", "--real-upto") } else { ("--fine-from", "--fine-upto") };
let get = |flag: &str, or: f32| args.windows(2).find(|w| w[0] == flag).and_then(|w| w[1].parse().ok()).unwrap_or(or);
(get(a, f32::NEG_INFINITY), get(b, f32::INFINITY))
}
/// Who a verdict is by: `--by NAME` (an agent that looked: claude), else a person (marked).
fn by(args: &[String]) -> &str {
args.windows(2).find(|w| w[0] == "--by").map_or("marked", |w| w[1].as_str())
}
/// The motion critic fitted to every example kept, held out by key, written beside the verdicts.
pub fn train() -> Result<String, String> {
let (cpath, epath) = critic::paths(&verdicts_path());
let ex = critic::examples(&std::fs::read_to_string(&epath).unwrap_or_default());
if ex.is_empty() {
return Ok(format!("motion critic: no examples yet ({})", epath.display()));
}
let c = critic::Critic::fit(&ex);
let right = ex.iter().filter(|e| (c.score_x(&e.0, &e.1) >= critic::SAY) == (e.2 >= 0.5)).count();
let prior = ex.iter().filter(|e| (critic::Critic::prior().score_x(&e.0, &e.1) >= critic::SAY) == (e.2 >= 0.5)).count();
let mut keys: Vec<&String> = ex.iter().map(|e| &e.1[2]).collect();
keys.sort();
keys.dedup();
let held = keys.iter().map(|k| {
let m = critic::Critic::fit(&ex.iter().filter(|e| &e.1[2] != *k).cloned().collect::<Vec<_>>());
ex.iter().filter(|e| &e.1[2] == *k && (m.score_x(&e.0, &e.1) >= critic::SAY) == (e.2 >= 0.5)).count()
}).sum::<usize>();
std::fs::write(&cpath, serde_json::to_string_pretty(&c.to_json()).unwrap_or_default()).map_err(|e| format!("{}: {e}", cpath.display()))?;
let real = ex.iter().filter(|e| e.2 >= 0.5).count();
Ok(format!("motion critic: {} examples on {} keys ({real} real, {} fine): the prior agreed with {prior}, the fitted critic with {right}, and with {held} each fitted without its own key (held out); kept in {}", ex.len(), keys.len(), ex.len() - real, cpath.display()))
}
fn verdicts_path() -> std::path::PathBuf {
match std::env::var_os("RAEA_NOTICE_MOTION").filter(|v| !v.is_empty()) {
Some(p) => p.into(),
None => raea_sys_notice::model::path().with_file_name("motion.json"),
}
}
+98
View File
@@ -0,0 +1,98 @@
//! `raea scene faults EDIT.tsx --seed N`: the judge measured on faults of known size. N props that rest as they should
//! are each moved once (sunk into what they stand on, lifted a few millimetres off it, or lifted into the air), the
//! lint run again, and the planted fault's finding judged. What it says: how many the lint found, and of those a camera
//! sees at two pixels or more, how many the judge calls faults; of those no camera sees, how many it still calls one.
//! Nothing is written: a planted fault's truth is its size, which the judge's own features already carry, so it
//! measures the judge rather than teaching it.
use bevy::math::{Mat4, Vec3};
use serde_json::Value;
use raea_core_scene::{Item, label};
use raea_sys_motionfaults::plant::Rng;
use raea_sys_notice::{Cam, FAULT, Model, Scene, camera};
/// Props this big across or smaller are moved.
const PROP: f32 = 1.2;
/// Pixels a planted fault covers at the least to count as plain to see.
const PLAIN: f32 = 2.0;
fn moved(its: &[Item], name: &str, by: Vec3) -> Vec<Item> {
its.iter().cloned().map(|mut it| {
if (it.kind == "mesh" || it.kind == "model") && label(&it, "") == name {
it.world = Mat4::from_translation(by) * it.world;
}
it
}).collect()
}
#[allow(clippy::too_many_arguments)]
pub fn run(now: &[Item], next: &[Item], views: &[Vec<Item>], found: &[Value], w: u32, h: u32, model: &Model, n: usize) -> String {
let count = |name: &str| now.iter().filter(|it| (it.kind == "mesh" || it.kind == "model") && label(it, "") == name).count();
let props: Vec<&str> = found
.iter()
.filter(|v| v["check"] == "rests")
.filter(|v| {
let (lo, hi) = (&v["box"]["min"], &v["box"]["max"]);
(0..3).all(|k| hi[k].as_f64().unwrap_or(9.0) - lo[k].as_f64().unwrap_or(0.0) <= PROP as f64)
})
.filter_map(|v| v["part"].as_str())
.filter(|p| count(p) == 1)
.collect();
let cams: Vec<Cam> = views.iter().filter_map(|f| camera(f)).collect();
// only props some camera of the shot sees (the middle of the box's top): a fault planted out of view tells
// nothing of how the judge weighs one in it
let scene = Scene::of(now);
let in_view = |p: &str| {
let Some(v) = found.iter().find(|v| v["part"] == p) else { return false };
let at = |k: usize, e: &str| v["box"][e][k].as_f64().unwrap_or(0.0) as f32;
let top = Vec3::new((at(0, "min") + at(0, "max")) / 2.0, at(1, "max") + 0.01, (at(2, "min") + at(2, "max")) / 2.0);
raea_sys_notice::seen(&[raea_sys_notice::sight::Spot { at: top, facing: None, size: 0.0 }], false, &cams, &scene, w as f32, h as f32).shown > 0
};
let props: Vec<&str> = props.into_iter().filter(|p| in_view(p)).collect();
if props.is_empty() {
return "no prop the shot sees rests on anything to plant a fault in".into();
}
let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
let (mut lines, mut lint_found, mut plain, mut plain_flagged, mut hidden, mut hidden_flagged, mut small, mut small_flagged) = (Vec::new(), 0, 0, 0, 0, 0, 0, 0);
for i in 0..n {
let part = props[(rng.next() * props.len() as f32) as usize % props.len()];
let r = rng.next();
let (kind, d) = if r < 0.4 { ("floats", 0.002 + rng.next() * 0.028) } else if r < 0.8 { ("sunk", 0.005 + rng.next() * 0.035) } else { ("air", 0.08 + rng.next() * 0.22) };
let by = Vec3::new(0.0, if kind == "sunk" { -d } else { d }, 0.0);
let (a, b) = (moved(now, part, by), moved(next, part, by));
let (again, _) = raea_sys_contact::lint(&a, &b);
let want = |c: &str| c == kind || (kind == "sunk" && c == "seated") || (kind == "air" && c == "floats") || (kind != "sunk" && c == "mounted");
let Some(f) = again.iter().find(|v| v["part"] == part && v["check"].as_str().is_some_and(want)) else {
// what it said of the part instead (a prop lifted against a wall reads as mounted on it)
let said: Vec<&str> = again.iter().filter(|v| v["part"] == part).filter_map(|v| v["check"].as_str()).collect();
lines.push(format!("{i:>3} {kind:<6} {:>6.1} mm {part}: not found as {kind} (the lint said {})", d * 1000.0, said.join(", ")));
eprintln!("{}", lines.last().unwrap());
continue;
};
lint_found += 1;
let scene = Scene::of(&a);
let j = raea_sys_notice::judge_in(std::slice::from_ref(f), &scene, &cams, w, h, model);
let Some(j) = j.first() else { continue };
let flagged = j.p >= FAULT;
if j.seen.shown == 0 {
hidden += 1;
hidden_flagged += flagged as usize;
} else if j.seen.px >= PLAIN {
plain += 1;
plain_flagged += flagged as usize;
} else {
small += 1;
small_flagged += flagged as usize;
}
lines.push(format!("{i:>3} {kind:<6} {:>6.1} mm {part}: seen {}/{} frames, {:.1} px -> {:.2}{}", d * 1000.0, j.seen.shown, j.seen.frames, j.seen.px, j.p, if flagged { " FAULT" } else { "" }));
// each trial lints the scene again (half a minute on a furnished room): said as it goes
eprintln!("{}", lines.last().unwrap());
}
lines.push(format!(
"planted {n} in {} props: the lint found {lint_found}; plain to see (>= {PLAIN} px) {plain}, judged faults {plain_flagged}; seen under {PLAIN} px {small}, judged faults {small_flagged}; no camera sees {hidden}, judged faults {hidden_flagged}",
props.len()
));
lines.join("\n")
}
+40 -7
View File
@@ -1,7 +1,10 @@
//! `raea scene stage EDIT.tsx [--composition ID] [--from N] [--to N] [--json]`: every frame's scene stepped without
//! drawing and held to the stage checks a render runs at its end (raea-sys-stage, docs/stage-guards.feature SG10-SG14):
//! 3D type that can't be read, parts that snap, a camera that lurches or reverses, frames with nothing composed in
//! them. Errors fail it, as they fail a render, so it's the cheap look before one.
//! them, a part shown closer than its planned detail (MK21). Errors fail it, as they fail a render, so it's the cheap look before one. It lays out no page, so what the
//! page holds waits for a render: its words over the parts (type-over-part), a Label's part as the shot's subject, and
//! a frame its words or pictures fill, which reads empty here and is said as a warning, not failed (SG11).
//! `--clearance M` holds the camera M metres off every solid part on every frame (0.45 for a carried camera, MK16).
use serde_json::json;
@@ -9,8 +12,16 @@ use raea_core_facts::{Level, finding};
use raea_runtime_bundle::{bundle_composition, comp_opts, flag};
use raea_runtime_export::{all_items, scene_frames_to};
pub(crate) fn cli(args: &[String]) -> Result<String, String> {
let usage = "raea scene stage EDIT.tsx [--composition ID] [--from N] [--to N] [--json]";
/// A composition's frames stepped without drawing, for `stage` and `lod`: each frame's parts from --from to --to (every
/// frame before is still stepped), their numbers, the frame's size and rate, and the composition's folder.
pub(crate) struct Stepped {
pub items: Vec<Vec<raea_core_scene::Item>>,
pub nums: Vec<i64>,
pub size: (u32, u32, f64),
pub dir: std::path::PathBuf,
}
pub(crate) fn stepped(args: &[String], usage: &str) -> Result<Stepped, String> {
let Some(edit) = args.get(2) else { return Err(usage.into()) };
let tsx = dunce::canonicalize(&std::path::PathBuf::from(edit)).map_err(|e| format!("{edit}: {e}"))?;
let dir = tsx.parent().unwrap().to_path_buf();
@@ -22,13 +33,35 @@ pub(crate) fn cli(args: &[String]) -> Result<String, String> {
let _ = std::fs::remove_file(&js);
let (frames, w, h, fps) = got?.ok_or("the composition has no 3D")?;
let frames: Vec<_> = frames.into_iter().filter(|(f, _)| *f >= from && to.is_none_or(|t| *f <= t)).collect();
let (Some(first), Some(last)) = (frames.first().map(|f| f.0), frames.last().map(|f| f.0)) else { return Err(format!("no frames from {from}")) };
let nums: Vec<i64> = frames.iter().map(|(f, _)| *f).collect();
let fs = raea_sys_stage::check(&all_items(&frames), &nums, w, h, fps, "raea scene stage");
if frames.is_empty() {
return Err(format!("no frames from {from}"));
}
Ok(Stepped { nums: frames.iter().map(|(f, _)| *f).collect(), items: all_items(&frames), size: (w, h, fps), dir })
}
pub(crate) fn cli(args: &[String]) -> Result<String, String> {
let Stepped { items, nums, size: (w, h, fps), dir } = stepped(args, "raea scene stage EDIT.tsx [--composition ID] [--from N] [--to N] [--clearance M] [--json]")?;
let (first, last) = (nums[0], nums[nums.len() - 1]);
let mut fs = raea_sys_stage::check(&items, &nums, w, h, fps, "raea scene stage");
// and each part held to its planned detail (its own `lod`, or its name's on the plan above it: MK21), as a render does
fs.extend(raea_runtime_lod_plan::lods(&items, &nums, w, h, fps, "raea scene stage", raea_runtime_lod_plan::plan::lods(&dir)).1.into_iter().filter(|f| f.check == "lod-closer"));
fs = raea_core_facts::finding::ranked(fs);
// the camera held off every solid part, when asked: the number after the flag, else a carried camera's 0.45 m
if let Some(v) = flag(args, "--clearance") {
let min = v.parse::<f32>().ok().filter(|m| *m >= 0.0).ok_or_else(|| format!("--clearance takes metres (0.45 for a carried camera), got {v:?}"))?;
let mut c = crate::clearance::clearance(&items, &nums, w, h, fps, min, "raea scene stage");
c.append(&mut fs);
fs = c;
}
for f in fs.iter_mut().filter(|f| f.check == "frame-empty" && f.level == Level::Error) {
f.level = Level::Warn;
f.says.push_str(" (no page is laid out here: if its words or pictures fill these frames, a render passes them)");
}
let text = if args.iter().any(|a| a == "--json") {
serde_json::to_string_pretty(&json!({"frames": [first, last], "findings": fs})).unwrap_or_default()
} else {
fs.iter().map(raea_core_facts::Finding::line).chain([format!("frames {first} to {last}: {}", finding::count(&fs))]).collect::<Vec<_>>().join("\n")
let note = "the page's checks (its words over parts, a Label's subject) run in raea render";
fs.iter().map(raea_core_facts::Finding::line).chain([format!("frames {first} to {last}: {} ({note})", finding::count(&fs))]).collect::<Vec<_>>().join("\n")
};
if fs.iter().any(|f| f.level == Level::Error) {
println!("{text}");
+5 -3
View File
@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "raea solid info and raea solid view: a solid file run, its parts measured (raea-core-solidinfo), and its review sheets in colour and clay"
description = "raea make solid info and raea make solid view: a solid file run, its parts measured (raea-core-solidinfo), and its review sheets in colour and clay"
[dependencies]
dunce = "1"
@@ -14,9 +14,11 @@ 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" }
# `raea judge`, dispatched with `raea solid` (verb())
# `raea judge`, dispatched with `raea make solid` (verb())
raea-app-judge = { path = "../judge" }
raea-app-ask = { path = "../ask" }
# `raea solid export`: the solid built, written as .glb and read back (core/shape), named and coloured (core/meshcheck)
# a scene, kit or shot held to its plan (docs/goal.feature)
raea-app-make = { path = "../make" }
# `raea make solid export`: the solid built, written as .glb and read back (core/shape), named and coloured (core/meshcheck)
raea-core-shape = { path = "../../core/shape" }
raea-core-meshcheck = { path = "../../core/meshcheck" }
+4 -4
View File
@@ -1,4 +1,4 @@
//! `raea solid export FILE.ts -o OUT.glb [--set k=v,...] [--part NAME] [--colour #RRGGBB]` (docs/blender.feature BL1):
//! `raea make solid export FILE.ts -o OUT.glb [--set k=v,...] [--part NAME] [--colour #RRGGBB]` (docs/blender.feature BL1):
//! a solid written as one .glb, metres, y up, so a Blender step can take it (bake.py for real UVs and baked maps, a
//! cloth to fall on). The solid stays the source: the .glb is made again from it whenever it changes. An empty solid,
//! or one solid info finds an error in, is refused with the findings. The file is read back and measured against the
@@ -52,7 +52,7 @@ fn said(info: &Value, level: &str, part: Option<&str>) -> Vec<String> {
}
pub fn export(file: &Path, parts: &[(String, String)], info: &Value, args: &[String]) -> Result<String, String> {
let out = flag(args, "-o").filter(|o| o.ends_with(".glb")).ok_or("raea solid export FILE.ts -o OUT.glb: give the .glb to write")?;
let out = flag(args, "-o").filter(|o| o.ends_with(".glb")).ok_or("raea make solid export FILE.ts -o OUT.glb: give the .glb to write")?;
let part = flag(args, "--part");
let chosen: Vec<&(String, String)> = parts.iter().filter(|(n, _)| part.as_deref().is_none_or(|p| p == n)).collect();
if chosen.is_empty() {
@@ -79,7 +79,7 @@ pub fn export(file: &Path, parts: &[(String, String)], info: &Value, args: &[Str
let name = part.clone().unwrap_or_else(|| file.file_stem().and_then(|s| s.to_str()).unwrap_or("solid").to_string());
j["nodes"][0]["name"] = json!(name);
j["meshes"][0]["name"] = json!(name);
j["asset"]["generator"] = json!("raea solid export");
j["asset"]["generator"] = json!("raea make solid export");
if let Some(c) = flag(args, "--colour") {
j["materials"] = json!([{"name": name, "pbrMetallicRoughness": {"baseColorFactor": linear(&c)?, "metallicFactor": 0.0, "roughnessFactor": 0.8}}]);
j["meshes"][0]["primitives"][0]["material"] = json!(0);
@@ -92,7 +92,7 @@ pub fn export(file: &Path, parts: &[(String, String)], info: &Value, args: &[Str
if !diff.is_empty() {
return Err(format!("solid export: {out} doesn't read back as the solid: {}", diff.join("; ")));
}
let side = json!({"source": format!("raea solid export {}{}", file.display(), part.as_ref().map(|p| format!(" --part {p}")).unwrap_or_default()), "license": "built in code for this project", "credit": ""});
let side = json!({"source": format!("raea make solid export {}{}", file.display(), part.as_ref().map(|p| format!(" --part {p}")).unwrap_or_default()), "license": "built in code for this project", "credit": ""});
std::fs::write(format!("{out}.json"), serde_json::to_string_pretty(&side).unwrap_or_default()).map_err(|e| e.to_string())?;
let r = |x: f64| (x * 1e5).round() / 1e5;
let mut t = vec![format!(
+9 -8
View File
@@ -1,11 +1,11 @@
//! `raea solid info FILE.ts [--json] [--set k=v,...] [--expect E.json] [--walk]`: the file's solid measured
//! `raea make solid info FILE.ts [--json] [--set k=v,...] [--expect E.json] [--walk]`: the file's solid measured
//! (raea-core-solidinfo). FILE.ts exports `default`: a Solid, an object of named Solids (the parts), or a function
//! of the params returning either; and optionally `params`, each a number, a boolean, or `[low, high, default]`. The
//! file is run by `raea run` (a wrapper that prints each part's shape expression), then measured natively. --set
//! builds it at other params and says what moved from the defaults; --walk moves each ranged param alone to each end
//! and says which break it (more pieces, empty) and which reach no geometry. FILE.expect.json beside it is read when
//! --expect isn't given. Errors exit 1, as scene lint. A part's `role` comes from the file's `roles` export ({body:
//! "contain"}), its `at` from the line that names it. `raea solid view` takes its pictures (view.rs); `raea solid export`
//! "contain"}), its `at` from the line that names it. `raea make solid view` takes its pictures (view.rs); `raea make solid export`
//! writes it as a .glb for a Blender step (export.rs). Its `needs` export ({textured: true}) asks for what solids can't
//! give yet: real UVs and baked maps name bake.py (docs/blender.feature BL14).
@@ -18,7 +18,7 @@ use serde_json::{Map, Value, json};
mod export;
mod view;
pub const USAGE: &str = "raea solid info FILE.ts [--json] [--set k=v,...] [--expect E.json] [--walk] (volume, box, pieces, genus per part; joints; predictions and mutants)\n raea solid view FILE.ts -o DIR [--set k=v,...] [--json] (the solid's parts in colour and clay from fixed cameras)\n raea solid export FILE.ts -o OUT.glb [--set k=v,...] [--part NAME] [--colour #RRGGBB] (the solid as one .glb for a Blender step, read back and checked)";
pub const USAGE: &str = "raea make solid info FILE.ts [--json] [--set k=v,...] [--expect E.json] [--walk] (volume, box, pieces, genus per part; joints; predictions and mutants)\n raea make solid view FILE.ts -o DIR [--set k=v,...] [--json] (the solid's parts in colour and clay from fixed cameras)\n raea make solid export FILE.ts -o OUT.glb [--set k=v,...] [--part NAME] [--colour #RRGGBB] (the solid as one .glb for a Blender step, read back and checked)";
thread_local! {
/// the last run file's `roles` and `needs` exports
@@ -68,7 +68,7 @@ print("RAEA_SOLID_INFO " + JSON.stringify({{ params: p, spec, parts: exprs, role
fn textured(out: &mut Value, file: &Path) {
let stem = file.file_stem().and_then(|s| s.to_str()).unwrap_or("solid");
let f = raea_core_meshcheck::blender::fix("bake.py", &format!("media/{stem}.glb media/{stem}-baked.glb --into-colour"));
let run = format!("raea solid export {} -o media/{stem}.glb --colour #RRGGBB && {}", file.display(), f["run"].as_str().unwrap_or(""));
let run = format!("raea make solid export {} -o media/{stem}.glb --colour #RRGGBB && {}", file.display(), f["run"].as_str().unwrap_or(""));
let says = format!("its file asks for textures (needs.textured), and a solid's UVs are box projections: export it and bake real UVs and maps; fix: {run}");
if let Some(a) = out["found"].as_array_mut() {
a.push(json!({"check": "textures", "level": "warning", "says": says, "fix": {"blender": "bake.py", "run": run}}));
@@ -91,13 +91,14 @@ fn parse_set(s: &str) -> Result<Map<String, Value>, String> {
Ok(m)
}
/// `raea solid ...`, `raea judge ...` and `raea ask ...` (docs/ask.feature AK3, which prints as it goes and exits with
/// `raea make solid ...`, `raea judge ...`, `raea make ...` (docs/goal.feature) and `raea ask ...` (docs/ask.feature AK3, which prints as it goes and exits with
/// its own code), the verbs that build and judge a piece (engine/cli hands them over), or None for another verb.
pub fn verb(args: &[String]) -> Option<Result<String, String>> {
match args.first().map(String::as_str) {
Some("solid") => Some(cli(args)),
Some("judge") => Some(raea_app_judge::cli(args)),
Some("ask") => std::process::exit(raea_app_ask::cli(&args[1..])),
Some("make") => Some(raea_app_make::cli(args)),
_ => None,
}
}
@@ -133,7 +134,7 @@ pub fn cli(args: &[String]) -> Result<String, String> {
return export::export(&file, &parts, &out, args);
}
if verb == "view" {
let dir = crate::view::out_dir(args).ok_or("raea solid view FILE.ts -o DIR: give the folder for the sheets")?;
let dir = crate::view::out_dir(args).ok_or("raea make solid view FILE.ts -o DIR: give the folder for the sheets")?;
return crate::view::view(&file, &set, &out, &dir, json_out);
}
out["params"] = params;
@@ -178,7 +179,7 @@ pub fn cli(args: &[String]) -> Result<String, String> {
}
// 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 found = finding::ranked(out["found"].as_array().into_iter().flatten().filter_map(|v| Finding::of_value(v, "raea make 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"] {
@@ -199,7 +200,7 @@ pub fn cli(args: &[String]) -> Result<String, String> {
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", s["volume"], s["box"]["size"], s["pieces"], s["genus"], s["tris"]));
t.push(format!("raea solid info: {}", finding::count(&found)));
t.push(format!("raea make solid info: {}", finding::count(&found)));
t.join("\n")
};
if errors {
+1 -1
View File
@@ -1,4 +1,4 @@
//! `raea solid view FILE.ts -o DIR [--set k=v,...]`: one solid's review sheets (research note agent-tool-surface.md's
//! `raea make solid view FILE.ts -o DIR [--set k=v,...]`: one solid's review sheets (research note agent-tool-surface.md's
//! `solid view`). The file's parts are put in a small scene, each on its own clay-friendly colour, on a slab under
//! a key and fill light, with a hero camera from the front-right corner, and `raea render --review` takes the fixed
//! views of it in colour and clay. It prints a sidecar: the sheets, the solid's box, whether it is in more than one
+1 -1
View File
@@ -17,5 +17,5 @@ serde_json = "1"
# the verbs' flags read as a render reads its own
raea-runtime-bundle = { path = "../../runtime/bundle" }
raea-runtime-export = { path = "../../runtime/export" }
# `raea motion` and `raea setup motion` (apps/motion), still reached as tools::motion
# `raea make motion` and `raea setup motion` (apps/motion), still reached as tools::motion
raea-app-motion = { path = "../motion" }
+9 -3
View File
@@ -21,8 +21,10 @@ struct Hook {
fn hooks(agent: &str) -> R<Vec<Hook>> {
let h = |event, matcher, secs| Hook { event, matcher, secs };
Ok(match agent {
"claude" => vec![h("PreToolUse", "Bash", 30), h("PostToolUse", "*", 60), h("Stop", "", 10)],
"codex" => vec![h("PreToolUse", "^(Bash|shell|shell_command|exec_command)$", 30), h("PostToolUse", "^(apply_patch|Edit|Write)$", 60)],
// SessionStart and UserPromptSubmit: notes sent from raea while the session was closed or idle reach it when it
// starts again or is next written to (Shane 11-28: "notes reach closed sessions")
"claude" => vec![h("PreToolUse", "Bash", 30), h("PostToolUse", "*", 60), h("Stop", "", 30), h("SessionStart", "", 10), h("UserPromptSubmit", "", 10)],
"codex" => vec![h("PreToolUse", "^(Bash|shell|shell_command|exec_command)$", 30), h("PostToolUse", "^(apply_patch|Edit|Write)$", 60), h("Stop", "", 30), h("SessionStart", "", 10), h("UserPromptSubmit", "", 10)],
"gemini" => vec![h("BeforeTool", "run_shell_command", 30), h("AfterTool", "write_file|replace", 60)],
"kimi" => vec![h("PreToolUse", "Bash|Shell", 30), h("PostToolUse", "Write|Edit|WriteFile|StrReplaceFile", 60)],
a => return Err(format!("no agent {a:?}: claude, codex, kimi or gemini")),
@@ -124,7 +126,8 @@ mod tests {
let c = d.join("claude/settings.json");
std::fs::create_dir_all(c.parent().unwrap()).unwrap();
std::fs::write(&c, r#"{"model":"x","hooks":{"PostToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"other"}]},{"matcher":"Write","hooks":[{"type":"command","command":"raea hook claude"}]}]}}"#).unwrap();
let [pre, post, stop] = <[Hook; 3]>::try_from(hooks("claude").unwrap()).ok().unwrap();
let [pre, post, stop, start, prompt] = <[Hook; 5]>::try_from(hooks("claude").unwrap()).ok().unwrap();
assert!(add_json(&c, "claude", &start).unwrap() && add_json(&c, "claude", &prompt).unwrap() && !add_json(&c, "claude", &start).unwrap());
assert!(add_json(&c, "claude", &pre).unwrap() && !add_json(&c, "claude", &pre).unwrap());
assert!(add_json(&c, "claude", &post).unwrap() && !add_json(&c, "claude", &post).unwrap(), "an older raea's after-save hook is widened to every tool, once");
assert!(add_json(&c, "claude", &stop).unwrap() && !add_json(&c, "claude", &stop).unwrap());
@@ -133,6 +136,9 @@ mod tests {
assert_eq!((v["hooks"]["PostToolUse"][0]["matcher"].as_str(), v["hooks"]["PostToolUse"][1]["matcher"].as_str()), (Some("Bash"), Some("*")));
assert_eq!(v["hooks"]["PreToolUse"][0]["hooks"][0]["command"], "raea hook claude");
assert_eq!(v["hooks"]["Stop"][0]["hooks"][0]["command"], "raea hook claude");
assert_eq!(v["hooks"]["SessionStart"][0]["hooks"][0]["command"], "raea hook claude");
assert_eq!(v["hooks"]["UserPromptSubmit"][0]["hooks"][0]["command"], "raea hook claude");
assert_eq!(hooks("codex").unwrap().iter().map(|h| h.event).collect::<Vec<_>>(), ["PreToolUse", "PostToolUse", "Stop", "SessionStart", "UserPromptSubmit"]);
let g = d.join("gemini/settings.json");
let [before, _] = <[Hook; 2]>::try_from(hooks("gemini").unwrap()).ok().unwrap();
assert!(add_json(&g, "gemini", &before).unwrap());
+3 -3
View File
@@ -1,10 +1,10 @@
//! The verbs that run raea's local tools: sound (`raea sao`, `tokensynth`, `setup-audio`, `sounds`: foley and an
//! instrument's notes made by local models, and the open sample libraries), `raea splat` (footage trained into a
//! The verbs that run raea's local tools: sound (`raea make sao`, `tokensynth`, `setup-audio`, `sounds`: foley and an
//! instrument's notes made by local models, and the open sample libraries), `raea make splat` (footage trained into a
//! Gaussian splat), `raea song` (a song's energy map, apps/tools/src/song.rs) and `raea gen` (generation flows on
//! made.app, fal, Replicate, OpenRouter, Modal and ComfyUI, with sao as the local model: apps/tools/src/generate.rs).
pub mod generate;
/// `raea motion` and `raea setup motion`: body motion made by Kimodo, on MLX on a Mac, on PyTorch elsewhere (apps/motion)
/// `raea make motion` and `raea setup motion`: body motion made by Kimodo, on MLX on a Mac, on PyTorch elsewhere (apps/motion)
pub use raea_app_motion as motion;
pub mod song;
pub mod sound;
+8 -8
View File
@@ -1,12 +1,12 @@
//! raea's sound tools from the command line: the two local models (SAO for foley, TokenSynth for an instrument's notes)
//! and the open sample libraries a Tone.js Sampler can play.
//!
//! raea sao "PROMPT" [--seconds 2] [--seed 1] [--dir EDIT_DIR] [-o OUT.wav]
//! raea tokensynth "TIMBRE" [--notes C2,C3,C4] [--seconds 2] [--velocity 100] [--seed 1234] [--precision fp16]
//! raea make sao "PROMPT" [--seconds 2] [--seed 1] [--dir EDIT_DIR] [-o OUT.wav]
//! raea make tokensynth "TIMBRE" [--notes C2,C3,C4] [--seconds 2] [--velocity 100] [--seed 1234] [--precision fp16]
//! [--dir EDIT_DIR] [-o OUT_DIR]
//! raea setup-audio [--check] [sao|tokensynth]
//! raea sounds [WORDS...]
//! raea sounds get PACK/INSTRUMENT [--notes C2,C4 | --all] [--dir EDIT_DIR] [-o OUT_DIR]
//! raea make sounds [WORDS...]
//! raea make sounds get PACK/INSTRUMENT [--notes C2,C4 | --all] [--dir EDIT_DIR] [-o OUT_DIR]
//!
//! sao and tokensynth make through the same asset store a composition's render does (raea_io_assets::Store beside
//! EDIT_DIR/edit.tsx, default the working folder), with the same parameters, so a sound made here is the one
@@ -126,9 +126,9 @@ fn deliver(from: &Path, to: &Path) -> R<()> {
Ok(())
}
pub const SAO_USAGE: &str = "raea sao \"PROMPT\" [--seconds 2] [--seed 1] [--dir EDIT_DIR] [-o OUT.wav]";
pub const SAO_USAGE: &str = "raea make sao \"PROMPT\" [--seconds 2] [--seed 1] [--dir EDIT_DIR] [-o OUT.wav]";
/// `raea sao "PROMPT" [--seconds 2] [--seed 1] [--dir D] [-o OUT.wav]`: one foley sound, made once.
/// `raea make sao "PROMPT" [--seconds 2] [--seed 1] [--dir D] [-o OUT.wav]`: one foley sound, made once.
pub fn sao(args: &[String]) -> R<String> {
const USAGE: &str = SAO_USAGE;
let prompt = positional(&args[1..], &["--seconds", "--seed", "--dir", "-o"]).join(" ");
@@ -159,9 +159,9 @@ pub fn sao(args: &[String]) -> R<String> {
Ok(format!("APPLIED sao {prompt:?}, {} s, seed {seed} -> {at} ({how}; asset {}){reuse}", js_num(seconds), &a.hash[..12]))
}
pub const TOKENSYNTH_USAGE: &str = "raea tokensynth \"TIMBRE\" [--notes C2,C3,C4] [--seconds 2] [--velocity 100] [--seed 1234] [--precision fp16] [--dir EDIT_DIR] [-o OUT_DIR]";
pub const TOKENSYNTH_USAGE: &str = "raea make tokensynth \"TIMBRE\" [--notes C2,C3,C4] [--seconds 2] [--velocity 100] [--seed 1234] [--precision fp16] [--dir EDIT_DIR] [-o OUT_DIR]";
/// `raea tokensynth "TIMBRE" [--notes C2,C3,C4] ... [-o OUT_DIR]`: an instrument's root notes, one WAV each.
/// `raea make tokensynth "TIMBRE" [--notes C2,C3,C4] ... [-o OUT_DIR]`: an instrument's root notes, one WAV each.
pub fn tokensynth(args: &[String]) -> R<String> {
const USAGE: &str = TOKENSYNTH_USAGE;
let timbre = positional(&args[1..], &["--notes", "--seconds", "--velocity", "--seed", "--precision", "--dir", "-o"]).join(" ");
+21 -15
View File
@@ -24,7 +24,7 @@ pub(crate) fn synonyms(word: &str) -> Vec<&str> {
}
}
/// `raea sounds [WORDS...]`: the instruments whose names hold every word (all of them with no words, by pack).
/// `raea make sounds [WORDS...]`: the instruments whose names hold every word (all of them with no words, by pack).
pub fn sounds(args: &[String]) -> R<String> {
if args.get(1).map(String::as_str) == Some("get") {
return sounds_get(args);
@@ -70,7 +70,7 @@ pub fn sounds(args: &[String]) -> R<String> {
if out.is_empty() {
return Ok(format!("no instrument in the sample libraries matches {:?}: try one word (piano, snare, strings, marimba)", words.join(" ")));
}
Ok(format!("{}\n\nraea sounds get PACK/INSTRUMENT [--notes C2,C4] copies one into media/sounds/ and prints the Sampler for it", out.join("\n\n")))
Ok(format!("{}\n\nraea make sounds get PACK/INSTRUMENT [--notes C2,C4] copies one into media/sounds/ and prints the Sampler for it", out.join("\n\n")))
}
/// Percent-encode a URL path (spaces, commas and `#` in VCSL's names), keeping its slashes.
@@ -106,16 +106,16 @@ pub(crate) fn static_path(p: &Path) -> String {
}
}
/// `raea sounds get PACK/INSTRUMENT [--notes ..|--all] [-o DIR]`: an instrument's samples into the edit's
/// `raea make sounds get PACK/INSTRUMENT [--notes ..|--all] [-o DIR]`: an instrument's samples into the edit's
/// media (default media/sounds/PACK-INSTRUMENT/), its licence beside them, and the TSX that plays them.
pub(crate) fn sounds_get(args: &[String]) -> R<String> {
const USAGE: &str = "raea sounds get PACK/INSTRUMENT [--notes C2,C4 | --all] [--dir EDIT_DIR] [-o OUT_DIR] (raea sounds WORDS finds one)";
const USAGE: &str = "raea make sounds get PACK/INSTRUMENT [--notes C2,C4 | --all] [--dir EDIT_DIR] [-o OUT_DIR] (raea make sounds WORDS finds one)";
let id = *positional(&args[2..], &["--notes", "--dir", "-o"]).first().ok_or(USAGE)?;
let (pid, iid) = id.split_once('/').ok_or(USAGE)?;
let c = catalog()?;
let pack = c["packs"].as_array().into_iter().flatten().find(|p| p["id"] == pid).ok_or(format!("no sample library `{pid}`: raea sounds lists them"))?;
let pack = c["packs"].as_array().into_iter().flatten().find(|p| p["id"] == pid).ok_or(format!("no sample library `{pid}`: raea make sounds lists them"))?;
let inst = pack["instruments"].as_array().into_iter().flatten().find(|i| i["id"] == iid)
.ok_or(format!("{pid} has no instrument `{iid}`: raea sounds {iid} searches for it"))?;
.ok_or(format!("{pid} has no instrument `{iid}`: raea make sounds {iid} searches for it"))?;
let files = files_of(pack, inst);
let pitched_files: Vec<_> = files.iter().filter(|f| f.0.is_some()).cloned().collect();
let pitched = pitched_files.iter().map(|f| f.0).collect::<std::collections::BTreeSet<_>>().len() >= 3;
@@ -185,7 +185,21 @@ pub(crate) fn sounds_get(args: &[String]) -> R<String> {
}
}
let base = PathBuf::from(flag(args, "--dir").unwrap_or_else(|| ".".into()));
let out = flag(args, "-o").map(PathBuf::from).unwrap_or_else(|| base.join("media/sounds").join(format!("{pid}-{iid}")));
let mut out = flag(args, "-o").map(PathBuf::from).unwrap_or_else(|| base.join("media/sounds").join(format!("{pid}-{iid}")));
let licence = format!(
"{}\n{}\nlicence: {}\nsource: {}\n{}\n",
pack["name"].as_str().unwrap_or_default(),
inst["name"].as_str().unwrap_or_default(),
pack["licence"].as_str().unwrap_or_default(),
pack["source"].as_str().unwrap_or_default(),
pack["attribution"].as_str().unwrap_or_default()
);
// a folder that already holds another instrument keeps it: two instruments' notes share names (C4.mp3), and the
// second one's replaced the first's and its licence (#217). This one goes in a folder of its own inside it
if std::fs::read_to_string(out.join("LICENCE.txt")).is_ok_and(|held| held != licence) {
out = out.join(format!("{pid}-{iid}"));
said.push(format!("the folder given already holds another instrument, so this one is in {}", out.display()));
}
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
let cache = raea_io_home::user_home().unwrap_or_default().join(".cache/raea-sounds").join(pid).join(iid);
let template = pack["url"].as_str().unwrap_or_default();
@@ -201,14 +215,6 @@ pub(crate) fn sounds_get(args: &[String]) -> R<String> {
std::fs::copy(&cached, &to).map_err(|e| format!("{}: {e}", to.display()))?;
bytes += std::fs::metadata(&to).map(|m| m.len()).unwrap_or(0);
}
let licence = format!(
"{}\n{}\nlicence: {}\nsource: {}\n{}\n",
pack["name"].as_str().unwrap_or_default(),
inst["name"].as_str().unwrap_or_default(),
pack["licence"].as_str().unwrap_or_default(),
pack["source"].as_str().unwrap_or_default(),
pack["attribution"].as_str().unwrap_or_default()
);
std::fs::write(out.join("LICENCE.txt"), &licence).map_err(|e| e.to_string())?;
let var = iid.replace(|c: char| !c.is_ascii_alphanumeric(), "_");
let tsx = if pitched {
+4 -4
View File
@@ -1,10 +1,10 @@
//! Splats from footage: a video (or a folder of pictures) of a real place or thing trained into a 3D Gaussian splat for
//! `<Splat src>` (raea_io_assets::Store::splat; tools/splat: frames, COLMAP, Brush on Metal).
//!
//! raea splat train VIDEO|IMAGE_DIR -o OUT.ply [--frames N] [--steps N] [--max-res PX] [--from S]
//! raea make splat train VIDEO|IMAGE_DIR -o OUT.ply [--frames N] [--steps N] [--max-res PX] [--from S]
//! [--seconds N] [--max-splats N] [--matte black] [--match sequential|exhaustive]
//! [--credit TEXT] [--license TEXT] [--dir EDIT_DIR]
//! raea splat setup
//! raea make splat setup
//!
//! Goes through the asset store beside EDIT_DIR/edit.tsx (default the working folder), so the same footage and params
//! train once; OUT.ply is a copy of the store's `<hash>.ply` and OUT.ply.json of its sidecar (with --credit and
@@ -17,7 +17,7 @@ use raea_runtime_bundle::flag;
type R<T> = Result<T, String>;
pub const USAGE: &str = "raea splat train VIDEO|IMAGE_DIR -o OUT.ply [--frames 150] [--steps 20000] [--max-res 1600] [--from S] [--seconds N] [--max-splats 2000000] [--matte none|black] [--match sequential|exhaustive] [--credit TEXT] [--license TEXT] [--dir EDIT_DIR]\n raea splat setup";
pub const USAGE: &str = "raea make splat train VIDEO|IMAGE_DIR -o OUT.ply [--frames 150] [--steps 20000] [--max-res 1600] [--from S] [--seconds N] [--max-splats 2000000] [--matte none|black] [--match sequential|exhaustive] [--credit TEXT] [--license TEXT] [--dir EDIT_DIR]\n raea make splat setup";
const WITH_VALUE: [&str; 13] = ["--frames", "--steps", "--max-res", "--from", "--seconds", "--max-splats", "--matte", "--match", "--credit", "--license", "--dir", "-o", "--o"];
/// The CLI's input and params (what Store::splat is asked), checked: (input, params JSON).
@@ -57,7 +57,7 @@ pub fn parse(args: &[String]) -> R<(PathBuf, Value)> {
Ok((input, raea_io_assets::splat_params(&Value::Object(p))?))
}
/// `raea splat ...`
/// `raea make splat ...`
pub fn splat(args: &[String]) -> R<String> {
match args.get(1).map(String::as_str) {
Some("setup") => {
+26
View File
@@ -0,0 +1,26 @@
[package]
name = "raea-app-voice"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "raea voice: speech to speech on this computer (Silero's turns, Parakeet's words, Pocket TTS's voice) as lines of JSON, for an agent that talks"
[[bin]]
name = "raea-voice"
path = "src/main.rs"
[dependencies]
# Pocket TTS and its word clock
raea-io-trace = { path = "../../io/trace" }
raea-sys-speech = { path = "../../systems/speech" }
# ort sessions the way raea builds them, and the model cache
raea-sys-ml = { path = "../../systems/ml" }
ort = { version = "=2.0.0-rc.13", features = ["half"] }
# the microphone and the speakers: the cpal the mixer uses
cpal = "0.15"
anyhow = "1"
serde_json = "1"
[target.'cfg(all(windows, target_arch = "x86_64"))'.dependencies]
ort = { version = "=2.0.0-rc.13", features = ["load-dynamic"] }
+118
View File
@@ -0,0 +1,118 @@
//! Parakeet TDT 0.6b v3 (NVIDIA, CC-BY-4.0) on ONNX: what was said. The export is istupakov/parakeet-tdt-0.6b-v3-onnx
//! (int8 encoder and decoder, NeMo's 128-bin front end as a model of its own), decoded as onnx-asr's
//! NemoConformerTdt decodes it: greedy, each step's token and how many encoder frames to skip.
use std::path::Path;
use anyhow::{anyhow, Context};
use ort::session::Session;
use ort::value::Tensor;
use raea_sys_ml::models::Spec;
const REPO: &str = "istupakov/parakeet-tdt-0.6b-v3-onnx";
pub const SPEC: Spec = Spec {
name: "parakeet-tdt-0.6b-v3",
files: &[
(REPO, "nemo128.onnx", "nemo128.onnx"),
(REPO, "encoder-model.int8.onnx", "encoder-model.int8.onnx"),
(REPO, "decoder_joint-model.int8.onnx", "decoder_joint-model.int8.onnx"),
(REPO, "vocab.txt", "vocab.txt"),
],
};
/// The prediction network's state: two layers of 640.
const STATE: usize = 2 * 640;
/// Tokens one encoder frame may give before the decoder moves on (onnx-asr's max_tokens_per_step).
const PER_STEP: usize = 10;
pub struct Asr {
front: Session,
encoder: Session,
decoder: Session,
vocab: Vec<String>,
}
fn err(e: ort::Error) -> anyhow::Error {
anyhow!("parakeet: {e}")
}
impl Asr {
pub fn load(dir: &Path) -> anyhow::Result<Asr> {
let vocab = std::fs::read_to_string(dir.join("vocab.txt")).context("parakeet's vocab.txt")?;
// "token id" a line; the token itself can hold a space's mark but never a plain space
let vocab: Vec<String> = vocab.lines().filter_map(|l| l.rsplit_once(' ').map(|(t, _)| t.to_string())).collect();
anyhow::ensure!(vocab.last().map(String::as_str) == Some("<blk>"), "parakeet's vocab.txt doesn't end in its blank");
Ok(Asr {
front: raea_sys_ml::session(&dir.join("nemo128.onnx"))?,
encoder: raea_sys_ml::session(&dir.join("encoder-model.int8.onnx"))?,
decoder: raea_sys_ml::session(&dir.join("decoder_joint-model.int8.onnx"))?,
vocab,
})
}
/// The words in `x` (16 kHz mono), as one line.
pub fn hear(&mut self, x: &[f32]) -> anyhow::Result<String> {
if x.len() < 1600 {
return Ok(String::new());
}
let wave = Tensor::from_array(([1usize, x.len()], x.to_vec())).map_err(err)?;
let len = Tensor::from_array(([1usize], vec![x.len() as i64])).map_err(err)?;
let (shape, feats, flen) = {
let o = self.front.run(ort::inputs!["waveforms" => wave, "waveforms_lens" => len]).map_err(err)?;
let (shape, f) = o["features"].try_extract_tensor::<f32>().map_err(err)?;
let (_, l) = o["features_lens"].try_extract_tensor::<i64>().map_err(err)?;
(shape.iter().map(|d| *d as usize).collect::<Vec<_>>(), f.to_vec(), l[0])
};
let feats = Tensor::from_array((shape, feats)).map_err(err)?;
let flen = Tensor::from_array(([1usize], vec![flen])).map_err(err)?;
let (dim, frames, enc) = {
let o = self.encoder.run(ort::inputs!["audio_signal" => feats, "length" => flen]).map_err(err)?;
let (shape, e) = o["outputs"].try_extract_tensor::<f32>().map_err(err)?;
let (_, l) = o["encoded_lengths"].try_extract_tensor::<i64>().map_err(err)?;
(shape[1] as usize, (shape[2] as usize, l[0] as usize), e.to_vec())
};
let (width, frames) = frames;
let blank = self.vocab.len() - 1;
let (mut s1, mut s2) = (vec![0f32; STATE], vec![0f32; STATE]);
let mut tokens: Vec<usize> = Vec::new();
let (mut t, mut emitted) = (0usize, 0usize);
while t < frames.min(width) {
let frame: Vec<f32> = (0..dim).map(|d| enc[d * width + t]).collect();
let last = tokens.last().copied().unwrap_or(blank) as i32;
let o = self
.decoder
.run(ort::inputs![
"encoder_outputs" => Tensor::from_array(([1usize, dim, 1], frame)).map_err(err)?,
"targets" => Tensor::from_array(([1usize, 1], vec![last])).map_err(err)?,
"target_length" => Tensor::from_array(([1usize], vec![1i32])).map_err(err)?,
"input_states_1" => Tensor::from_array(([2usize, 1, 640], s1.clone())).map_err(err)?,
"input_states_2" => Tensor::from_array(([2usize, 1, 640], s2.clone())).map_err(err)?,
])
.map_err(err)?;
let (_, logits) = o["outputs"].try_extract_tensor::<f32>().map_err(err)?;
let best = |v: &[f32]| v.iter().enumerate().fold((0usize, f32::NEG_INFINITY), |b, (i, x)| if *x > b.1 { (i, *x) } else { b }).0;
let token = best(&logits[..self.vocab.len()]);
let skip = best(&logits[self.vocab.len()..]);
if token != blank {
s1.copy_from_slice(&o["output_states_1"].try_extract_tensor::<f32>().map_err(err)?.1[..STATE]);
s2.copy_from_slice(&o["output_states_2"].try_extract_tensor::<f32>().map_err(err)?.1[..STATE]);
tokens.push(token);
emitted += 1;
}
if skip > 0 {
t += skip;
emitted = 0;
} else if token == blank || emitted == PER_STEP {
t += 1;
emitted = 0;
}
}
Ok(self.text(&tokens))
}
/// Tokens as a line: a token's leading mark is the space before a word.
fn text(&self, tokens: &[usize]) -> String {
let joined: String = tokens.iter().map(|t| self.vocab[*t].as_str()).filter(|t| !t.starts_with("<|")).collect();
joined.replace('\u{2581}', " ").split_whitespace().collect::<Vec<_>>().join(" ")
}
}
+288
View File
@@ -0,0 +1,288 @@
//! The microphone and the speakers (cpal), or files in their place (`--from`, `--to`: a session with no devices, for
//! checks and for measuring).
use std::collections::VecDeque;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use anyhow::{anyhow, bail, Context};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
/// A stream's rate changed as it comes, by linear interpolation: speech in, and Pocket's 24 kHz out.
pub struct Resample {
/// input samples per output sample
step: f64,
/// where the next output sample falls, in input samples from the start of the next piece (-1 is `last`)
pos: f64,
last: f32,
}
impl Resample {
pub fn new(from: u32, to: u32) -> Resample {
Resample { step: from as f64 / to as f64, pos: 0.0, last: 0.0 }
}
pub fn push(&mut self, x: &[f32], out: &mut Vec<f32>) {
let Some(&end) = x.last() else { return };
while self.pos + 1.0 < x.len() as f64 {
let i = self.pos.floor();
let a = if i < 0.0 { self.last } else { x[i as usize] };
let b = x[(i + 1.0) as usize];
out.push(a + (b - a) * (self.pos - i) as f32);
self.pos += self.step;
}
self.pos -= x.len() as f64;
self.last = end;
}
}
/// Interleaved channels as one: each frame's mean.
fn mono(x: &[f32], ch: usize) -> Vec<f32> {
let mut out = Vec::with_capacity(x.len() / ch + 1);
for frame in x.chunks(ch) {
let mut sum = 0.0;
for s in frame {
sum += s;
}
out.push(sum / frame.len() as f32);
}
out
}
/// A WAV's sound as mono samples and its rate: 16-bit PCM or 32-bit float, any channels.
pub fn read_wav(path: &Path) -> anyhow::Result<(Vec<f32>, u32)> {
let b = std::fs::read(path).with_context(|| format!("{}", path.display()))?;
anyhow::ensure!(b.len() > 12 && &b[..4] == b"RIFF" && &b[8..12] == b"WAVE", "{}: not a WAV file", path.display());
let u16_at = |i: usize| u16::from_le_bytes([b[i], b[i + 1]]);
let u32_at = |i: usize| u32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]);
let (mut at, mut fmt) = (12usize, None);
while at + 8 <= b.len() {
let (id, len) = (&b[at..at + 4], u32_at(at + 4) as usize);
let body = at + 8;
if id == b"fmt " && body + 16 <= b.len() {
fmt = Some((u16_at(body), u16_at(body + 2) as usize, u32_at(body + 4), u16_at(body + 14)));
} else if id == b"data" {
let (kind, ch, rate, bits) = fmt.ok_or_else(|| anyhow!("{}: its sound comes before its format", path.display()))?;
let data = &b[body..(body + len).min(b.len())];
let one: Vec<f32> = match (kind, bits) {
(1, 16) => data.chunks_exact(2).map(|s| i16::from_le_bytes([s[0], s[1]]) as f32 / 32768.0).collect(),
(3, 32) => data.chunks_exact(4).map(|s| f32::from_le_bytes([s[0], s[1], s[2], s[3]])).collect(),
_ => bail!("{}: a {bits}-bit WAV of kind {kind}; 16-bit PCM and 32-bit float are read", path.display()),
};
return Ok((mono(&one, ch.max(1)), rate));
}
at = body + len + (len & 1);
}
bail!("{}: a WAV with no sound in it", path.display())
}
/// Mono samples as a 16-bit WAV.
pub fn write_wav(path: &Path, x: &[f32], rate: u32) -> anyhow::Result<()> {
let mut b = Vec::with_capacity(44 + x.len() * 2);
let len = (x.len() * 2) as u32;
b.extend_from_slice(b"RIFF");
b.extend_from_slice(&(36 + len).to_le_bytes());
b.extend_from_slice(b"WAVEfmt ");
for v in [16u32, 1 | (1 << 16), rate, rate * 2, 2 | (16 << 16)] {
b.extend_from_slice(&v.to_le_bytes());
}
b.extend_from_slice(b"data");
b.extend_from_slice(&len.to_le_bytes());
for s in x {
b.extend_from_slice(&((s.clamp(-1.0, 1.0) * 32767.0) as i16).to_le_bytes());
}
std::fs::write(path, b).with_context(|| format!("{}", path.display()))
}
/// The microphone: 16 kHz mono in pieces down `tx` for as long as the stream it returns is kept.
pub fn microphone(tx: Sender<Vec<f32>>) -> anyhow::Result<cpal::Stream> {
let dev = cpal::default_host().default_input_device().ok_or_else(|| anyhow!("this computer has no microphone to listen on"))?;
let cfg = dev.default_input_config().map_err(|e| anyhow!("the microphone: {e}"))?;
let ch = cfg.channels().max(1) as usize;
let mut rs = Resample::new(cfg.sample_rate().0, crate::turns::RATE as u32);
let mut take = move |mono: Vec<f32>| {
let mut out = Vec::with_capacity(mono.len());
rs.push(&mono, &mut out);
let _ = tx.send(out);
};
let bad = raea_io_trace::once::said_once::<cpal::StreamError>("raea voice: the microphone");
let stream = match cfg.sample_format() {
cpal::SampleFormat::F32 => {
dev.build_input_stream(&cfg.config(), move |d: &[f32], _: &cpal::InputCallbackInfo| take(mono(d, ch)), bad, None)
}
cpal::SampleFormat::I16 => dev.build_input_stream(
&cfg.config(),
move |d: &[i16], _: &cpal::InputCallbackInfo| {
let x: Vec<f32> = d.iter().map(|s| *s as f32 / 32768.0).collect();
take(mono(&x, ch))
},
bad,
None,
),
f => bail!("the microphone gives {f:?} samples, which raea voice doesn't read"),
}
.map_err(|e| anyhow!("the microphone didn't open (is raea allowed to use it? System Settings > Privacy & Security > Microphone): {e}"))?;
stream.play().map_err(|e| anyhow!("the microphone didn't start: {e}"))?;
Ok(stream)
}
/// A WAV in the microphone's place: its sound at the pace it was recorded (at once with `fast`), a second and a half
/// of quiet after it so its last turn ends, and then the channel closes.
pub fn microphone_file(path: &Path, fast: bool, tx: Sender<Vec<f32>>) -> anyhow::Result<()> {
let (x, rate) = read_wav(path)?;
let mut heard = Vec::with_capacity(x.len());
Resample::new(rate, crate::turns::RATE as u32).push(&x, &mut heard);
heard.extend(std::iter::repeat_n(0.0, crate::turns::RATE * 3 / 2));
std::thread::spawn(move || {
// by the clock from its start, so a late wake-up is made up and it keeps a microphone's pace
let (began, mut sent) = (Instant::now(), 0u64);
for piece in heard.chunks(crate::turns::WIN) {
if tx.send(piece.to_vec()).is_err() {
return;
}
sent += piece.len() as u64;
if !fast {
std::thread::sleep((began + Duration::from_micros(1_000_000 * sent / crate::turns::RATE as u64)).saturating_duration_since(Instant::now()));
}
}
});
Ok(())
}
/// What is waiting to be played, shared with whoever makes the sound.
pub struct Line {
pub queue: Mutex<VecDeque<f32>>,
/// samples played so far, at the voice's rate
pub played: AtomicU64,
/// everything played, when it goes to a file
kept: Mutex<Vec<f32>>,
keep: AtomicBool,
/// what went to the speakers, quiet included, for the echo to be taken out of the microphone (echo.rs): kept
/// while `tap` is on, and taken by the session
pub far: Mutex<Vec<f32>>,
pub tap: AtomicBool,
}
impl Line {
/// Drops what hasn't been played yet (the person spoke over it, or it was stopped).
pub fn clear(&self) {
self.queue.lock().unwrap().clear();
}
/// (samples played so far, samples still waiting to be)
pub fn at(&self) -> (u64, usize) {
(self.played.load(Ordering::Relaxed), self.queue.lock().unwrap().len())
}
/// The next `n` samples (fewer when the queue runs out), counted as played.
fn take(&self, want: usize) -> Vec<f32> {
let mut q = self.queue.lock().unwrap();
let n = want.min(q.len());
let got: Vec<f32> = q.drain(..n).collect();
self.played.fetch_add(n as u64, Ordering::Relaxed);
if self.keep.load(Ordering::Relaxed) {
self.kept.lock().unwrap().extend(&got);
}
if self.tap.load(Ordering::Relaxed) && want < 1 << 20 {
let mut far = self.far.lock().unwrap();
far.extend(&got);
far.extend(std::iter::repeat_n(0.0, want - n));
}
got
}
}
/// A file in the speakers' place: what is waiting is taken at the pace it would play (all of it at once with `fast`).
fn drain(line: Arc<Line>, each: usize) {
std::thread::spawn(move || {
let (began, mut ticks) = (Instant::now(), 0u32);
while Arc::strong_count(&line) > 1 {
ticks += 1;
std::thread::sleep((began + Duration::from_millis(20) * ticks).saturating_duration_since(Instant::now()));
line.take(each);
}
});
}
/// The speakers, or a file in their place.
pub struct Speaker {
pub line: Arc<Line>,
rate: u32,
to: Option<PathBuf>,
_stream: Option<cpal::Stream>,
}
impl Speaker {
/// `rate`: the voice's. With `to`, nothing sounds: what would have played is written there when the session ends.
pub fn open(rate: u32, to: Option<PathBuf>, fast: bool) -> anyhow::Result<Speaker> {
let line = Arc::new(Line { queue: Mutex::new(VecDeque::new()), played: AtomicU64::new(0), kept: Mutex::new(Vec::new()), keep: AtomicBool::new(to.is_some()), far: Mutex::new(Vec::new()), tap: AtomicBool::new(false) });
if to.is_some() {
drain(line.clone(), if fast { usize::MAX } else { rate as usize / 50 });
return Ok(Speaker { line, rate, to, _stream: None });
}
let dev = cpal::default_host().default_output_device().ok_or_else(|| anyhow!("this computer has nothing to play sound on"))?;
let cfg = dev.default_output_config().map_err(|e| anyhow!("the speakers: {e}"))?;
anyhow::ensure!(cfg.sample_format() == cpal::SampleFormat::F32, "the speakers take {:?} samples, which raea voice doesn't write", cfg.sample_format());
let ch = cfg.channels().max(1) as usize;
let mut rs = Resample::new(rate, cfg.sample_rate().0);
let need = rate as f64 / cfg.sample_rate().0 as f64;
let l = line.clone();
let mut ready: VecDeque<f32> = VecDeque::new();
let play = move |out: &mut [f32], _: &cpal::OutputCallbackInfo| {
let frames = out.len() / ch;
if ready.len() < frames {
let mut made = Vec::new();
rs.push(&l.take(((frames - ready.len()) as f64 * need).ceil() as usize + 2), &mut made);
ready.extend(made);
}
for f in out.chunks_mut(ch) {
f.fill(ready.pop_front().unwrap_or(0.0));
}
};
let stream = dev.build_output_stream(&cfg.config(), play, raea_io_trace::once::said_once::<cpal::StreamError>("raea voice: the speakers"), None).map_err(|e| anyhow!("the speakers didn't open: {e}"))?;
stream.play().map_err(|e| anyhow!("the speakers didn't start: {e}"))?;
Ok(Speaker { line, rate, to, _stream: Some(stream) })
}
/// Writes the file, when the session's sound went to one.
pub fn close(&self) -> anyhow::Result<()> {
match &self.to {
Some(p) => write_wav(p, &self.line.kept.lock().unwrap(), self.rate),
None => Ok(()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_rate_changes_piece_by_piece_as_it_would_whole() {
let x: Vec<f32> = (0..4800).map(|i| (i as f32 * 0.01).sin()).collect();
let mut whole = Vec::new();
Resample::new(48_000, 16_000).push(&x, &mut whole);
let mut pieces = Vec::new();
let mut rs = Resample::new(48_000, 16_000);
for p in x.chunks(477) {
rs.push(p, &mut pieces);
}
assert!((whole.len() as i64 - 1600).abs() <= 1, "a third as many samples: {}", whole.len());
assert_eq!(whole.len(), pieces.len());
assert!(whole.iter().zip(&pieces).all(|(a, b)| (a - b).abs() < 1e-5));
}
#[test]
fn a_wav_written_reads_back() {
let f = std::env::temp_dir().join(format!("raea-voice-{}.wav", std::process::id()));
let x: Vec<f32> = (0..2400).map(|i| (i as f32 * 0.05).sin() * 0.5).collect();
write_wav(&f, &x, 24_000).unwrap();
let (y, rate) = read_wav(&f).unwrap();
std::fs::remove_file(&f).unwrap();
assert_eq!((rate, y.len()), (24_000, x.len()));
assert!(x.iter().zip(&y).all(|(a, b)| (a - b).abs() < 1e-3));
}
}
+374
View File
@@ -0,0 +1,374 @@
//! raea's own voice taken out of what the microphone hears, so the person can talk over it.
//!
//! A computer's microphone hears its speakers. While raea speaks, what was sent to the speakers (the far side) is
//! passed through a filter that learns the way from speaker to microphone (an NLMS adaptive filter, 128 ms long, at
//! the hearing rate), and what the filter makes of it is taken from the microphone's sound. What is left is the
//! person, when they speak. Where in time the echo sits (the sound card's and the room's delay) is found first, by
//! lining up the two sides' loudness over the last second.
//!
//! Until the filter has learned the room (`sure`: a second of its voice, the echo down by 10 dB or more) nothing
//! left over counts as the person, so raea is never stopped by its own voice. Once it has, sound that stands clear
//! of the echo is the person (`near`). Two filters do it (the two-path way): the one in use never learns, the one
//! behind it always does and replaces it when it leaves less, so the person's voice is never learned as echo.
use std::collections::VecDeque;
use std::time::{Duration, Instant};
use crate::audio::Resample;
use crate::turns::WIN;
/// The filter's length: 128 ms of the way from speaker to microphone.
const TAPS: usize = 2048;
/// Loudness is compared in blocks of 4 ms.
const BLOCK: usize = 64;
/// The echo is looked for up to 480 ms late.
const LAGS: usize = 120;
/// A second of loudness is lined up.
const ENV: usize = 250;
/// How much of the far side is kept: the latest echo the filter can be asked about.
const HIST: usize = LAGS * BLOCK + TAPS + WIN;
/// The far side counts as sounding above this mean square (about -60 dBFS).
const SOUNDING: f32 = 1e-6;
/// How fast the filter learns.
const MU: f32 = 0.3;
/// What a window turned out to hold.
#[derive(Clone, Copy, Debug, Default)]
pub struct Heard {
/// raea's own voice was sounding in it
pub far: bool,
/// something stands clear of raea's own voice (always, when raea is quiet)
pub near: bool,
/// the filter has learned the room: what's left can be trusted
pub sure: bool,
}
pub struct Echo {
far: Vec<f32>,
w: Vec<f32>,
/// the filter behind it, always learning; and for how many windows it has done better, or worse
behind: Vec<f32>,
better: usize,
worse: usize,
pub delay: usize,
mic_env: Vec<f32>,
far_env: Vec<f32>,
/// a delay seen, and how many times in a row
vote: (usize, usize),
/// how much quieter the echo leaves than it came, smoothed
pub erle: f32,
/// windows learned on since the delay was last set
learned: usize,
sure: bool,
windows: usize,
}
impl Default for Echo {
fn default() -> Echo {
Echo { far: vec![0.0; HIST], w: vec![0.0; TAPS], behind: vec![0.0; TAPS], better: 0, worse: 0, delay: 0, mic_env: Vec::new(), far_env: Vec::new(), vote: (0, 0), erle: 1.0, learned: 0, sure: false, windows: 0 }
}
}
fn power(x: &[f32]) -> f32 {
let mut p = 0.0;
for s in x {
p += s * s;
}
p
}
impl Echo {
/// The filter starts over (the echo moved in time, or the room changed).
fn forget(&mut self) {
self.w.fill(0.0);
self.behind.fill(0.0);
(self.erle, self.learned, self.sure, self.better, self.worse) = (1.0, 0, false, 0, 0);
}
/// Where the echo sits: the lag (in blocks) at which the microphone's loudness follows the far side's best.
fn lag(&self) -> Option<usize> {
if self.mic_env.len() < ENV || self.far_env.len() < ENV + LAGS {
return None;
}
let mic = &self.mic_env[self.mic_env.len() - ENV..];
let mean = |x: &[f32]| x.iter().sum::<f32>() / x.len() as f32;
let (mm, mut best) = (mean(mic), (0.6, None));
let mv: f32 = mic.iter().map(|a| (a - mm) * (a - mm)).sum();
for l in 0..=LAGS {
let at = self.far_env.len() - ENV - l;
let far = &self.far_env[at..at + ENV];
let fm = mean(far);
let (mut c, mut fv) = (0.0, 0.0);
for (a, b) in mic.iter().zip(far) {
c += (a - mm) * (b - fm);
fv += (b - fm) * (b - fm);
}
let r = c / (mv * fv).sqrt().max(1e-12);
if r > best.0 {
best = (r, Some(l));
}
}
best.1
}
/// One pass of a filter over a window: what's left of `mic` goes to `out`; returns (left, echo made) as power,
/// each sample's judged before the filter learns from it.
fn pass(far: &[f32], delay: usize, w: &mut [f32], mic: &[f32], learn: bool, out: &mut [f32]) -> (f32, f32) {
let (mut left, mut made) = (0.0, 0.0);
let first = far.len() - mic.len() - delay;
let mut norm = power(&far[first + 1 - TAPS..=first]);
for (n, d) in mic.iter().enumerate() {
let at = first + n;
if n > 0 {
norm += far[at] * far[at] - far[at - TAPS] * far[at - TAPS];
}
let x = &far[at + 1 - TAPS..=at];
let mut y = 0.0;
for (a, b) in w.iter().zip(x) {
y += a * b;
}
let e = d - y;
if learn && norm > SOUNDING {
let g = MU * e / (norm + 1e-3);
for (a, b) in w.iter_mut().zip(x) {
*a += g * b;
}
}
out[n] = e;
left += e * e;
made += y * y;
}
(left, made)
}
/// A window of the microphone and the window of the far side played with it. What's left of the microphone's
/// goes to `out`.
pub fn push(&mut self, mic: &[f32], far: &[f32], out: &mut Vec<f32>) -> Heard {
self.far.drain(..far.len());
self.far.extend_from_slice(far);
for (m, f) in mic.chunks(BLOCK).zip(far.chunks(BLOCK)) {
self.mic_env.push(power(m));
self.far_env.push(power(f));
}
let (m, f) = (self.mic_env.len().saturating_sub(ENV), self.far_env.len().saturating_sub(ENV + LAGS));
self.mic_env.drain(..m);
self.far_env.drain(..f);
self.windows += 1;
out.clear();
out.resize(mic.len(), 0.0);
// is raea's voice in what the filter is asked about, and has the echo moved?
let span = &self.far[self.far.len() - mic.len() - self.delay - TAPS..self.far.len() - self.delay];
let sounding = power(span) / span.len() as f32 > SOUNDING;
let loud = self.far_env[self.far_env.len().saturating_sub(ENV)..].iter().sum::<f32>() / (ENV * BLOCK) as f32 > SOUNDING;
if loud && self.windows % 4 == 0 {
if let Some(l) = self.lag() {
self.vote = if l == self.vote.0 { (l, self.vote.1 + 1) } else { (l, 1) };
// the filter starts 8 ms before where the echo is loudest
let to = l.saturating_sub(2) * BLOCK;
if self.vote.1 >= 3 && to.abs_diff(self.delay) > 2 * BLOCK {
self.delay = to;
self.forget();
}
}
}
if !sounding {
out.copy_from_slice(mic);
return Heard { far: false, near: true, sure: self.sure };
}
// The filter that is used only takes out; a second one behind it never stops learning. When the second
// leaves less (the first hadn't met this sound yet, or the room changed), it becomes the first. The person's
// voice can't be learned as echo that way: it makes the second worse, not better, and the first is untouched.
let (left, made) = Echo::pass(&self.far, self.delay, &mut self.w, mic, false, out);
let mut scratch = vec![0.0; mic.len()];
// (the one behind is judged as it stood before this window, then learns from it: judged while it learns, it
// seems to take out some of any voice, since each sample's correction carries into the next)
let (behind, _) = Echo::pass(&self.far, self.delay, &mut self.behind, mic, false, &mut scratch);
Echo::pass(&self.far, self.delay, &mut self.behind, mic, true, &mut scratch);
// (better only when it also takes most of the sound out: with the person talking nothing can, so a filter
// that chased their voice is never taken up)
let came = power(mic);
self.better = if behind < 0.7 * left && behind < 0.5 * came { self.better + 1 } else { 0 };
self.worse = if behind > 2.0 * left { self.worse + 1 } else { 0 };
// (the person's voice leaves the one behind no better off; a sound the filter hadn't met does, at once)
let misfit = behind < 0.85 * left;
if self.better >= 2 {
self.w.copy_from_slice(&self.behind);
self.better = 0;
} else if self.worse >= 3 {
self.behind.copy_from_slice(&self.w);
self.worse = 0;
}
// clear of the echo: well above what the filter usually leaves of it (four times, and never under a sixteenth),
// and not something the filter behind could have taken out
// (what is louder than the whole echo can't be the echo misjudged, whatever the filter behind makes of it)
let near = (!misfit || left > 2.0 * made) && left > made * (4.0 / self.erle).max(0.06) && left / mic.len() as f32 > SOUNDING;
if !(self.sure && near) {
self.erle = 0.9 * self.erle + 0.1 * (came / left.max(1e-12)).min(1000.0);
}
// a filter gone wrong adds sound: then the microphone's own is what's left
if left > came {
out.copy_from_slice(mic);
}
self.learned += 1;
// a second of its own voice learned, and the echo down by 10 dB (7 dB keeps it, once reached)
self.sure = self.learned >= 32 && self.erle >= if self.sure { 5.0 } else { 10.0 };
Heard { far: true, near, sure: self.sure }
}
}
/// The far side lined up with the microphone, window by window. Both come at their own pace in pieces, so a
/// microphone window waits (a few milliseconds) until the far side that played with it, and the two windows after,
/// have arrived: the echo then always comes after the sound that made it, never before.
pub struct Sides {
rs: Resample,
far: Vec<f32>,
/// how many far samples came before `far[0]`
base: u64,
/// the far sample that plays as the microphone's first is heard
offset: Option<u64>,
mic: u64,
held: VecDeque<(Vec<f32>, Instant)>,
room: Option<f32>,
}
impl Sides {
/// `rate`: the far side's. `room`: a simulated room's gain (checks), in place of a real one.
pub fn new(rate: u32, room: Option<f32>) -> Sides {
Sides { rs: Resample::new(rate, crate::turns::RATE as u32), far: vec![0.0; SPAN + WIN], base: 0, offset: None, mic: 0, held: VecDeque::new(), room }
}
/// More of what went to the speakers.
pub fn far(&mut self, x: &[f32]) {
self.rs.push(x, &mut self.far);
}
/// A window from the microphone.
pub fn mic(&mut self, win: Vec<f32>) {
self.held.push_back((win, Instant::now()));
}
/// The next microphone window whose far side has come, and that far side.
pub fn next(&mut self) -> Option<(Vec<f32>, Vec<f32>)> {
let waited = self.held.front()?.1.elapsed();
let total = self.base + self.far.len() as u64;
let offset = *self.offset.get_or_insert(total);
// where the far side stands as this window ends, and the two windows more the filter is given
let now = offset + self.mic + WIN as u64;
let end = now + 2 * WIN as u64;
if total < end {
// the speakers aren't being fed (they stopped, or never started): quiet stands in
if waited < Duration::from_millis(300) {
return None;
}
self.far.resize(self.far.len() + (end - total) as usize, 0.0);
}
let (mut mic, _) = self.held.pop_front()?;
let at = |i: u64| (i - self.base) as usize;
if let Some(gain) = self.room {
room(&self.far[at(now) - WIN - SPAN..at(now)], gain, &mut mic);
}
let far = self.far[at(end) - WIN..at(end)].to_vec();
self.mic += WIN as u64;
// the far side behind what any later window can ask for goes
let old = at(now).saturating_sub(WIN + SPAN);
if old > 16_000 {
self.far.drain(..old);
self.base += old as u64;
}
Some((mic, far))
}
}
/// A room, for checks with no microphone: what the far side sounds like to a microphone 40 ms and a few surfaces
/// away, at `gain`, added to `mic`. `far` ends where `mic` does and is `SPAN` longer.
pub fn room(far: &[f32], gain: f32, mic: &mut [f32]) {
const WAYS: [(usize, f32); 6] = [(640, 1.0), (688, -0.45), (816, 0.3), (1008, -0.2), (1360, 0.12), (1840, -0.07)];
let first = far.len() - mic.len();
for (n, m) in mic.iter_mut().enumerate() {
let mut e = 0.0;
for (late, by) in WAYS {
e += by * far[first + n - late];
}
*m += gain * e;
}
}
/// How much more of the far side `room` needs than the window it fills.
pub const SPAN: usize = 1840;
#[cfg(test)]
mod tests {
use super::*;
/// Something like speech: noise that swells and falls a few times a second.
fn babble(n: usize, seed: u32) -> Vec<f32> {
let mut s = seed;
(0..n)
.map(|i| {
s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
let noise = (s >> 8) as f32 / (1u32 << 24) as f32 - 0.5;
noise * 0.4 * (0.55 + 0.45 * (i as f32 * 0.0021).sin()) * if (i / 4000) % 3 == 2 { 0.05 } else { 1.0 }
})
.collect()
}
/// Runs `secs` of raea talking in the simulated room, the person talking over it from `over` (a window) on.
fn run(secs: usize, over: Option<usize>) -> (Echo, Vec<Heard>, Vec<f32>) {
let n = secs * 16_000 / WIN;
let far = babble(n * WIN + SPAN, 7);
let person = babble(n * WIN, 99);
let (mut echo, mut heard, mut ratio, mut out) = (Echo::default(), Vec::new(), Vec::new(), Vec::new());
for k in 0..n {
let mut mic = vec![0.0; WIN];
room(&far[k * WIN..(k + 1) * WIN + SPAN], 0.8, &mut mic);
if over.is_some_and(|o| k >= o) {
for (m, p) in mic.iter_mut().zip(&person[k * WIN..]) {
*m += p * 0.8;
}
}
let came = power(&mic);
heard.push(echo.push(&mic, &far[SPAN + k * WIN..SPAN + (k + 1) * WIN], &mut out));
ratio.push(power(&out) / came.max(1e-12));
}
(echo, heard, ratio)
}
#[test]
fn its_own_voice_is_learned_and_taken_out() {
let (echo, heard, ratio) = run(6, None);
// the echo's direct sound is 640 samples late: the filter starts just before it
assert!(echo.delay <= 640 && echo.delay + 256 >= 640, "delay {}", echo.delay);
let sure = heard.iter().position(|h| h.sure).expect("never sure");
assert!(sure < 3 * 16_000 / WIN, "sure only after {sure} windows");
// once sure, nothing is taken for the person, and the echo is down to a twentieth or less in most windows
let after = sure + 16;
// (some windows stand out while the filter in use waits for the one behind; the session also wants them to
// sound like speech, which noise doesn't)
let own = heard[after..].iter().filter(|h| h.far && h.near).count();
assert!(own * 5 <= heard.len() - after, "its own voice taken for the person in {own} of {} windows", heard.len() - after);
let mut late: Vec<f32> = heard[after..].iter().zip(&ratio[after..]).filter(|(h, _)| h.far).map(|(_, r)| *r).collect();
late.sort_by(f32::total_cmp);
assert!(late[late.len() / 2] < 0.05, "half the windows keep more than a twentieth: {}", late[late.len() / 2]);
}
#[test]
fn the_person_talking_over_it_stands_clear() {
let at = 5 * 16_000 / WIN;
let (_, heard, ratio) = run(6, Some(at));
assert!(heard[at - 1].sure);
let over = &heard[at..];
let clear = over.iter().filter(|h| h.near).count();
assert!(clear * 10 >= over.len() * 6, "clear in {clear} of {} windows", over.len());
// (their voice has pauses) and it is left in: most of what came is still there
assert!(ratio[at..].iter().sum::<f32>() / over.len() as f32 > 0.3);
}
#[test]
fn quiet_passes_through() {
let (mut echo, mut out) = (Echo::default(), Vec::new());
let mic: Vec<f32> = (0..WIN).map(|i| (i as f32 * 0.1).sin() * 0.2).collect();
let h = echo.push(&mic, &[0.0; WIN], &mut out);
assert!(!h.far && h.near && out == mic);
}
}
+110
View File
@@ -0,0 +1,110 @@
//! `raea voice`: speech to speech on this computer, for an agent that talks (the app's ideation session). Silero VAD
//! says when the person starts and stops speaking, Parakeet says what they said, and Pocket TTS says the agent's
//! words as they arrive, sentence by sentence. Nothing leaves the computer and nothing is paid for; the models are
//! fetched the first time (about 800 MB) into raea's model folder.
//!
//! `raea voice` is a session over lines of JSON (session.rs has them). `raea voice hear FILE.wav` and
//! `raea voice say "WORDS" -o OUT.wav` are one hearing and one saying, with how long each took.
use std::path::PathBuf;
use std::time::Instant;
use serde_json::json;
pub mod asr;
pub mod audio;
pub mod echo;
pub mod session;
pub mod speak;
pub mod turns;
pub const USAGE: &str = "raea voice [--voice NAME] [--duplex] [--over] [--pause MS] [--from IN.wav] [--to OUT.wav] [--room GAIN] [--fast] | raea voice hear FILE.wav | raea voice say \"WORDS\" -o OUT.wav [--voice NAME]";
pub const ABOUT: &str = "speech in and out on this computer, as lines of JSON on stdin and stdout: what raea.app's Ideate hears and speaks with. While it speaks it doesn't listen, unless --duplex (headphones: it listens all the time) or --over (speakers: its own voice is taken out of the microphone's sound, new and not yet tried across real rooms); --room GAIN is a simulated room for checking --over with files; hear writes a recording's words, say speaks words to a file";
/// A model's download told as it goes, once every 20 MB of each file.
pub fn fetching(emit: fn(serde_json::Value)) -> impl FnMut(&str, u64) {
let mut last = (String::new(), 0u64);
move |file: &str, bytes: u64| {
let mb = bytes / 20_000_000 * 20;
if last.0 != file || last.1 != mb {
last = (file.to_string(), mb);
emit(json!({ "fetch": { "file": file, "mb": mb } }));
}
}
}
/// The word after `name` on the command line.
fn flag(args: &[String], name: &str) -> Option<String> {
args.windows(2).find(|w| w[0] == name).map(|w| w[1].clone())
}
fn quiet(_: serde_json::Value) {}
/// `raea voice hear FILE.wav`: what the file says, with how long loading and hearing took.
fn hear(file: &str) -> anyhow::Result<String> {
let (x, rate) = audio::read_wav(std::path::Path::new(file))?;
let mut heard = Vec::with_capacity(x.len());
audio::Resample::new(rate, turns::RATE as u32).push(&x, &mut heard);
let t = Instant::now();
let mut asr = asr::Asr::load(&raea_sys_ml::models::ensure(&asr::SPEC, &mut fetching(quiet))?)?;
let load_ms = t.elapsed().as_millis() as u64;
let t = Instant::now();
let text = asr.hear(&heard)?;
Ok(json!({ "text": text, "seconds": heard.len() as f64 / turns::RATE as f64, "load_ms": load_ms, "ms": t.elapsed().as_millis() as u64 }).to_string())
}
/// `raea voice say "WORDS" -o OUT.wav`: the words said into a file, with how long the first sound and the whole took.
fn say(text: &str, out: &str, voice: Option<String>) -> anyhow::Result<String> {
use raea_sys_speech::pocket::{Out, Pocket};
let t = Instant::now();
let mut pocket = Pocket::load(&raea_sys_ml::models::ensure(&Pocket::SPEC, &mut fetching(quiet))?)?;
// Pocket's stock voice, as a session's: never the clip the library's own default takes from the person's voice folder
let voice = voice.unwrap_or_else(|| Pocket::VOICES[0].to_string());
pocket.begin("", &voice, 1, 0.7)?;
let load_ms = t.elapsed().as_millis() as u64;
let t = Instant::now();
let (mut sound, mut first_ms) = (Vec::new(), None);
let mut g = pocket.begin(text, &voice, 7, 0.7)?;
while let Some(o) = pocket.step(&mut g)? {
if let Out::Audio(a) = o {
first_ms.get_or_insert(t.elapsed().as_millis() as u64);
sound.extend(a);
}
}
let ms = t.elapsed().as_millis() as u64;
audio::write_wav(std::path::Path::new(out), &sound, speak::RATE)?;
Ok(json!({ "voice": voice, "seconds": sound.len() as f64 / speak::RATE as f64, "load_ms": load_ms, "first_ms": first_ms, "ms": ms }).to_string())
}
pub fn cli(args: &[String]) -> Result<String, String> {
let said = |e: anyhow::Error| format!("raea voice: {e:#}");
match args.get(1).map(String::as_str) {
Some("hear") => hear(args.get(2).ok_or(USAGE)?).map_err(said),
Some("say") => say(args.get(2).ok_or(USAGE)?, &flag(args, "-o").ok_or(USAGE)?, flag(args, "--voice")).map_err(said),
Some("help" | "--help" | "-h") => Ok(format!("usage: {USAGE}\n({ABOUT})")),
Some(a) if !a.starts_with("--") => Err(USAGE.into()),
_ => {
let pause_ms = match flag(args, "--pause") {
Some(p) => p.parse().map_err(|_| "--pause takes milliseconds".to_string())?,
None => 700,
};
let o = session::Opts {
from: flag(args, "--from").map(PathBuf::from),
to: flag(args, "--to").map(PathBuf::from),
voice: flag(args, "--voice"),
duplex: args.iter().any(|a| a == "--duplex"),
over: args.iter().any(|a| a == "--over"),
room: match flag(args, "--room") {
Some(g) => Some(g.parse().map_err(|_| "--room takes a gain, like 0.5".to_string())?),
None => None,
},
fast: args.iter().any(|a| a == "--fast"),
pause_ms,
};
session::run(o).map(|_| String::new()).map_err(|e| {
session::emit(json!({ "error": format!("{e:#}") }));
said(e)
})
}
}
}
+12
View File
@@ -0,0 +1,12 @@
//! `raea-voice`: raea voice on its own (what `raea voice` runs), for a build that needs none of the engine.
fn main() {
let args: Vec<String> = std::iter::once("voice".to_string()).chain(std::env::args().skip(1)).collect();
match raea_app_voice::cli(&args) {
Ok(s) if s.is_empty() => {}
Ok(s) => println!("{s}"),
Err(e) => {
eprintln!("{e}");
std::process::exit(1);
}
}
}
+295
View File
@@ -0,0 +1,295 @@
//! A voice session: lines of JSON in (what to say), lines of JSON out (what was heard, and how the saying goes).
//!
//! in {"say":{"id":"u1","text":"Got it. "}} more of utterance u1's words (send as a model streams them)
//! {"end":"u1"} u1 has all its words
//! {"stop":true} stop talking now
//! {"mute":true|false} stop or start listening
//! {"quit":true} (or the input closing) say what's left, then end
//! out {"fetch":{"file","mb"}} a model downloading, the first time
//! {"ready":{"voice","hears","rate"}} it can hear and speak
//! {"level":-37.5} the microphone's loudness (dBFS), a few times a second
//! {"speech":"began"|"ended"} the person started or stopped speaking
//! {"heard":{"text","seconds","ms"}} what they said, how long they spoke and how long hearing it took
//! {"saying":{"id","first_ms"}} u1's first sound, and how long after its first words came
//! {"word":{"id","i","text"}} a word of u1 starting to sound
//! {"said":{"id"}} u1 was said to its end
//! {"stopped":{"id"}} u1 was cut off (a stop, or the person spoke over it)
//! {"error":"..."}
//!
//! While raea speaks it doesn't listen: a computer's microphone hears its own speakers, and raea would take its own
//! voice for the person interrupting. Words begun before it started are still heard. Two ways to talk over it:
//! `duplex` listens all the time with nothing taken out (headphones), and `over` takes raea's own voice out of what
//! the microphone hears (echo.rs) so speakers work too: what stands clear of it stops raea. `over` is new: it has
//! been checked in a simulated room (`room`), not yet across real rooms, so it isn't the default.
use std::collections::VecDeque;
use std::io::{BufRead, Write};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::mpsc::{channel, RecvTimeoutError};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use serde_json::{json, Value};
use crate::audio::{microphone, microphone_file, Speaker};
use crate::echo::{Echo, Heard, Sides};
use crate::speak::{Say, Words, RATE};
use crate::turns::{Turn, Turns, Vad, WIN};
pub struct Opts {
pub from: Option<PathBuf>,
pub to: Option<PathBuf>,
pub voice: Option<String>,
pub duplex: bool,
/// listen while speaking, with raea's own voice taken out of the microphone's sound
pub over: bool,
/// a simulated room's gain, in place of a real one (checks)
pub room: Option<f32>,
pub fast: bool,
pub pause_ms: usize,
}
pub fn emit(v: Value) {
let mut o = std::io::stdout().lock();
let _ = writeln!(o, "{v}");
let _ = o.flush();
}
/// What a line of input asks for; None for a line that asks nothing known.
pub enum Ask {
Say(Say),
Mute(bool),
Quit,
}
pub fn ask(line: &str) -> Option<Ask> {
let v: Value = serde_json::from_str(line).ok()?;
if let Some(s) = v.get("say") {
return Some(Ask::Say(Say::Text { id: s.get("id")?.as_str()?.to_string(), text: s.get("text")?.as_str()?.to_string() }));
}
if let Some(id) = v.get("end").and_then(Value::as_str) {
return Some(Ask::Say(Say::End(id.to_string())));
}
if v.get("stop").is_some() {
return Some(Ask::Say(Say::Stop));
}
if let Some(m) = v.get("mute").and_then(Value::as_bool) {
return Some(Ask::Mute(m));
}
v.get("quit").map(|_| Ask::Quit)
}
/// dBFS of a window, one decimal.
fn level(win: &[f32]) -> f64 {
let rms = (win.iter().map(|s| s * s).sum::<f32>() / win.len().max(1) as f32).sqrt();
((20.0 * rms.max(1e-6).log10()) as f64 * 10.0).round() / 10.0
}
pub fn run(o: Opts) -> anyhow::Result<()> {
let speaker = Speaker::open(RATE, o.to.clone(), o.fast)?;
let words = Arc::new(Mutex::new(Words::default()));
let talking = Arc::new(AtomicBool::new(false));
let muted = Arc::new(AtomicBool::new(false));
let closing = Arc::new(AtomicBool::new(false));
let hearing = Arc::new(AtomicUsize::new(0));
// the voice
let (say_tx, say_rx) = channel::<Say>();
let (voice_ready, voice_is) = channel();
let (line, w, t, name) = (speaker.line.clone(), words.clone(), talking.clone(), o.voice.clone());
let voice = std::thread::spawn(move || crate::speak::worker(say_rx, line, w, name, t, voice_ready, emit));
// the ears: each turn's sound heard on its own thread, so the microphone is never kept waiting
let (heard_tx, heard_rx) = channel::<Vec<f32>>();
let (ears_ready, ears_are) = channel();
let pending = hearing.clone();
std::thread::spawn(move || {
let loaded = raea_sys_ml::models::ensure(&crate::asr::SPEC, &mut crate::fetching(emit)).and_then(|d| crate::asr::Asr::load(&d));
let mut asr = match loaded {
Ok(a) => {
let _ = ears_ready.send(Ok(()));
a
}
Err(e) => {
let _ = ears_ready.send(Err(e));
return;
}
};
for said in heard_rx {
let t = Instant::now();
match asr.hear(&said) {
Ok(text) => emit(json!({ "heard": { "text": text, "seconds": (said.len() as f64 / crate::turns::RATE as f64 * 100.0).round() / 100.0, "ms": t.elapsed().as_millis() as u64 } })),
Err(e) => emit(json!({ "error": format!("{e:#}") })),
}
pending.fetch_sub(1, Ordering::Relaxed);
}
});
let mut vad = Vad::load(&crate::turns::model(&mut crate::fetching(emit))?)?;
let name = voice_is.recv().map_err(|_| anyhow::anyhow!("the voice stopped before it could speak"))??;
ears_are.recv().map_err(|_| anyhow::anyhow!("the ears stopped before they could hear"))??;
// what's asked, line by line
let (tx, m, c) = (say_tx.clone(), muted.clone(), closing.clone());
std::thread::spawn(move || {
for line in std::io::stdin().lock().lines() {
let Ok(line) = line else { break };
match ask(&line) {
Some(Ask::Say(s)) => drop(tx.send(s)),
Some(Ask::Mute(on)) => m.store(on, Ordering::Relaxed),
Some(Ask::Quit) => break,
None if line.trim().is_empty() => {}
None => emit(json!({ "error": format!("not a line raea voice knows: {}", line.chars().take(120).collect::<String>()) })),
}
}
let _ = tx.send(Say::Close);
c.store(true, Ordering::Relaxed);
});
let (mic_tx, mic_rx) = channel::<Vec<f32>>();
let _mic = match &o.from {
Some(f) => {
microphone_file(f, o.fast, mic_tx)?;
None
}
None => Some(microphone(mic_tx)?),
};
emit(json!({ "ready": { "voice": name, "hears": "parakeet-tdt-0.6b-v3", "rate": RATE } }));
let mut turns = Turns::new(o.pause_ms);
let (mut buf, mut windows, mut mic_done) = (Vec::<f32>::new(), 0usize, false);
let mut quiet_since = Instant::now();
// its own voice taken out of the microphone's sound, unless that's not wanted or there's no clock to line up by
let mut sides = (o.over && !o.duplex && !o.fast).then(|| (Sides::new(RATE, o.room), Echo::default()));
speaker.line.tap.store(sides.is_some(), Ordering::Relaxed);
let mut ready = VecDeque::<(Vec<f32>, Option<Heard>, f64)>::new();
// RAEA_VOICE_TRACE=1: the echo's state every window, for finding out why it was or wasn't stopped
let trace = std::env::var_os("RAEA_VOICE_TRACE").is_some();
// windows in a row that stood clear of its own voice; windows of nothing at all from a real microphone
let (mut over, mut dead) = (0usize, if o.from.is_none() { Some(0usize) } else { None });
loop {
match mic_rx.recv_timeout(Duration::from_millis(10)) {
Ok(piece) => buf.extend(piece),
Err(RecvTimeoutError::Timeout) => {}
Err(RecvTimeoutError::Disconnected) => mic_done = true,
}
while buf.len() >= WIN {
let win: Vec<f32> = buf.drain(..WIN).collect();
let loud = level(&win);
// a microphone raea isn't allowed to use gives nothing at all, with no error: say so, once
if let Some(n) = dead {
dead = win.iter().all(|s| *s == 0.0).then_some(n + 1);
if n + 1 == 3 * crate::turns::RATE / WIN {
emit(json!({ "error": "the microphone is giving no sound at all: allow raea to use it (System Settings > Privacy & Security > Microphone on a Mac), or pick another input" }));
dead = None;
}
}
match &mut sides {
Some((s, _)) => s.mic(win),
None => ready.push_back((win, None, loud)),
}
}
if let Some((s, echo)) = &mut sides {
s.far(&std::mem::take(&mut *speaker.line.far.lock().unwrap()));
while let Some((mic, far)) = s.next() {
let (loud, mut left) = (level(&mic), Vec::new());
let heard = echo.push(&mic, &far, &mut left);
if trace {
let (delay, erle) = (echo.delay, echo.erle);
emit(json!({ "echo": { "delay": delay, "erle": (erle * 10.0).round() / 10.0, "far": heard.far, "near": heard.near, "sure": heard.sure, "left": level(&left), "mic": loud } }));
}
ready.push_back((left, Some(heard), loud));
}
}
while let Some((win, cancelled, loud)) = ready.pop_front() {
windows += 1;
let speaking = talking.load(Ordering::Relaxed);
if speaking {
quiet_since = Instant::now();
}
// its own voice dies away in the room for a moment after the last sample
let own = speaking || quiet_since.elapsed() < Duration::from_millis(250);
let through = o.duplex || cancelled.is_some_and(|h| h.sure);
if muted.load(Ordering::Relaxed) || (own && !through) {
over = 0;
if turns.speaking() {
emit(json!({ "speech": "ended" }));
}
// muted, their words are dropped; talked over by raea, what they had said so far is still heard
if muted.load(Ordering::Relaxed) {
turns.clear();
} else if let Some(said) = turns.cut() {
hearing.fetch_add(1, Ordering::Relaxed);
let _ = heard_tx.send(said);
}
vad.reset();
continue;
}
if windows % 4 == 0 {
emit(json!({ "level": loud }));
}
let mut p = vad.speech(&win)?;
if own && !o.duplex {
// a trace of its own voice can be left, and their voice dips under it between words: windows that
// stand clear of it and sound like speech count up, the others count down, and six up is them
over = if cancelled.is_some_and(|h| h.near) && p >= 0.5 { over + 1 } else { over.saturating_sub(1) };
if trace {
emit(json!({ "own": { "p": (p * 100.0).round() / 100.0, "over": over, "near": cancelled.is_some_and(|h| h.near) } }));
}
if !turns.speaking() && over < 6 {
p = 0.0;
}
}
match turns.push(&win, p) {
Some(Turn::Began) => {
emit(json!({ "speech": "began" }));
if speaking {
let _ = say_tx.send(Say::Stop);
}
}
Some(Turn::Ended(said)) => {
emit(json!({ "speech": "ended" }));
hearing.fetch_add(1, Ordering::Relaxed);
let _ = heard_tx.send(said);
}
None => {}
}
}
// the words whose sound has started
{
let mut w = words.lock().unwrap();
let played = speaker.line.at().0;
while w.told < w.starts.len() && w.told < w.words.len() && played >= w.start_at + (w.starts[w.told] * RATE as f64) as u64 {
emit(json!({ "word": { "id": w.id, "i": w.told, "text": w.words[w.told] } }));
w.told += 1;
}
}
let idle = voice.is_finished() && hearing.load(Ordering::Relaxed) == 0;
if closing.load(Ordering::Relaxed) && idle && (o.from.is_none() || mic_done) {
break;
}
}
speaker.close()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_lines_a_session_takes() {
assert!(matches!(ask(r#"{"say":{"id":"u1","text":"Hello. "}}"#), Some(Ask::Say(Say::Text { id, text })) if id == "u1" && text == "Hello. "));
assert!(matches!(ask(r#"{"end":"u1"}"#), Some(Ask::Say(Say::End(id))) if id == "u1"));
assert!(matches!(ask(r#"{"stop":true}"#), Some(Ask::Say(Say::Stop))));
assert!(matches!(ask(r#"{"mute":true}"#), Some(Ask::Mute(true))));
assert!(matches!(ask(r#"{"quit":true}"#), Some(Ask::Quit)));
assert!(ask(r#"{"sing":"la"}"#).is_none() && ask("not json").is_none());
}
#[test]
fn quiet_and_loud_in_dbfs() {
assert_eq!(level(&[0.0; 512]), -120.0);
assert_eq!(level(&[1.0; 512]), 0.0);
assert_eq!(level(&[0.1; 512]), -20.0);
}
}
+250
View File
@@ -0,0 +1,250 @@
//! The voice: what the agent says, said by Pocket TTS as its words arrive. Text comes in pieces (a model's stream);
//! each whole sentence is said as soon as it's there, so the first sound doesn't wait for the last word. The word
//! clock says when each word starts, for a caption that follows the voice.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, TryRecvError};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use raea_sys_speech::pocket::{Out, Pocket};
use raea_sys_speech::words::Clock;
use serde_json::json;
use crate::audio::Line;
/// Pocket's rate.
pub const RATE: u32 = 24_000;
const TEMPERATURE: f32 = 0.7;
pub enum Say {
/// more of what `id` says
Text { id: String, text: String },
/// `id` has all its words
End(String),
/// stop talking now
Stop,
/// say what's left, then finish
Close,
}
/// The words being said and when each starts, for whoever follows the playback.
#[derive(Default)]
pub struct Words {
pub id: String,
pub words: Vec<String>,
/// seconds into the utterance, for the words whose start is decided
pub starts: Vec<f64>,
/// how many have been told
pub told: usize,
/// the playback position (samples played) its first sample has
pub start_at: u64,
}
/// The sentences `buf` holds whole, taken out of it: up to its last full stop, question or exclamation mark that a
/// space or a line end follows. With `all`, everything.
pub fn whole(buf: &mut String, all: bool) -> Option<String> {
let cut = if all {
buf.len()
} else {
let b = buf.as_bytes();
let ends = |i: usize| matches!(b[i], b'.' | b'!' | b'?') && b.get(i + 1).is_some_and(|c| c.is_ascii_whitespace());
(0..b.len()).rev().find(|i| ends(*i) || b[*i] == b'\n').map(|i| i + 1)?
};
let said: String = buf.drain(..cut).collect();
(!said.trim().is_empty()).then(|| said.trim().to_string())
}
struct Utter {
id: String,
buf: String,
ended: bool,
line: Vec<f32>,
clock: Clock,
asked: Instant,
sounded: bool,
}
struct Voice {
pocket: Pocket,
name: String,
out: Arc<Line>,
words: Arc<Mutex<Words>>,
emit: fn(serde_json::Value),
now: Option<Utter>,
closing: bool,
seed: u64,
}
impl Voice {
fn take(&mut self, m: Say) {
match m {
Say::Text { id, text } => {
if self.now.as_ref().is_none_or(|u| u.id != id) {
*self.words.lock().unwrap() = Words { id: id.clone(), ..Words::default() };
self.now = Some(Utter { id, buf: String::new(), ended: false, line: Vec::new(), clock: Clock::new(RATE), asked: Instant::now(), sounded: false });
}
self.now.as_mut().unwrap().buf.push_str(&text);
}
Say::End(id) => {
if let Some(u) = self.now.as_mut().filter(|u| u.id == id) {
u.ended = true;
}
}
Say::Stop => {
self.out.clear();
if let Some(u) = self.now.take() {
self.words.lock().unwrap().id.clear();
(self.emit)(json!({ "stopped": { "id": u.id } }));
}
}
Say::Close => {
self.closing = true;
if let Some(u) = self.now.as_mut() {
u.ended = true;
}
}
}
}
/// Everything waiting on the channel; false once the other end is gone.
fn drain(&mut self, rx: &Receiver<Say>) -> bool {
loop {
match rx.try_recv() {
Ok(m) => self.take(m),
Err(TryRecvError::Empty) => return true,
Err(TryRecvError::Disconnected) => {
self.take(Say::Close);
return false;
}
}
}
}
/// Says `text` for the utterance `id`; stops early when that utterance is stopped or replaced.
fn say(&mut self, id: &str, text: &str, rx: &Receiver<Say>) -> anyhow::Result<()> {
self.seed = self.seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
let mut g = self.pocket.begin(text, &self.name, self.seed, TEMPERATURE)?;
while let Some(out) = self.pocket.step(&mut g)? {
let Some(u) = self.now.as_mut().filter(|u| u.id == id) else { return Ok(()) };
match out {
Out::Begin(sentence) => u.clock.begin_sentence(&sentence, u.line.len()),
Out::End => u.clock.end_sentence(u.line.len()),
Out::Audio(a) => {
if !u.sounded {
u.sounded = true;
let (played, waiting) = self.out.at();
self.words.lock().unwrap().start_at = played + waiting as u64;
(self.emit)(json!({ "saying": { "id": id, "first_ms": u.asked.elapsed().as_millis() as u64 } }));
}
self.out.queue.lock().unwrap().extend(&a);
u.line.extend_from_slice(&a);
u.clock.advance(&u.line, false);
self.publish();
}
}
self.drain(rx);
}
Ok(())
}
fn publish(&mut self) {
let Some(u) = &self.now else { return };
let mut w = self.words.lock().unwrap();
if w.id == u.id && (w.words.len() != u.clock.words.len() || w.starts.len() != u.clock.starts.len()) {
w.words.clone_from(&u.clock.words);
w.starts.clone_from(&u.clock.starts);
}
}
}
/// The voice's thread: loads Pocket, says `ready` once it can speak, then says what comes down `rx` until it closes.
/// `busy` is up while an utterance is being made or played.
pub fn worker(rx: Receiver<Say>, out: Arc<Line>, words: Arc<Mutex<Words>>, name: Option<String>, busy: Arc<AtomicBool>, ready: std::sync::mpsc::Sender<anyhow::Result<String>>, emit: fn(serde_json::Value)) {
let loaded = (|| {
let dir = raea_sys_ml::models::ensure(&Pocket::SPEC, &mut crate::fetching(emit))?;
let mut pocket = Pocket::load(&dir)?;
anyhow::ensure!(pocket.sample_rate() == RATE, "Pocket TTS speaks at {} Hz, not {RATE}", pocket.sample_rate());
// Pocket TTS's own first voice, never a clip of somebody found on this computer (the library's default
// takes one when it's there): a session speaks in a voice of someone's only when asked to by name
let name = name.unwrap_or_else(|| Pocket::VOICES[0].to_string());
// the voice's state loaded now, not under the first words
pocket.begin("", &name, 1, TEMPERATURE)?;
Ok((pocket, name))
})();
let (pocket, name) = match loaded {
Ok(p) => p,
Err(e) => {
let _ = ready.send(Err(e));
return;
}
};
let _ = ready.send(Ok(name.clone()));
let seed = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos() as u64).unwrap_or(7) | 1;
let mut v = Voice { pocket, name, out, words, emit, now: None, closing: false, seed };
loop {
busy.store(v.now.is_some() || v.out.at().1 > 0, Ordering::Relaxed);
let Some(u) = v.now.as_mut() else {
if v.closing {
return;
}
match rx.recv() {
Ok(m) => v.take(m),
Err(_) => return,
}
continue;
};
let ended = u.ended;
if let Some(text) = whole(&mut u.buf, ended) {
let id = u.id.clone();
if let Err(e) = v.say(&id, &text, &rx) {
emit(json!({ "error": format!("Pocket TTS: {e:#}") }));
v.take(Say::Stop);
}
continue;
}
if ended {
// every word made: the clock decides the last starts, and the utterance is said once it has all played
u.clock.advance(&u.line, true);
let id = u.id.clone();
v.publish();
while v.out.at().1 > 0 && v.now.as_ref().is_some_and(|u| u.id == id) {
std::thread::sleep(Duration::from_millis(15));
v.drain(&rx);
}
if v.now.as_ref().is_some_and(|u| u.id == id) {
v.now = None;
emit(json!({ "said": { "id": id } }));
}
continue;
}
// waiting for the rest of a sentence
match rx.recv_timeout(Duration::from_millis(50)) {
Ok(m) => v.take(m),
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
Err(_) => v.take(Say::Close),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn whole_sentences_are_said_as_they_arrive() {
let mut buf = String::from("Got it. A launch film for the Ridge 2");
assert_eq!(whole(&mut buf, false).as_deref(), Some("Got it."));
assert_eq!(whole(&mut buf, false), None, "half a sentence waits for its end");
buf.push_str(", gritty. Who is it for");
assert_eq!(whole(&mut buf, false).as_deref(), Some("A launch film for the Ridge 2, gritty."));
assert_eq!(whole(&mut buf, true).as_deref(), Some("Who is it for"), "with everything in, what's left is said");
assert_eq!(whole(&mut buf, true), None);
}
#[test]
fn a_number_with_a_point_is_not_a_sentence_end() {
let mut buf = String::from("It costs 2.5 times more");
assert_eq!(whole(&mut buf, false), None);
}
}
+189
View File
@@ -0,0 +1,189 @@
//! Whose turn it is: Silero VAD v5 (MIT) window by window as the microphone comes in, and from it when the person
//! starts speaking and when they've stopped (a pause long enough to be the end of what they were saying).
use std::path::PathBuf;
use anyhow::anyhow;
use ort::session::Session;
use ort::value::Tensor;
pub const RATE: usize = 16_000;
/// Silero's window: 32 ms.
pub const WIN: usize = 512;
const CTX: usize = 64;
/// The silero-vad 5.1.2 package's model.
const URL: &str = "https://github.com/snakers4/silero-vad/raw/v5.1.2/src/silero_vad/data/silero_vad.onnx";
pub fn model(progress: &mut dyn FnMut(&str, u64)) -> anyhow::Result<PathBuf> {
raea_sys_ml::models::ensure_url("silero-vad", "silero_vad.onnx", URL, progress)
}
pub struct Vad {
session: Session,
state: Vec<f32>,
ctx: Vec<f32>,
}
impl Vad {
pub fn load(file: &std::path::Path) -> anyhow::Result<Vad> {
Ok(Vad { session: raea_sys_ml::session(file)?, state: vec![0.0; 2 * 128], ctx: vec![0.0; CTX] })
}
/// How likely this window (WIN samples at 16 kHz) is speech; the state carries on from the last one.
pub fn speech(&mut self, win: &[f32]) -> anyhow::Result<f32> {
let e = |e: ort::Error| anyhow!("silero vad: {e}");
let mut input = self.ctx.clone();
input.extend_from_slice(win);
self.ctx.copy_from_slice(&input[input.len() - CTX..]);
let o = self
.session
.run(ort::inputs![
"input" => Tensor::from_array(([1usize, CTX + WIN], input)).map_err(e)?,
"state" => Tensor::from_array(([2usize, 1, 128], self.state.clone())).map_err(e)?,
"sr" => Tensor::from_array(((), vec![RATE as i64])).map_err(e)?,
])
.map_err(e)?;
let p = o["output"].try_extract_tensor::<f32>().map_err(e)?.1[0];
self.state.copy_from_slice(&o["stateN"].try_extract_tensor::<f32>().map_err(e)?.1[..256]);
Ok(p)
}
pub fn reset(&mut self) {
self.state.fill(0.0);
self.ctx.fill(0.0);
}
}
/// What a window of sound changed.
#[derive(Debug, PartialEq)]
pub enum Turn {
/// the person started speaking
Began,
/// they stopped: everything they said, with a little quiet on either side
Ended(Vec<f32>),
}
/// The turn-taking over window probabilities: speech begins after `ON` windows in a row at 0.5 or more, and ends
/// after `quiet` windows in a row under 0.35 (Silero's own two thresholds).
pub struct Turns {
/// windows of quiet that end a turn
pub quiet: usize,
speaking: bool,
run: usize,
silent: usize,
/// the sound kept: the last PRE windows while nobody speaks, the whole turn while someone does
kept: Vec<f32>,
}
/// Windows of speech in a row that begin a turn (96 ms: a click or a cough is shorter).
const ON: usize = 3;
/// Windows kept from before a turn began (its first sound comes before Silero is sure).
const PRE: usize = 10;
/// A turn is cut off here (a minute), so one never grows without end under steady noise.
const LONGEST: usize = RATE * 60;
impl Turns {
/// `pause_ms`: how long a pause ends the turn.
pub fn new(pause_ms: usize) -> Turns {
Turns { quiet: (pause_ms * RATE / 1000 / WIN).max(1), speaking: false, run: 0, silent: 0, kept: Vec::new() }
}
pub fn speaking(&self) -> bool {
self.speaking
}
/// Forgets a turn under way (the microphone was muted, or raea itself was talking).
pub fn clear(&mut self) {
(self.speaking, self.run, self.silent) = (false, 0, 0);
self.kept.clear();
}
/// The turn under way, as far as it got, when raea itself starts talking over it: half a second or more of it is
/// still the person's words (they began before the agent's greeting reached them), anything shorter is forgotten.
pub fn cut(&mut self) -> Option<Vec<f32>> {
let said = (self.speaking && self.kept.len() >= RATE / 2).then(|| std::mem::take(&mut self.kept));
self.clear();
said
}
/// One more window and how likely it is speech.
pub fn push(&mut self, win: &[f32], p: f32) -> Option<Turn> {
self.kept.extend_from_slice(win);
if !self.speaking {
self.run = if p >= 0.5 { self.run + 1 } else { 0 };
if self.run >= ON {
(self.speaking, self.silent) = (true, 0);
return Some(Turn::Began);
}
let keep = (PRE + self.run) * WIN;
if self.kept.len() > keep {
self.kept.drain(..self.kept.len() - keep);
}
return None;
}
self.silent = if p < 0.35 { self.silent + 1 } else { 0 };
if self.silent < self.quiet && self.kept.len() < LONGEST {
return None;
}
// the closing quiet but for a few windows goes: it's the pause, not the turn
let cut = self.silent.saturating_sub(4) * WIN;
let mut said = std::mem::take(&mut self.kept);
said.truncate(said.len() - cut.min(said.len()));
self.clear();
Some(Turn::Ended(said))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_turn_cut_short_keeps_what_was_said() {
let mut t = Turns::new(700);
assert!(t.cut().is_none());
for _ in 0..40 {
t.push(&[0.1; WIN], 0.9);
}
assert!(t.speaking());
assert!(t.cut().is_some_and(|said| said.len() >= RATE / 2));
assert!(!t.speaking() && t.cut().is_none());
// a moment of it isn't a turn
for _ in 0..ON + 1 {
t.push(&[0.1; WIN], 0.9);
}
assert!(t.speaking() && t.cut().is_none());
}
fn feed(t: &mut Turns, probs: &[(f32, usize)]) -> Vec<Turn> {
let mut out = Vec::new();
for (p, n) in probs {
for _ in 0..*n {
out.extend(t.push(&[0.1; WIN], *p));
}
}
out
}
#[test]
fn a_turn_begins_on_steady_speech_and_ends_on_a_long_pause() {
let mut t = Turns::new(640);
// a click (one window), then half a second of speech, a short pause mid-sentence, more speech, then quiet
let got = feed(&mut t, &[(0.1, 20), (0.9, 1), (0.1, 5), (0.9, 16), (0.1, 8), (0.9, 16), (0.1, 30)]);
assert_eq!(got.len(), 2, "one turn: the click begins nothing, the short pause ends nothing: {got:?}");
assert_eq!(got[0], Turn::Began);
let Turn::Ended(said) = &got[1] else { panic!("{got:?}") };
// what was said: the quiet kept from before, both runs of speech and the pause between, a little closing quiet
let windows = said.len() / WIN;
assert!((16 + 8 + 16 + 4..=16 + 8 + 16 + 4 + PRE + ON).contains(&windows), "{windows} windows");
assert!(!t.speaking());
}
#[test]
fn clearing_forgets_a_turn_under_way() {
let mut t = Turns::new(640);
assert_eq!(feed(&mut t, &[(0.9, 10)]), vec![Turn::Began]);
t.clear();
assert!(feed(&mut t, &[(0.1, 40)]).is_empty(), "nothing ends: nothing was under way");
}
}
+1 -1
View File
@@ -14,7 +14,7 @@ raea-io-assets = { path = "../../io/assets" }
serde_json = "1"
# a project's compositions and components read from their source (docs/projects.feature PJ8)
raea-app-registry = { path = "registry" }
# the project's record of what renders and checks found, which raea next reads (docs/direction.feature DR3)
# the project's record of what renders and checks found, which raea goal next reads (docs/direction.feature DR3)
raea-core-facts = { path = "../../core/facts" }
# a command's words (its arguments that aren't flags or their values), read as raea check reads them
raea-app-check = { path = "../check" }
+2 -2
View File
@@ -1,11 +1,11 @@
//! A project's compositions and components, registered by reading its files (docs/projects.feature PJ8),
//! so the raea app, `raea project scan`, `raea doctor` and `raea next` agree on what each file is:
//! so the raea app, `raea project scan`, `raea doctor` and `raea goal next` agree on what each file is:
//! - a composition is each <Composition> a registerRoot registers (its props read from the source, not rendered), or a
//! .tsx's default export with none that no other file imports, registered for it under its file's name (versions
//! NAME-vN.tsx are one composition), sized from its newest render's manifest when it has one;
//! - a component is a .tsx a composition imports, directly or through another.
//! What isn't connected is linted (lint.rs), each with its file and line and the fix. raea-app-workspace runs `scan`
//! for `raea project scan`, `raea doctor`, `raea next` and `raea context`.
//! for `raea project scan`, `raea doctor`, `raea goal next` and `raea context`.
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
+1 -1
View File
@@ -103,7 +103,7 @@ pub(super) fn lint(reg: &Registry, files: &[File], used_by: &BTreeMap<String, BT
format!("imports {} from outside the project", tilde(&to)),
&match in_shared {
Some(r) => format!("import it by the workspace's name for it: \"@shared/{}\"", r.with_extension("").to_string_lossy().replace(std::path::MAIN_SEPARATOR, "/")),
None => "move it to the workspace's shared/ and import it as @shared/<kind>/<name>, or copy it into the project (raea component add, for raea's sets)".into(),
None => "move it to the workspace's shared/ and import it as @shared/<kind>/<name>, or copy it into the project (raea make component add, for raea's sets)".into(),
},
))
}
+62
View File
@@ -0,0 +1,62 @@
//! A project's client (docs/projects.feature): `raea project tag`, and what a project is filed under.
use super::workspace::*;
use super::*;
/// What a project is filed under in raea cloud (Shane 11-24: raea cloud's tags, not folders inside folders): its
/// client, `project.<name>.client` in .raea/workspace. raea.app files every card `raea show` makes from the folder under
/// it, with a board showing it; a folder naming none is its own client, named for it. Projects don't nest: an old
/// workspace's `parent` is read as "the same client as the parent" and nothing writes it.
pub fn client_of(ws: &Path, name: &str) -> Option<String> {
get(&ws.join(".raea/workspace"), &format!("project.{name}.client")).filter(|c| !c.trim().is_empty())
}
/// `raea project tag [NAME] [--client C | --no-client]`: a project's client set, cleared, or said (NAME: the project
/// this folder is in when left out)
pub(crate) fn tag(name: Option<&str>, client: Option<&str>, clear: bool, json_out: bool) -> R<String> {
let here = std::env::current_dir().map_err(|e| e.to_string())?;
let ws = up(&here, ".raea/workspace").ok_or("not in a workspace: raea workspace init NAME makes one")?;
tag_in(&ws, &here, name, client, clear, json_out)
}
/// `tag` in the workspace at `ws`, from the folder `here`
pub(crate) fn tag_in(ws: &Path, here: &Path, name: Option<&str>, client: Option<&str>, clear: bool, json_out: bool) -> R<String> {
// (both resolved: a folder reached through a link, /var for /private/var, is still the workspace's)
let real = |p: &Path| dunce::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
let ws = real(ws);
let name = match name {
Some(n) => {
let s = slug(n);
if projects(&ws).iter().any(|p| p.0 == s) { s } else if projects(&ws).iter().any(|p| p.0 == n) { n.to_string() } else { return Err(format!("no project {n} in this workspace: raea workspace lists them")) }
}
None => {
let dir = up(here, ".raea/project").map(|d| real(&d)).filter(|d| *d != ws).ok_or("not in a project: name one (raea project tag NAME --client C)")?;
let rel = relative(&ws, &dir);
projects(&ws).into_iter().find(|p| p.1 == rel).map(|p| p.0).ok_or_else(|| format!("{} isn't one of this workspace's projects", dir.display()))?
}
};
let file = ws.join(".raea/workspace");
let key = format!("project.{name}.client");
if clear {
if client_of(&ws, &name).is_some() {
config(Some(&file), &["--unset", &key])?;
commit(&ws, &[".raea/workspace"], &format!("project {name}: no client"))?;
}
} else if let Some(c) = client {
let c = c.trim();
if c.is_empty() {
return Err("a client has a name: --client NAME (--no-client clears it)".into());
}
if client_of(&ws, &name).as_deref() != Some(c) {
set(&file, &key, c)?;
commit(&ws, &[".raea/workspace"], &format!("project {name}: client {c}"))?;
}
}
let now = client_of(&ws, &name);
if json_out {
return Ok(json!({"project": name, "client": now}).to_string());
}
Ok(match now {
Some(c) => format!("{name}: client {c} (raea show files its work under {c}, on {c}'s board)"),
None => format!("{name}: no client named, so its work is filed under one named for it (raea project tag {name} --client NAME names one)"),
})
}
+2 -2
View File
@@ -86,12 +86,12 @@ fn old_controllers(base: &Path, ws: Option<&Path>, out: &mut Vec<Finding>) {
}
}
/// A brief.ts that still keeps tasks in `stages` (docs/plan.feature PL8a): they read, unread, and belong in plan.org.
/// A brief.ts that still keeps tasks in `stages` (docs/plan.feature PL8a): they read, unread, and belong in plan.ts.
fn briefs_with_tasks(base: &Path, out: &mut Vec<Finding>) {
let f = base.join("brief.ts");
let Ok(text) = std::fs::read_to_string(&f) else { return };
if text.lines().any(|l| l.trim_start().starts_with("stages:") || l.trim_start().starts_with("\"stages\":")) {
let says = format!("{}: keeps tasks in `stages`, which raea no longer reads; move each to the project's plan.org (an Org heading under its stage, its mark as TODO, DONE or DROPPED), then delete `stages`", f.display());
let says = format!("{}: keeps tasks in `stages`, which raea no longer reads; move each to the project's plan.ts (a task under its stage, its mark as its keyword: TODO, DONE or DROPPED), then delete `stages`", f.display());
out.push(Finding { says, fix: Fix::No });
}
}
+1
View File
@@ -4,6 +4,7 @@ use std::path::{Path, PathBuf};
use serde_json::json;
mod client;
pub mod doctor;
mod repair;
pub mod next;
+3 -3
View File
@@ -1,4 +1,4 @@
//! `raea next` (docs/skills.feature SK10): the two or three useful next steps for a project, read from its files: the
//! `raea goal next` (docs/skills.feature SK10): the two or three useful next steps for a project, read from its files: the
//! brief (what it still needs, from the raea CLI's brief doctor), the storyboard its modes want, its compositions, and
//! from the project's record (docs/direction.feature DR3) its renders and their checks and what each found. A menu for
//! the agent or the person to pick from; nothing runs.
@@ -97,10 +97,10 @@ pub fn steps(dir: &Path, brief: &Brief, stale: usize) -> Vec<String> {
out
}
/// `raea next`'s text.
/// `raea goal next`'s text.
pub fn text(dir: &Path, brief: &Brief, stale: usize) -> String {
let s = steps(dir, brief, stale);
let mut t = format!("raea next: {}\n", dir.display());
let mut t = format!("raea goal next: {}\n", dir.display());
for (i, line) in s.iter().enumerate() {
t.push_str(&format!("{}. {line}\n", i + 1));
}
+30 -2
View File
@@ -91,8 +91,8 @@ fn doctor_connects_a_projects_files() {
// a controller from before 11-20 is told where its parts go, and kept
let out = doctor::doctor(&["--fix".into(), d.display().to_string()], &[], "0.0.1", &|_| Ok(String::new())).unwrap();
assert!(out.starts_with("APPLIED 2 of 5 fixed") && out.contains("controllers/pace.ts: a controller, which raea no longer reads") && out.contains("taste.ts"), "{out}");
// a brief's old tasks are said to belong in plan.org (docs/plan.feature PL8a), and kept
assert!(out.contains("brief.ts: keeps tasks in `stages`") && out.contains("plan.org"), "{out}");
// a brief's old tasks are said to belong in plan.ts (docs/plan.feature PL8a), and kept
assert!(out.contains("brief.ts: keeps tasks in `stages`") && out.contains("plan.ts"), "{out}");
assert!(d.join("controllers/pace.ts").is_file() && std::fs::read_to_string(d.join("brief.ts")).unwrap().contains("stages"), "nothing of the person's is deleted");
let _ = std::fs::remove_dir_all(&d);
}
@@ -229,3 +229,31 @@ fn a_workspace_0_1_6_broke_is_repaired() {
assert!(status().status.success(), "git status after the repair: {}", String::from_utf8_lossy(&status().stderr));
let _ = std::fs::remove_dir_all(&ws);
}
#[test]
fn a_project_names_its_client() {
// Shane 11-24: projects relate by raea cloud's tags (a client), not by nesting; raea.app files `raea show`'s cards
// under the client the folder names (host/local-cloud/clients.ts)
use crate::client::tag_in;
use crate::workspace::{client_of, new_project_in};
let ws = scratch("client");
crate::workspace::make_workspace(&ws, "Clients", "monorepo").unwrap();
new_project_in(&ws, "Launch", None).unwrap();
new_project_in(&ws, "Teaser", None).unwrap();
assert_eq!(client_of(&ws, "launch"), None);
// named, from inside the project; then by name; cleared
let inside = ws.join("projects/launch/compositions");
assert!(tag_in(&ws, &inside, None, Some("Acme"), false, false).unwrap().contains("client Acme"));
assert_eq!(client_of(&ws, "launch").as_deref(), Some("Acme"));
let j: serde_json::Value = serde_json::from_str(&tag_in(&ws, &ws, Some("Teaser"), Some(" Acme "), false, true).unwrap()).unwrap();
assert_eq!(j, serde_json::json!({"project": "teaser", "client": "Acme"}));
assert!(tag_in(&ws, &ws, Some("nope"), Some("Acme"), false, false).is_err());
assert!(tag_in(&ws, &ws, Some("launch"), Some(" "), false, false).is_err());
tag_in(&ws, &ws, Some("launch"), None, true, false).unwrap();
assert_eq!(client_of(&ws, "launch"), None);
// committed, so the workspace's history has it
let log = std::process::Command::new("git").args(["log", "--format=%s"]).current_dir(&ws).output().unwrap();
let log = String::from_utf8_lossy(&log.stdout);
assert!(log.contains("project teaser: client Acme") && log.contains("project launch: no client"), "{log}");
let _ = std::fs::remove_dir_all(&ws);
}
+24 -7
View File
@@ -5,7 +5,7 @@
use super::*;
use std::process::Command;
const USAGE: &str = "usage: raea workspace [--json] | raea workspace init [NAME] [--layout monorepo|submodules] | raea workspace adopt DIR [--name NAME] [--layout monorepo|submodules]\n raea project [--json] | raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME | raea project scan [DIR] [--json]";
const USAGE: &str = "usage: raea workspace [--json] | raea workspace init [NAME] [--layout monorepo|submodules] | raea workspace adopt DIR [--name NAME] [--layout monorepo|submodules]\n raea project [--json] | raea project new NAME [--storage inline|submodule] [--client NAME] | raea project tag [NAME] [--client NAME | --no-client] [--json] | raea project split NAME [--remote URL] | raea project join NAME | raea project scan [DIR] [--json]";
/// git for raea's own commits. A new Mac has no user.email and a hostname git can't make one from, so every commit
/// failed with "Author identity unknown" and the person's first project was never made. git reads $EMAIL only when
@@ -95,7 +95,7 @@ pub(crate) fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
/// The words of a command that aren't flags or a flag's value.
fn words(args: &[String]) -> Vec<&str> {
raea_app_check::words(args, &["--layout", "--storage", "--name", "--remote"])
raea_app_check::words(args, &["--layout", "--storage", "--name", "--remote", "--client"])
}
// a name as a folder (slug), and the nearest folder holding a marker (up): the registry's, which reads projects with
@@ -344,12 +344,17 @@ fn show_workspace(json_out: bool) -> R<String> {
let file = ws.join(".raea/workspace");
let ps = projects(&ws);
if json_out {
let projects: Vec<_> = ps.iter().map(|(n, p, s)| json!({"name": n, "path": p, "storage": s, "id": get(&file, &format!("project.{n}.id"))})).collect();
return Ok(json!({"path": ws, "id": get(&file, "workspace.id"), "name": get(&file, "workspace.name"), "layout": get(&file, "workspace.layout"), "projects": projects}).to_string());
let projects: Vec<_> = ps.iter().map(|(n, p, s)| json!({"name": n, "path": p, "storage": s, "id": get(&file, &format!("project.{n}.id")), "client": client_of(&ws, n)})).collect();
// the clients its projects name, so a new one joins an existing client rather than a near-twin of it
let mut clients: Vec<String> = ps.iter().filter_map(|(n, _, _)| client_of(&ws, n)).collect();
clients.sort_by_key(|c| c.to_lowercase());
clients.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
return Ok(json!({"path": ws, "id": get(&file, "workspace.id"), "name": get(&file, "workspace.name"), "layout": get(&file, "workspace.layout"), "clients": clients, "projects": projects}).to_string());
}
let mut out = format!("{} ({}, {})\n{}\n", get(&file, "workspace.name").unwrap_or_default(), get(&file, "workspace.id").unwrap_or_default(), get(&file, "workspace.layout").unwrap_or_default(), ws.display());
for (n, p, s) in &ps {
out.push_str(&format!(" {n} {p} {s}\n"));
let c = client_of(&ws, n).map(|c| format!(" client {c}")).unwrap_or_default();
out.push_str(&format!(" {n} {p} {s}{c}\n"));
}
Ok(out.trim_end().to_string())
}
@@ -359,7 +364,15 @@ pub fn project(args: &[String]) -> R<String> {
let w = words(args);
match w.first().copied() {
None => show_project(args.iter().any(|a| a == "--json")),
Some("new") => new_project(w.get(1).ok_or(USAGE)?, flag(args, "--storage")),
Some("new") => {
let name = *w.get(1).ok_or(USAGE)?;
let said = new_project(name, flag(args, "--storage"))?;
match flag(args, "--client") {
Some(c) => Ok(format!("{said}\n{}", tag(Some(name), Some(c), false, false)?)),
None => Ok(said),
}
}
Some("tag") => tag(w.get(1).copied(), flag(args, "--client"), args.iter().any(|a| a == "--no-client"), args.iter().any(|a| a == "--json")),
Some("split") => storage::split(w.get(1).ok_or(USAGE)?, flag(args, "--remote")),
Some("join") => storage::join(w.get(1).ok_or(USAGE)?),
// PJ8: the folder's compositions and components, and what isn't connected
@@ -372,6 +385,9 @@ pub fn project(args: &[String]) -> R<String> {
}
}
pub use super::client::client_of;
pub(crate) use super::client::tag;
fn new_project(name: &str, storage: Option<&str>) -> R<String> {
let here = std::env::current_dir().map_err(|e| e.to_string())?;
let ws = up(&here, ".raea/workspace").ok_or("not in a workspace: raea workspace init NAME makes one")?;
@@ -429,7 +445,8 @@ fn show_project(json_out: bool) -> R<String> {
let file = dir.join(".raea/project");
let ws = up(&dir, ".raea/workspace").filter(|w| *w != dir);
if json_out {
return Ok(json!({"path": dir, "id": get(&file, "project.id"), "name": get(&file, "project.name"), "workspace": ws}).to_string());
let client = ws.as_ref().and_then(|w| projects(w).into_iter().find(|p| p.1 == relative(w, &dir)).and_then(|p| client_of(w, &p.0)));
return Ok(json!({"path": dir, "id": get(&file, "project.id"), "name": get(&file, "project.name"), "workspace": ws, "client": client}).to_string());
}
let mut out = format!("{} ({})\n{}\n", get(&file, "project.name").unwrap_or_default(), get(&file, "project.id").unwrap_or_default(), dir.display());
if let Some(ws) = &ws {
+19
View File
@@ -0,0 +1,19 @@
// A set as blender/lightbake.py left it (docs/bake.feature BK0): one <Model> of its meshes, each with its Cycles
// lightmap and the exposure that puts the bake at raea's brightness, from the .lightmaps.json lightbake.py wrote. A
// mesh lightbake.py left unbaked (a metal) is drawn as raea draws it. `raea make bake light --compare` makes media/baked/.
import { staticFile } from "raea";
import { Model } from "raea/3d";
import { Lightmap, StandardMaterial } from "raea/pbr";
export type BakeInfo = { meshes: { mesh: string; material: string[]; map: string; lightmap_exposure: number }[] };
export function Baked({ dir, info }: { dir: string; info: BakeInfo }) {
return (
<Model src={staticFile(`${dir}/set.glb`)}>
{info.meshes.map((m) => (
<Lightmap key={`l-${m.mesh}`} mesh={m.mesh} image={staticFile(`${dir}/lightmaps/${m.map.split("/").pop()}`)} />
))}
{info.meshes.flatMap((m) => m.material.map((mat) => <StandardMaterial key={`m-${mat}`} material={mat} lightmap_exposure={m.lightmap_exposure} />))}
</Model>
);
}
+17
View File
@@ -0,0 +1,17 @@
// The cornell set with Cycles' bounce light baked into its lightmaps by blender/lightbake.py, any sun left live: what raea's
// own bake is measured against (docs/bake.feature BK0). `raea make bake light --compare` makes media/baked/cornell/.
import { AbsoluteFill, Composition, registerRoot } from "raea";
import { Baked } from "./baked";
import { Look } from "./parts/cornell";
import info from "./media/baked/cornell/set.lightmaps.json";
function Shot() {
return (
<AbsoluteFill style={{ background: "#000000" }}>
<Look />
<Baked dir="baked/cornell" info={info} />
</AbsoluteFill>
);
}
registerRoot(() => <Composition id="cornell-cycles" component={Shot} width={1280} height={720} fps={30} durationInFrames={1} />);
+14
View File
@@ -0,0 +1,14 @@
// The cornell set drawn by raea with nothing baked: the "before" frame (docs/bake.feature BK0, apps/lightbake/sets.json).
import { AbsoluteFill, Composition, registerRoot } from "raea";
import { Look, Parts } from "./parts/cornell";
function Shot() {
return (
<AbsoluteFill style={{ background: "#000000" }}>
<Look />
<Parts />
</AbsoluteFill>
);
}
registerRoot(() => <Composition id="cornell" component={Shot} width={1280} height={720} fps={30} durationInFrames={1} />);
+1
View File
@@ -0,0 +1 @@
baked/
Loaded 100 of 2339 files, more files were not shown because too many files have changed in this diff. Show more