Compare commits

..
Author SHA1 Message Date
shinyobjectz f86933383b Judges never pick a harness: a fresh session of the project's own agent, or Clef
Shane, 12-03: nothing judges or checks with another harness, and nothing the agent reads makes it choose a harness,
model or provider. Dutch's plan turn spent about 3 minutes on raea goal judge --by claude (not signed in on a box),
--by clef (no video at plan) and --by kimi (not on PATH), because sdk/goal spawned claude -p and kimi -p itself.

- sdk/cloud/server/critic.ts: each agent session the box server starts gets RAEA_JUDGE_URL and RAEA_JUDGE_TOKEN;
  POST /host/judge {cwd, prompt} starts a fresh session of that same agent (command, sign-in, environment) over ACP
  stdio, allows reads only, and returns what it says. The desktop's local cloud runs the same server.
- sdk/goal: judge() takes no critic. A rule with a piece to watch or hear goes to Clef-Omni, any other to the session's
  critic. raea goal check asks for a verdict itself when it's missing, stale or partial, so the check is the one
  command and the hooks judge with it. BY, critic() and --by are gone.
- raea judge and raea fingerprint read: the same critic through io/clef/src/critic.rs (one call for every caller);
  --by kimi|claude gone, judge eye --read in its place.
- Help, the manual and the Bevy guides name no harness.
2026-12-03 16:43:42 -08:00
shaneandshinyobjectz 80562f9ef7 skills pin: raea-skills fb72c5e for v0.1.17-rc2 (#318)
raea-skills #150-#153: raea show --choose and the workspace MCP line, the component library routing, the playable guide
on Bevy's PBR (#317), and the references regenerated with raea built at main 5f407a1c. SKILLS_STRICT=1
tools/skills.sh check passes on this tree with raea-feed main.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 13:43:14 -08:00
shaneandshinyobjectz 5f407a1cc2 A playable's 3D is drawn by Bevy's own PBR programs (PA11) (#317)
* A playable's 3D is drawn by Bevy's own PBR programs (PA11)

tools/bevy-glsl composes Bevy's mesh, pbr and prepass shaders with Bevy's ShaderCache for a WebGL2 device and
translates them with naga; sdk/playable/bevy/build.sh writes them, with each uniform block's field offsets, into
host/bevy/programs.ts, and apps/playable's test fails when Bevy's shaders or the translator change without a rebuild.
host/bevy.ts replaces three.js's renderer and the tone pass: it reads raea's three.js scene graph and fills Bevy's
blocks as Bevy's render world does (reverse Z, one light cluster, one directional shadow cascade, point and spot
lights, distance fog), draws into half float with 4x MSAA, and maps through TonyMcMapface's table.

A Plane3d now reaches three.js as its one face, not as a box with no depth whose top face three points down.

Against `raea render --frame`: brick-rush portrait frame 90 6.1 -> 4.3 / 255, landscape frame 300 9.8 -> 7.7; a
light test scene 0.7 to 1.3 with fog, point and spot lights and an orthographic camera. The page is about 100 KB
smaller and its first frame is as fast as before in WebKit.

* bevy-glsl gets its layer; one fewer helper and line for the gates

tools/layers.toml places bevy-glsl under tools. The translator's one-use int() helper is folded into its call (a
duplicate of uint()), so programs.from moves while programs.ts stays byte for byte. scene.ts asks geometry.ts's
planeOf for a Plane3d's face in one line, back to 500.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 13:21:21 -08:00
shaneandshinyobjectz b0437d2d08 raea show --choose: pick one of 2 to 6 named options (#314)
* raea show --choose: the person picks one of 2 to 6 named options, each its files

raea-platform home.feature HM9. `raea show --choose "Warm grade" A.png B.png --choose "Cool grade" C.png
--recommend 2`: each --choose names an option and holds the files after it; --recommend N marks the one the agent
would pick (nothing is picked for the person). It goes to the app's host as intent "choose" with the options, and
the pick comes back to the inbox as {"kind":"answer","choice":"Cool grade"}. Refused: one option or more than six, an
option with no files, a file outside the options, --group, --question or --fyi with it, --recommend out of range.
Usage, the native help line and the manual page say so.

* raea show help: the pick's JSON braces escaped in the format string

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 12:47:53 -08:00
shaneandshinyobjectz 230f817543 raea check: contrast reads a text in the colour it has on the frame it's measured at (#316)
A text that keeps its words but changes colour (a step chip lighting up, grey on dark to dark on yellow) is one run,
and a run kept only its last frame's colour. Contrast measures at the run's middle frame, so the swipe-graph film's
chips were read as dark text on a dark chip: 1.2:1 where the pixels measure about 8:1. A run now keeps its colour on
each frame beside its box, and contrast uses the middle frame's (Run::middle_color).

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 12:47:46 -08:00
shaneandshinyobjectz 8dfd71eb92 The component library says when to use each piece: search by how people ask, show NAME, props and upstream names (#315)
An agent asked for "the effect template for composer animations with Claude" found nothing: the catalog had one thin
line per item and the search only read names and that line. Now:

- tools/library-meta.sh (enrich.ts, props.ts, upstream.ts, words.ts, hand.json) matches each of the 609 items by
  content to the upstream component it came from (all 609 match; snapcn's terminal-simulator and text-highlight are
  ui/terminal-session and text/highlight-sweep here) and writes into catalog.json: upstream (a search alias only),
  what (what it draws and how it moves), use_when and avoid_when (upstream's useWhen/avoidWhen in plain words, other
  libraries' names out, pointers rewritten to our category/name or dropped), asked_as (upstream's askedAs plus the
  words people use for its kind: template, effect, composer, chat input, AI prompt, terminal, Claude Code...), props
  (name, type, default and a line each, read from its Props type with the TypeScript parser), length, fps, size,
  aspect and vibe. snapcn's and React Video Editor's items have no when-to-use upstream: hand.json holds those, 134.
- raea make component list WORDS searches names, upstream names and asked_as heavily, what and use_when once; filler
  words are skipped and "template"/"effect"/"preset" alone list the items that are one with how to narrow it.
- raea make component show NAME prints one item in full; list/show --json give the same as JSON.
- sdk/guides/craft/components.md: a template, an effect or a branded screen goes to the library first.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 12:29:09 -08:00
shaneandshinyobjectz 2cbfa8c608 A playable carries Bevy's world as wasm for a game whose rules are raea/ecs systems (#313)
PA12: runtime/ecs builds as a cdylib for wasm32 (src/wasm.rs; sdk/playable/ecs/build.sh: 253 KB, 105 KB gzipped,
no imports) into sdk/playable/src/host/ecs.wasm, with the hash of what it was built from beside it, which apps/playable's
test checks. The lint's walk sees a World made; the export carries the module and its entry loads host/ecs.ts before
the game, so raea/ecs's calls (native.ts ecsCall: the engine's bridge, else the page's) reach Bevy's tables in the page
as they do in the engine. A page that can't make the module keeps raea/ecs's TypeScript tables.

World.copy() is a game's next state (copied with its systems, stepped on its own), and a native store nothing holds
frees its world, so a game's let-go states don't keep theirs. examples/playables/star-catch.tsx is a game whose rules
are three systems on a World; conformance/ecs-wasm.test.ts runs one world's life on the wasm and on the TypeScript
tables and finds them equal. The playable guide shows the pattern.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 12:23:00 -08:00
shaneandshinyobjectz c3765a13bb Playables play sound after the first touch: raea/tone through Tone.js, generated sounds made at export (#312)
PA6: the lint no longer refuses <Audio>. Its walk renders raea/tone's output beside each composition and lists every
generated sound the game describes (raea/asset now keeps them by src). The export makes each one with the asset store a
render uses, compresses it to 64 kb/s AAC, and carries it in the page. It bundles host/sound.ts only for a game with
sound, and Tone.js (the project's `raea add [email protected]`) only for a raea/tone graph, which host/tone.ts builds from
Tone's own classes and replays event by event. Sound starts in the first gesture, pauses while the ad is hidden and
fades at the end card. A frame stepped past on a slow phone still renders its page, so an <Sfx> on it sounds.

brick-rush gets a square-wave blip on the paddle and each brick and a generated crack under each brick (1,844 KB a
page). tools/check.ts reports what played and fails a page whose sound doesn't decode or never plays. The playable
guide covers sound, and that raea's bundled font families are now carried in the page.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 11:39:15 -08:00
shaneandshinyobjectz 5301beb62f Playables: a 2D page carries no three.js, fonts as the native render draws them, a playable goal, exact light rows (#311)
PA15: the host asks for its 3D through one interface (host/draw3d.ts). The export passes three.js's drawer to
start() only when the lint finds a 3D kind, so a 2D game's page drops from about 1,345 KB to 378 KB.

PA8: the page inlines core/fonts' faces under every family the game names that raea aliases, each weight drawn
by the face core/fonts picks. Inter is the page's default.

PA19: core/brief has a playable goal (game, name, networks, orientation, seconds, video). Its deliverables are what
`raea playable` writes, and raea goal's playable pack reads the export's new manifest. `raea playable --name`.
The generated declarations are split in two files to stay under 500 lines each.

PA18: the fast rows rounded a light's rotation to 6 decimals while the full rows wrote it exact, so
RAEA_LIVE3D_CHECK panicked on brick-rush. Rotation and colour columns now pass through exact, and the corpus
no longer skips brick-rush.

tools/check.ts plays with TAP_MS (0 is an instant tap). apps/make's step tests compile again.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 10:55:16 -08:00
shane 5c2a524369 Merge pull request #309 from shinyobjectz/cut-words-captions
Words timed to their sound, captions required, TikTok text boxes
2026-12-03 10:13:16 -08:00
shaneandshinyobjectz 4044e442c2 A playable keeps a tap until a step reads it (#310)
The host gave the game only what was held when a step read the input, so a tap
that went down and up between two steps (33 ms apart at 30 fps, longer on a phone
that drops frames) never reached the game. Found on the cloud's Nataly playable:
instant taps left the attract demo running; held 100 ms they played to the end
card. A press, a finger and a key now count as held for the step after they
went down, and the next step sees them let go.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 10:04:37 -08:00
shinyobjectz d4e39d41f0 taxonomy: HugText and EmojiText are raea's own 2026-12-03 09:50:14 -08:00
shinyobjectz c7e5534d38 Words timed to their sound, captions required, TikTok text boxes
- raea cloud's words (farm POST /v1/words) hear with raea-words on Modal: Parakeet TDT v3, Qwen3-ForcedAligner's
  times, each word widened onto the pauses beside it. On StreetTalk's takes: word ends early 15% (Whisper 57%),
  starts 30 ms median (70), a clipped word timed to where its sound stops (3/24 past it, Whisper 22/24).
  Whisper large-v3 on Groq is the fallback and hears languages Parakeet doesn't.
- The sound check checks a farm render's takes: its manifest names them by blob hash, and offload points them at the
  project's files (localSources). A voice clip it can't find is an error, not a skipped warning.
- The captions check fails a cut with talking and no captions, and a bare stretch of 3 s or more. A text hook may
  hold the opening (5 s) alone: a brief's "captions or a text hook, never both" means not in one frame.
- HugText: text in a box hugging each line, as TikTok draws it. EmojiText draws emoji in the colour emoji faces on
  any machine; the farm image gets fonts-noto-color-emoji.
2026-12-03 09:45:00 -08:00
shaneandshinyobjectz 788444e127 Videoform: its rules in a taste line's shape, and where to start (#208)
Controllers are gone (projects.feature PJ9, #209), so a videoform's mined rules go in its own `rules`, each in a taste
line's shape (words, a check, its values, a level), and `raea check PROJECT` holds a piece to the rules of the
fingerprint that judges it (VF8, a 15-line hook in apps/direction check.rs). docs/videoform.feature gains a short
"Start here": the order (VF1, VF2, VF3, then VF4 with VF12 as the gate before VF1b and VF9-VF11), the new crates, the
three hooks into what exists and the bench. docs/fingerprint.md records decision 6: Pro and Studio's monthly pool of
clef checks and content intelligence.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 08:07:40 -08:00
shaneandshinyobjectz 5b72d2e4dc raea cloud: a 540p proxy of every library video, made on Modal and kept by hash (IG14-IG16) (#306)
sdk/cloud/deploy/modal/proxy.py is raea cloud's proxy maker, its own Modal app (raea-proxy) beside the
indexer so it deploys without the indexer's bundle: a video fetched from the address its index job uses,
hashed as it comes, and made 540p H.264 (CRF 28, a keyframe a second, AAC 96k, faststart), then written
through the Worker's /u/<prefix>/<file-sha> with a ticket for the workspace's proxies alone. A hash already
kept isn't made again; an original that light is its own proxy. Deployed 12-02 as raea-proxy v1.

docs/cloud-ingest.feature IG14-IG16: the proxy made once from the index's download, people watch it, and
agents search by content, look and cut from proxies and fetch originals only for the master.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-02 22:43:25 -08:00
shaneandshinyobjectz 33d34e51b5 raea cloud's Sprite server asks raea's version once at start without blocking (#307)
It asked raea --version synchronously when it began listening, and on a
request when it hadn't yet: on a Sprite whose disk was cold that held every
request, health included, for about 6 s, and after the restarts of 12-02 up
to its 20 s timeout, which also left the version "unknown" for good. Now it
is asked once, off the event loop (2 min at most); /v1/health waits up to
3 s for it, then says "reading", and the start-up line comes once it's known.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-02 21:49:45 -08:00
shaneandshinyobjectz 7cd22cecfc raea-web in Safari: a let holding a texture or sampler is inlined before a shader module is made (#308)
Safari's WGSL holds to the spec (a let can't hold a texture or sampler; Chrome's Tint lets it through). Bevy's PBR
shaders do it in every mesh with UVs, so raea-web drew nothing in Safari: "Fragment module is invalid" for any
sphere or model. @raea/web's loadRaea now patches GPUDevice.createShaderModule once (sdk/web/src/wgsl.ts) to inline
those lets through the rest of their block, so the released engine (web-ad67361) draws in Safari 27: checked in
Ideate's 3D scene via safaridriver (spheres, shadows, fog, point lights). Unit tests: sdk/web/test/unit/wgsl.test.ts.
The vendored bevy_pbr shaders could be fixed at the source with the next web build (30 sites).

Co-authored-by: shinyobjectz <[email protected]>
2026-12-02 21:46:10 -08:00
shaneandshinyobjectz 76e6b00e04 Cloud: a turn's end is read from the agent's own session, not the newest one on its sign-in (#305)
Agents on one sign-in share a home on the Sprite. The watcher read the home's newest transcript, so one chat's last
message ended every other turn running beside it, with nothing said: three of ten chats run two at a time ended
mid-work. The transcript is now the one of the ACP session the socket is on, read off its own messages, and nothing is
said before a session is known. Claude's Stop hook file is shared the same way: while two agents on one sign-in are
open, it is not read.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-02 01:10:21 -08:00
shaneandshinyobjectz 88cacbe7f7 A cloud box comes with ffmpeg and the PDF tools (#304)
Every agent looked for them, searched the disk, then installed them with apt at each project's start; the montage check reads frames with ffmpeg too.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 23:20:54 -08:00
shaneandshinyobjectz 4fd7210cfe Farm: a job's files are listed 32 at a time, and a slow start says where it went (#303)
Each file's stat is a trip to the volume: one after another, 511 files took 9.7 s at each end of every job. A job that drew nothing took 46 s; it takes 16 s.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 23:05:49 -08:00
shaneandshinyobjectz 06a48730d1 A box says a Claude agent's turn has ended from its Stop hook (#302)
The hook is written into the socket's own settings and touches a file the box watches; as with a transcript's end, it's said only when nothing the agent started still runs.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 21:53:29 -08:00
shaneandshinyobjectz 28d89f8ffd Goal check: montage reads frames from a file, and keeps its findings beside the video (#301)
* The montage pack reads a video's frames from a file, not down a pipe

13 MB of small frames through the pipe took 9.7 s of a 35 s cut's read on a cloud box; into a file, 4.6 s.

* A video's montage findings are kept beside it, measured again when it or its beats change

Reading a 35 s cut's frames took 7 s each time the goal was checked, on files that hadn't changed.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 21:40:48 -08:00
shaneandshinyobjectz 7b8317764a A made video's floor report is kept beside it, measured again only for cause (#300)
The measure took 26 s a cut and ran again on the same file at publish and at done. A kept report with an error is always measured again: what it names can be put right without the video changing.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 20:59:21 -08:00
shaneandshinyobjectz c69e28fac3 A box says when its agent's turn has ended: its transcript ended a step and nothing of its own still runs (#299)
Gemini wrote its last message without answering session/prompt, and the run stayed open 45 minutes until the idle agent was ended, read as cut off and started again. A step with no tool call is also how it waits on a job in the background (123 of 131 in one run), so the agent's processes are read with it.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 20:39:50 -08:00
shaneandshinyobjectz 83da71b62d A video's scene reading is kept beside it, and a kept reading isn't the work changing (#298)
A cut checked at its render was read again at publish and again at done, 30 s a file each time: a done check of 11 files took 334 s. And a done check that heard a cut's words wrote them beside it, so the critic's verdict of a minute before read as older than the work and every says rule failed again.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 19:01:29 -08:00
shaneandshinyobjectz 4d896d2b2f One size is one size however it's told: a name's 9x16, a 1080x1920 video, never a still (#297)
Told by pixels alone, an ad named _9x16 beside its own 1080x1920 renders and a 540x960 still read as three sizes, and an agent with one size made couldn't stop for its sign-off.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 18:43:59 -08:00
shaneandshinyobjectz d4d13925fa Farm: scene frames in parallel, 32 warm containers a video (#296)
* The farm reads a cut's scene frames on containers of their own, side by side

They went through the API's one core one after another inside its event loop: 70 frames of a 35 s ad took 37-47 s, and for that long every other call waited (a render's start 48 s, /v1/health 41 s, each job's follow). A whole goal check on a 35 s cut: 34 s, from 77-98.

* The farm draws a video on up to 32 containers, kept warm a minute, and says where a slow job's end went

A 35 s 1080x1920 cut: 80 s from the box's call to its file, from 104-160. At 8 containers its parts ran two after another on each; at 2 s idle every render's containers started cold.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 18:22:58 -08:00
shaneandshinyobjectz a8d7263235 A caption over a person's body is a warning; over a face or what the shot shows it stays an error (#295)
Two people fill a 9:16 interview frame, and each caption's clearest place is a different one: an agent spent hours cropping shots and rendering again to clear errors that a steady caption position can't. The warning still names the clear place.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 18:22:53 -08:00
shaneandshinyobjectz d0f09511fe A file of another codec is refused from its moov box, not after the whole file is read (#294)
On Linux every open of an HEVC file tried the portable backend first, which read the whole file into memory to learn
it wasn't H.264 (0.1.16-rc4 on a Sprite: a cold probe of a 1.1 GB interview still took minutes, warm 1.8 s). The
sample entry is read from the moov box first. rotation_of read the whole file for a matrix: the moov box alone.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 12:38:36 -08:00
shaneandshinyobjectz 1a8a7df53d Opening a video, probing it and making its contact sheet no longer read the whole file (#293)
On a cloud Sprite one `raea media probe` of a 1.1 GB 4K interview took 112 s, and its 16-frame sheet 32 s where
ffmpeg alone takes 7 (12-01, measured). Three causes:

- The ffmpeg backend asked ffprobe for every packet's time on each open, and for MP4 and QuickTime ffprobe reads every
  packet to answer: 1 GB read per open, and a sheet opened its file once a frame. The times now come from the file's
  own sample tables (io/ffmpeg mov.rs; the same times as ffprobe's on 45 of 45 real client clips, up to one shift),
  and ffprobe is asked only for the stream's facts. Fragments, other containers and edit lists that do more than set
  a start are asked of ffprobe as before.
- `media probe` decoded the whole sound track to learn its rate, channels and length: read from the track's tables.
- A sheet's frames are read four at a time.

The Sprite's service sets its disks' read-ahead to 16 MB at each start: at the disk's own 256 KB, with each read
answered in about 26 ms, a pass over footage ran at 10 MB/s.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 11:22:11 -08:00
shaneandshinyobjectz ef8ea7563d On Windows a file asked for by its whole path is that file, not a package's name (#278) (#292)
0.1.16-rc2's Windows build failed its own new check: brief.ts importing react found the React raea ships, which was
then asked for again by its path (D:\..\react\index.js) and read as a package named that: "Cannot find package
'D:\...\index.js'". The resolver knew a whole path only by a leading slash.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 09:42:49 -08:00
shaneandshinyobjectz 6716b6b9f0 A Sprite's setup installs the open faces brands are closest to, and box.sh up builds a Sprite just made (#291)
A Sprite had Liberation and DejaVu alone, so every cut's type fell back to Liberation Sans. setup.sh now installs Inter,
Roboto, Open Sans, Lato, Montserrat, Noto, IBM Plex, Bebas Neue and the URW base 35, each when the Ubuntu has it.
box.sh up ended with curl's exit 7 on a Sprite just made (its wait for running agents asked a server that isn't there
yet).

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 09:12:06 -08:00
shaneandshinyobjectz 313ac8ab83 A project's file that imports react finds the React raea ships (#278) (#290)
* A project's file that imports react finds the React raea ships, as raea's own files do (#278)

0.1.15 let raea's own files (sdk/app) find react in the release's one node_modules. A project's file still could not:
brief.ts, or a scene it registers, imports its hooks from "react", a project has no package.json, and the render's
own checks load brief.ts. So a render was applied, then failed with "brief.ts doesn't run: Cannot find package
'react'" and "fix every ERROR above, then render again", on every release through 0.1.16-rc1.

Any file with no node_modules of its own above it now gets the package raea ships (the bundler gives a scene the same
React); a project's own copy still wins, and a package raea doesn't ship is still not found. The release's check of
the built archive renders beside such a brief.ts on every platform.

* The archive's check of a brief.ts that imports react runs on every build, not only on real machines

* node.rs back under the size limit

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 08:41:09 -08:00
shaneandshinyobjectz cdfb043026 clef's second opinion on a cut is a list of pointed picture and sound checks, the faults it found first (#289)
Asked "do the graphics look designed", clef graded Dutch's plain boxes "strong". Asked pointed yes/no checks of the
same cut it found three of them: three or more text boxes at once (0.93), captions, cards and badges all the same
plain box (0.57), the app shown only as a box of text (0.80). Shane, 12-01: "you just have to have them be more
specific or pointed like giving it some list of design checks to answer ... a few catch all checks on visual and
audio design"; "the agent itself is really responsible for design".

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 06:16:58 -08:00
shaneandshinyobjectz 35267727b8 raea goal seen judges a video's design at full size; a project's design is the agent's own (#288)
* raea goal seen judges a video's design at full size, with clef as a second opinion; a project's design is the agent's own within the brand's colours

A contact sheet's tiles show what happens in a cut, never whether its type, captions and cards look good, and it was
the only picture an agent looked at before sign-off. raea goal seen FILE now also writes six frames at full size
(FILE.looks/) and the seen pack holds a video until --look says how its design stands beside a reference. On raea
cloud it prints clef's grades of the whole cut, picture and sound, lowest first, as a second opinion.
A project's AGENTS.md no longer says "never a colour, font or size of your own": the brand's colours and faces are
the palette, and size, weight, shape, layout and motion are designed for the piece.

* skills: raea goal seen's frames at full size and --look (raea-skills #148)

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 06:02:21 -08:00
shaneandshinyobjectz c72717a635 RAEA_MEDIA=ffmpeg encodes with the system's H.264 encoder where ffmpeg has no libx264 (the LGPL build raea ships on Windows: h264_mf), at the bitrate (#279) (#287)
Co-authored-by: shinyobjectz <[email protected]>
2026-11-30 22:15:21 -08:00
shaneandshinyobjectz 0256cb9673 The AppImage's two pinned tools come from raea's own copy when GitHub's download fails (the runner got HTTP 618 three times for v0.1.15-rc1, and the Linux archive waits on it) (#286)
Co-authored-by: shinyobjectz <[email protected]>
2026-11-30 21:57:25 -08:00
shaneandshinyobjectz b9b0d76568 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 (#285)
Co-authored-by: shinyobjectz <[email protected]>
2026-11-30 20:59:20 -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
1817 changed files with 439294 additions and 6776 deletions

No files matched your search

+3
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
+2
View File
@@ -107,5 +107,7 @@ sdk/raea/.scratch-*/
# examples/materials/wear: its house is made by make-house.ts (media/) and baked at render time (assets/wear/)
/examples/materials/wear/media/
/examples/materials/wear/assets/
# a playable example's generated sounds, made beside it the first time it's rendered or exported (raea's asset store)
/examples/playables/assets/
# tools/bevy-parity links each example folder's assets/ to Bevy's checkout at run time (an absolute, per-machine path)
/sdk/raea/bench/bevy-parity/**/assets
Generated
+163 -32
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"
@@ -13801,6 +13820,7 @@ dependencies = [
"fastrand",
"raea-app-check",
"raea-app-double",
"raea-io-clef",
"raea-io-home",
"raea-sys-columns",
"raea-sys-fingerprint",
@@ -13894,8 +13914,6 @@ dependencies = [
"raea-core-facts",
"raea-core-review",
"raea-io-home",
"raea-runtime-cut-plan",
"raea-runtime-goal-plan",
"raea-runtime-lod-plan",
"resvg 0.48.1",
"serde_json",
@@ -13961,7 +13979,10 @@ dependencies = [
name = "raea-app-playable"
version = "0.1.0"
dependencies = [
"base64 0.22.1",
"dunce",
"raea-core-fonts",
"raea-io-assets",
"raea-io-home",
"raea-runtime-bundle",
"regex",
@@ -14319,6 +14340,8 @@ dependencies = [
"raea-app-voice",
"raea-app-workspace",
"raea-bevy-plugins",
"raea-cli-goal",
"raea-cli-refused",
"raea-core-alloc",
"raea-core-animate",
"raea-core-brief",
@@ -14347,6 +14370,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"
@@ -14474,6 +14517,7 @@ version = "0.1.0"
name = "raea-core-shape"
version = "0.1.0"
dependencies = [
"blake3",
"manifold-rust",
"raea-core-fonts",
"raea-core-grow",
@@ -14492,6 +14536,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"
@@ -15033,29 +15086,62 @@ dependencies = [
"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",
@@ -15069,10 +15155,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]]
@@ -15274,7 +15358,6 @@ name = "raea-runtime-calls"
version = "0.1.0"
dependencies = [
"base64 0.22.1",
"bevy",
"image",
"manifold-rust",
"parley",
@@ -15285,6 +15368,7 @@ dependencies = [
"raea-io-net",
"raea-io-trace",
"raea-native",
"raea-runtime-ecs",
"raea-runtime-plugins",
"raea-runtime-wear",
"raea-sys-fonts",
@@ -15314,15 +15398,6 @@ dependencies = [
"raea-io-home",
]
[[package]]
name = "raea-runtime-cut-plan"
version = "0.1.0"
dependencies = [
"raea-core-brief",
"raea-io-soft",
"serde_json",
]
[[package]]
name = "raea-runtime-dom"
version = "0.1.0"
@@ -15359,6 +15434,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"
@@ -15430,6 +15513,7 @@ dependencies = [
"raea-runtime-page",
"raea-runtime-pagestore",
"raea-runtime-react",
"raea-runtime-review",
"raea-runtime-scene",
"raea-runtime-scene3d",
"raea-runtime-sound",
@@ -15446,14 +15530,6 @@ dependencies = [
"wgpu",
]
[[package]]
name = "raea-runtime-goal-plan"
version = "0.1.0"
dependencies = [
"raea-core-brief",
"serde_json",
]
[[package]]
name = "raea-runtime-gpuframe"
version = "0.1.0"
@@ -15520,6 +15596,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"
@@ -15576,12 +15663,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",
@@ -15590,8 +15674,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",
@@ -15643,6 +15727,7 @@ dependencies = [
"raea-core-alloc",
"raea-core-animate",
"raea-core-scene",
"raea-core-shape",
"raea-core-wire",
"raea-io-assets",
"raea-io-media",
@@ -15667,6 +15752,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]]
@@ -15677,6 +15774,7 @@ dependencies = [
"raea-core-program",
"raea-core-review",
"raea-core-scene",
"raea-runtime-kinds",
"raea-runtime-look",
"raea-runtime-scene2d",
"raea-sys-frame",
@@ -15715,6 +15813,7 @@ dependencies = [
"raea-sys-sampler",
"raea-sys-shader",
"raea-sys-share",
"raea-sys-toon",
"serde_json",
]
@@ -16053,6 +16152,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"
@@ -16191,6 +16301,7 @@ dependencies = [
"bevy",
"raea-core-program",
"raea-core-scene",
"raea-core-tables",
"raea-io-media",
"raea-sys-layers",
"raea-sys-shots",
@@ -16412,9 +16523,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",
@@ -16428,6 +16541,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"
@@ -16808,6 +16928,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"
+10 -2
View File
@@ -12,6 +12,7 @@ members = [
"core/ease",
"core/fonts",
"core/program",
"core/tables",
"core/scene",
"core/shape",
"core/meshcheck",
@@ -30,6 +31,7 @@ members = [
"systems/phase",
"systems/shader/wgsl",
"systems/sampler",
"systems/memtally",
"systems/parity",
"systems/shader",
"systems/three-shader",
@@ -41,6 +43,8 @@ members = [
"engine/bevy-world",
"engine/bundle",
"engine/cli",
"engine/cli/goal",
"engine/cli/refused",
"engine/neural",
"engine/light",
"engine/modules",
@@ -123,6 +127,7 @@ members = [
"systems/page-net",
"systems/page-ops",
"systems/frame",
"systems/facetrack",
"systems/engine-shaders",
"systems/shots",
"systems/hold",
@@ -151,6 +156,7 @@ members = [
"systems/look",
"systems/compose",
"systems/material",
"systems/toon",
"systems/mesh",
"systems/post",
"systems/fog",
@@ -172,12 +178,14 @@ 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",
@@ -191,20 +199,20 @@ 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/cut-plan",
"runtime/goal-plan",
"runtime/live",
"runtime/page",
"runtime/appscreen",
"runtime/sound",
"runtime/look",
"runtime/scene",
"runtime/kinds",
"runtime/scene2d",
"runtime/shared",
"apps/ask",
+1 -1
View File
@@ -130,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.
+1 -1
View File
@@ -49,7 +49,7 @@ fn hex(digest: &[u8]) -> String {
digest.iter().take(16).map(|b| format!("{b:02x}")).collect()
}
/// What a file is, cheaply, and the size an ident names (raea-core-ask, so `raea make status` reads the same).
/// 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.
+1 -1
View File
@@ -28,6 +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/make.feature MK2; split out to keep this crate small)
# 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"
+1 -1
View File
@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "`raea hook`'s Stop gate for a `make` job (docs/make.feature MK2): an agent can't end its turn until `raea make status` says the job is done"
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"
+40 -34
View File
@@ -1,8 +1,8 @@
//! raea-app-check-make: the Stop hook's half of `raea make` (docs/make.feature MK2): an agent working in a project whose brief.ts has a
//! `make` job can't end its turn until `raea make status` says the job is done. Cheap when there's no job: the brief's
//! words are read, and only a brief with `make:` is evaluated (by `raea make status`, a child process, so this crate
//! doesn't carry the judge). 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 (PL7's keeper stops the same way).
//! 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};
@@ -12,13 +12,13 @@ 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 brief.ts with a job, at or above `cwd` inside its raea project.
/// 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 std::fs::read_to_string(&p).is_ok_and(|t| t.contains("make:") || t.contains("make :")).then_some(p);
return Some(p);
}
if project.as_deref() == Some(d) {
return None;
@@ -46,37 +46,42 @@ pub fn may_block(guard: &Path, items: &str) -> bool {
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 is done, the job
/// didn't load (never block on raea's own failure), or the same items have blocked it three times already.
/// Each turn's status also brings the job's task in plan.org up to date (`--plan`, docs/make.feature MK3).
/// 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(["make", "status"]).arg(brief.parent()?).args(["--json", "--plan"]).env("RAEA_RECORD", "off").output().ok()?;
let s: Value = serde_json::from_slice(&out.stdout).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/make").join(format!("{:x}", hash(&[session, &brief.display().to_string()])));
if s["done"] == true {
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(&s);
let items = open_items(&r);
if !may_block(&guard, &items) {
return None;
}
Some(format!(
"Not done ({} job, {}): {items}. Keep going: `raea make status` lists what's open; a defect you judge wrong is answered in NOTES.md by its name.",
s["kind"].as_str().unwrap_or("make"),
brief.display()
))
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: what's missing, then each gate that isn't clear.
pub fn open_items(s: &Value) -> String {
let mut items: Vec<String> = s["missing"].as_array().into_iter().flatten().filter_map(|m| m.as_str().map(String::from)).collect();
items.extend(s["gates"].as_array().into_iter().flatten().filter(|g| g["clear"] != true).map(|g| format!("{}{}: {}", g["gate"].as_str().unwrap_or(""), g["of"].as_str().map(|o| format!(" {o}")).unwrap_or_default(), g["says"].as_str().unwrap_or(""))));
/// 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("; ")
}
@@ -86,19 +91,18 @@ mod tests {
use serde_json::json;
fn tmp(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("raea-make-gate-{name}-{}", std::process::id()));
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 only_a_brief_with_a_job_is_held() {
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")), None, "a brief without make is never held");
std::fs::write(d.join("brief.ts"), "export default brief({ title: \"x\", make: kit({ objects: [] }) })").unwrap();
assert_eq!(brief_with_job(&d.join("compositions")).map(|p| p.file_name().unwrap().to_owned()), Some("brief.ts".into()));
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]
@@ -110,10 +114,12 @@ mod tests {
}
#[test]
fn open_items_list_what_is_missing_then_the_gates_that_are_not_clear() {
let s = json!({"missing": ["out/kit/lineup.png"], "gates": [
{"gate": "checks", "of": "scene.tsx", "clear": false, "says": "never rendered"},
{"gate": "critic", "clear": true, "says": "ok"}]});
assert_eq!(open_items(&s), "out/kit/lineup.png; checks scene.tsx: never rendered");
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");
}
}
+22 -9
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 {
@@ -156,7 +163,7 @@ pub fn hook(args: &[String]) -> R<String> {
return Ok(sent.map(|t| json!({"hookSpecificOutput": {"hookEventName": event, "additionalContext": t}}).to_string()).unwrap_or_default());
}
if event == "Stop" {
// what the person sent, and a `make` job that isn't done (docs/make.feature MK2): either keeps the turn going
// 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() });
}
@@ -171,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) {
+2 -1
View File
@@ -213,7 +213,8 @@ pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe,
continue;
}
// 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 color = r.middle_color();
let ratio = if crate::read::native() { crate::read::contrast(video, t, crop, color) } else { raea_sys_measure::contrast(std::path::Path::new(video), t, crop, color) };
let Some(ratio) = ratio else { continue };
measured += 1;
if ratio < 3.0 {
+6 -5
View File
@@ -67,8 +67,8 @@ fn taste_checks_hold_text_to_the_persons_line() {
Taste { form: "text-above", value: 62.0, line: "Captions sit clear of the bottom.".into() },
Taste { form: "text-hold", value: 2.0, line: "Text holds two seconds".into() },
]);
let low = Run { text: "Render anything.".into(), from: 1.0, to: 4.0, box_: [800.0, 800.0, 300.0, 60.0], boxes: vec![[800.0, 800.0, 300.0, 60.0]], color: String::new(), size: 48.0 };
let high = Run { text: "raea".into(), from: 5.0, to: 6.0, box_: [800.0, 300.0, 300.0, 60.0], boxes: vec![[800.0, 300.0, 300.0, 60.0]], color: String::new(), size: 48.0 };
let low = Run { text: "Render anything.".into(), from: 1.0, to: 4.0, box_: [800.0, 800.0, 300.0, 60.0], boxes: vec![[800.0, 800.0, 300.0, 60.0]], colors: vec![], color: String::new(), size: 48.0 };
let high = Run { text: "raea".into(), from: 5.0, to: 6.0, box_: [800.0, 300.0, 300.0, 60.0], boxes: vec![[800.0, 300.0, 300.0, 60.0]], colors: vec![], color: String::new(), size: 48.0 };
let (mut issues, mut passed) = (vec![], vec![]);
taste_text(&rules, &[low, high], 1920.0, 1080.0, &mut issues, &mut passed);
let says: Vec<_> = issues.iter().map(|i| (i.rule, i.p, i.at)).collect();
@@ -267,7 +267,7 @@ fn typing_is_one_run_and_cues_find_their_word() {
#[test]
fn a_caption_is_timed_from_the_first_word_it_shows() {
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 1.0, box_: [0.0; 4], boxes: vec![], color: String::new(), size: 48.0 };
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 1.0, box_: [0.0; 4], boxes: vec![], colors: vec![], color: String::new(), size: 48.0 };
let words: Vec<Word> = [("half", 12.2), ("of", 12.66), ("the", 12.8), ("spend", 12.96)].iter().map(|(t, s)| Word { text: (*t).into(), start: *s, end: *s }).collect();
let (mut issues, mut passed) = (vec![], vec![]);
// on with "of": on time, though "spend" (its first word of weight) is said 0.3 s later
@@ -335,7 +335,7 @@ fn safe_area_tests_the_letters_not_the_box() {
#[test]
fn a_card_sharing_one_word_with_another_line_isnt_held_to_it() {
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 2.0, box_: [0.0; 4], boxes: vec![], color: String::new(), size: 48.0 };
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 2.0, box_: [0.0; 4], boxes: vec![], colors: vec![], color: String::new(), size: 48.0 };
let said = |ws: &[(&str, f64)]| ws.iter().map(|(t, s)| Word { text: (*t).into(), start: *s, end: *s }).collect::<Vec<Word>>();
let words = said(&[("at", 37.9), ("wirestock", 38.2), ("i", 38.9), ("worked", 39.0), ("on", 39.2), ("a", 39.3), ("sora", 39.5), ("campaign", 40.2)]);
let (mut issues, mut passed) = (vec![], vec![]);
@@ -425,10 +425,11 @@ fn things_found_are_findings_and_an_unknown_rule_is_not() {
#[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 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(), colors: vec![], 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]));
}
+36 -2
View File
@@ -43,6 +43,10 @@ pub struct Run {
/// a full-width box is nowhere near x = 0, #89): a text the camera carries (a sign on a panning street) moves
/// through the frame's edges and zones, which only counts against it when no frame shows it clear
pub boxes: Vec<[f64; 4]>,
/// its colour on each of those frames, beside `boxes`: a text can change colour while it reads the same (a step
/// chip lighting up, grey on dark to dark on yellow), and its contrast is its colour on the frame it's measured at
pub colors: Vec<String>,
/// its colour on its last frame
pub color: String,
pub size: f64,
}
@@ -57,6 +61,15 @@ impl Run {
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])
}
/// Its colour on the frame `middle` measures: the one it had there, not the one it ended with.
pub fn middle_color(&self) -> &str {
let n = self.boxes.len();
match self.colors.get(n / 2) {
Some(c) if n > 1 && self.colors.len() == n => c,
_ => &self.color,
}
}
}
/// The brand kit the cut was styled from (brand/ at or above the manifest's or the video's folder, as render finds
@@ -114,18 +127,21 @@ pub fn text_runs(manifest: &Value) -> Vec<Run> {
});
let mut r = match found {
Some(i) => open.remove(i),
None => Run { text: text.clone(), from: t, to: t, box_: b, boxes: Vec::new(), color: String::new(), size: 0.0 },
None => Run { text: text.clone(), from: t, to: t, box_: b, boxes: Vec::new(), colors: Vec::new(), color: String::new(), size: 0.0 },
};
let color = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string();
if text.len() > r.text.len() {
r.boxes.clear();
r.colors.clear();
}
if text.len() >= r.text.len() {
r.text = text;
r.box_ = b;
r.boxes.push(ink.unwrap_or(b));
r.colors.push(color.clone());
}
r.to = t + 1.0 / fps;
r.color = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string();
r.color = color;
r.size = x["size"].as_f64().unwrap_or(0.0);
next.push(r);
}
@@ -294,3 +310,21 @@ pub fn cues(runs: &[Run], words: &[Word], issues: &mut Vec<Issue>, passed: &mut
passed.push(format!("cues: {checked} texts land on their words"));
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn a_text_that_lights_up_is_measured_in_its_colour_at_the_middle() {
// a step chip: grey on dark for six frames, then dark on yellow for four (the same words)
let m = json!({"fps": 10.0, "frames": (0..10).map(|f| json!({"frame": f, "text": [
{"text": "03 MAP", "box": [500, 120, 130, 52], "size": 23, "color": if f < 6 { "rgb(169, 169, 174)" } else { "rgb(10, 10, 11)" }}
]})).collect::<Vec<_>>()});
let runs = text_runs(&m);
assert_eq!(runs.len(), 1);
assert_eq!(runs[0].color, "rgb(10, 10, 11)", "its last colour");
assert_eq!(runs[0].middle_color(), "rgb(169, 169, 174)", "the frame contrast measures is still grey");
}
}
+1 -1
View File
@@ -410,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));
}
+2
View File
@@ -15,6 +15,8 @@ raea-sys-fingerprint = { path = "../../systems/fingerprint" }
raea-sys-fingerprint-use = { path = "../../systems/fingerprint-use" }
# score --ask: each flag asked again of the decision model (docs/ask.feature AK8)
raea-app-double = { path = "../double" }
# the critic a note is read by: a fresh session of the project's own agent (critic.rs)
raea-io-clef = { path = "../../io/clef" }
raea-sys-fingerprint-things = { path = "../../systems/fingerprint-things" }
# the encoders and the columns they make
raea-sys-columns = { path = "../../systems/columns" }
+2 -3
View File
@@ -21,13 +21,13 @@ use std::path::Path;
pub use serve::serve;
pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT [--by kimi|claude] | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh kimi or claude session read a project's pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)";
pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh session of the project's own agent read its pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)";
/// Evaluates a .ts file's default export to its JSON (the CLI's spec host)
pub type Eval = fn(&Path) -> Result<String, String>;
/// The flags each verb takes, and whether each takes a value
pub(crate) const FLAGS: [(&str, bool); 31] = [
pub(crate) const FLAGS: [(&str, bool); 30] = [
("--fp", true),
("--was", true),
("--to", true),
@@ -51,7 +51,6 @@ pub(crate) const FLAGS: [(&str, bool); 31] = [
("--as", true),
("--against", true),
("--profile", true),
("--by", true),
("--ask", true),
("--tally", false),
("--bad", false),
+11 -32
View File
@@ -1,5 +1,5 @@
//! Notes become evidence (docs/fingerprint.feature FP5a, FP5b). `raea fingerprint read PROJECT [--by kimi|claude]`
//! has a fresh agent session read each pinned note on the project's videos into a kind (defect, direction, praise or
//! Notes become evidence (docs/fingerprint.feature FP5a, FP5b). `raea fingerprint read PROJECT` has a fresh session of
//! the project's own agent (its host's critic, raea_io_clef::critic; never one raea or the agent picks) read each pinned note on the project's videos into a kind (defect, direction, praise or
//! both) and an axis from the fingerprint's own axes, kept in the fingerprint's readings.jsonl. Nothing trains on them
//! yet: `raea fingerprint readings --ask N` puts N readings to the person as questions in the app (`raea show
//! --question`, answers to the "fingerprint" inbox), `readings --tally` counts how often the person agreed, and only
@@ -99,30 +99,9 @@ pub fn fold(notes: &mut [Reading], fp: &Fingerprint, ans: &[Value], by: &str) {
}
}
/// One fresh session's words: kimi's or claude's stream, the assistant's text joined
fn ask(by: &str, p: &str) -> Result<String, String> {
let mut c = std::process::Command::new(by);
match by {
"kimi" => c.args(["-p", p, "--output-format", "stream-json"]),
"claude" => c.args(["-p", p, "--output-format", "stream-json", "--verbose", "--allowedTools", ""]),
o => return Err(format!("--by {o}: kimi or claude")),
};
let out = c.output().map_err(|e| format!("couldn't run {by}: {e}"))?;
let mut text = String::new();
for line in String::from_utf8_lossy(&out.stdout).lines() {
let Ok(v) = serde_json::from_str::<Value>(line) else { continue };
let content = if v["role"] == "assistant" { &v["content"] } else if v["type"] == "assistant" { &v["message"]["content"] } else if v["type"] == "result" { &v["result"] } else { continue };
match content {
Value::String(s) => text += s,
Value::Array(a) => a.iter().filter_map(|p| p["text"].as_str()).for_each(|s| text += s),
_ => {}
}
text.push('\n');
}
if text.trim().is_empty() {
return Err(format!("{by} said nothing: {}", String::from_utf8_lossy(&out.stderr).lines().last().unwrap_or("")));
}
Ok(text)
/// One fresh session of the project's own agent, through its host (raea_io_clef::critic): its words
fn ask(cwd: &Path, p: &str) -> Result<String, String> {
raea_io_clef::critic::ask(cwd, p)
}
pub fn readings_of(dir: &Folder) -> Vec<Reading> {
@@ -133,12 +112,12 @@ pub fn write_readings(dir: &Folder, r: &[Reading]) -> std::io::Result<()> {
std::fs::write(dir.dir.join("readings.jsonl"), r.iter().filter_map(|x| serde_json::to_string(x).ok()).map(|l| l + "\n").collect::<String>())
}
/// `raea fingerprint read PROJECT [--by kimi|claude]`
/// `raea fingerprint read PROJECT`
pub(crate) fn read_here(args: &[String], cwd: &Path) -> i32 {
let run = || -> Result<String, String> {
let w = words(args)?;
let project = w.first().map_or(cwd.to_path_buf(), |p| cwd.join(p));
let by = flag(args, "--by").unwrap_or("kimi");
let by = "agent";
let dir = crate::pick::chosen(args, Some(&crate::pick::piece_in(args, cwd))).0;
let fp = dir.read(None).map_err(|e| e.to_string())?;
let mut notes = pinned(&project);
@@ -148,15 +127,15 @@ pub(crate) fn read_here(args: &[String], cwd: &Path) -> i32 {
return Ok(format!("no new pinned notes in {}", project.display()));
}
for chunk in notes.chunks_mut(40) {
let text = ask(by, &prompt(&fp, chunk))?;
let ans = answer(&text).ok_or_else(|| format!("{by} answered no readings JSON"))?;
let text = ask(&project, &prompt(&fp, chunk))?;
let ans = answer(&text).ok_or_else(|| "the critic answered no readings JSON".to_string())?;
fold(chunk, &fp, &ans, by);
eprintln!("read {} notes", chunk.len());
}
let read = notes.iter().filter(|n| !n.kind.is_empty()).count();
kept.extend(notes.into_iter().filter(|n| !n.kind.is_empty()));
write_readings(&dir, &kept).map_err(|e| e.to_string())?;
Ok(format!("{read} notes read into labels by {by}, kept in {}; none trains a head until you've checked them: raea fingerprint readings --ask 50", dir.dir.join("readings.jsonl").display()))
Ok(format!("{read} notes read into labels by a fresh session of the project's agent, kept in {}; none trains a head until you've checked them: raea fingerprint readings --ask 50", dir.dir.join("readings.jsonl").display()))
};
match run() {
Ok(o) => {
@@ -285,7 +264,7 @@ mod tests {
let fp = raea_sys_fingerprint::taxonomy::base("me");
let mut n = vec![Reading { note: "n1".into(), ..Default::default() }, Reading { note: "n2".into(), ..Default::default() }, Reading { note: "n3".into(), ..Default::default() }];
let ans = answer("I read them.\n[{\"id\": \"n1\", \"kind\": \"defect\", \"axis\": \"glitch\"}, {\"id\": \"n2\", \"kind\": \"direction\", \"axis\": \"made up\"}, {\"id\": \"n3\", \"kind\": \"rant\", \"axis\": null}]").unwrap();
fold(&mut n, &fp, &ans, "kimi");
fold(&mut n, &fp, &ans, "agent");
assert_eq!((n[0].kind.as_str(), n[0].axis.as_deref()), ("defect", Some("glitch")));
assert_eq!((n[1].kind.as_str(), n[1].axis.as_deref()), ("direction", None), "an axis the fingerprint hasn't is dropped");
assert_eq!(n[2].kind, "", "a kind it doesn't know is no reading");
+1 -1
View File
@@ -110,7 +110,7 @@ fn shape(expr: &str, out: &Path, meshes: &mut BTreeMap<String, String>) -> R<Val
// 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")?;
}
+18 -73
View File
@@ -1,8 +1,9 @@
//! A judge that is an agent CLI rather than clef-omni: `raea judge DIR --by kimi|claude` (Shane, 11-06: "use claude or
//! kimi cli as the judge"). Each call is a new session, run in DIR with only the sheets to look at (kimi's media tool;
//! claude with Read alone), given the fresh-context judge prompt (sdk/guides/craft/bevy/prompts.md section 3) and
//! never the code or the builder's notes. It answers JSON: the seven scores 0-10, the blind read and every defect named;
//! the pass, done and stall are still decided in code (rubric::pass, progress). `raea judge eye DIR --by kimi` records
//! A judge that is an agent rather than clef-omni (Shane, 11-06: an agent as the judge; 12-03: never a harness raea
//! picks or the agent names): a fresh session of the agent this project runs on, which the host that started it (raea
//! cloud's box, the raea app) offers as RAEA_JUDGE_URL. Each call is a new session, run in DIR with only the sheets to
//! look at, given the fresh-context judge prompt (sdk/guides/craft/bevy/prompts.md section 3) and never the code or
//! the builder's notes. It answers JSON: the seven scores 0-10, the blind read and every defect named;
//! the pass, done and stall are still decided in code (rubric::pass, progress). `raea judge eye DIR --read` records
//! its reading as the eye clef is calibrated against.
use std::path::Path;
@@ -11,10 +12,13 @@ use serde_json::{Map, Value, json};
use crate::rubric::{BAR, scores};
pub const BY: [&str; 2] = ["kimi", "claude"];
/// Whether this session has a critic to ask: where it has, the agent judges; else clef.
pub fn critic() -> bool {
raea_io_clef::critic::here()
}
/// 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/make.feature MK5); none asks the rubric raea judge has always asked.
/// 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),
@@ -125,70 +129,11 @@ pub fn read(kind: Option<&str>, v: &Value) -> (Map<String, Value>, Vec<Value>, V
(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(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(kind, &dir, brief, target);
let mut cmd = match by {
"kimi" => {
let mut c = std::process::Command::new("kimi");
c.args(["-p", &p, "--output-format", "stream-json"]);
c
}
"claude" => {
let mut c = std::process::Command::new("claude");
c.args(["-p", &p, "--allowedTools", "Read", "--output-format", "stream-json", "--verbose"]);
c
}
o => return Err(format!("judge: --by {o}: the judges are clef (the default), {}", BY.join(", "))),
};
let mut child = cmd.current_dir(&dir).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()).spawn()
.map_err(|e| format!("judge: couldn't run {by}: {e} (is the {by} CLI installed and signed in?)"))?;
let mut said = Vec::new();
let mut last = String::new();
for line in std::io::BufReader::new(child.stdout.take().ok_or("judge: no output pipe")?).lines().map_while(Result::ok) {
let Ok(v) = serde_json::from_str::<Value>(&line) else { continue };
said.extend(texts(&v));
let step = match (v["role"].as_str(), v["type"].as_str()) {
(Some("tool") | Some("user"), _) => "looked at a picture".to_string(),
(Some("assistant"), _) | (_, Some("assistant")) => texts(&v).last().map_or_else(|| "thinking".into(), |t| t[..t.floor_char_boundary(100)].to_string()),
_ => continue,
};
if step != last {
eprintln!("judge ({by}): {}", step.replace('\n', " "));
last = step;
}
}
let out = child.wait_with_output().map_err(|e| format!("judge: {by}: {e}"))?;
let text = said.join("\n");
if !out.status.success() && last_verdict(&text).is_none() {
return Err(format!("judge: {by} failed: {}", String::from_utf8_lossy(&out.stderr).lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("no output")));
}
last_verdict(&text).ok_or_else(|| format!("judge: {by} answered no verdict JSON: {}", text.trim().chars().rev().take(300).collect::<String>().chars().rev().collect::<String>()))
}
/// The words in one streamed line: kimi's {role: assistant, content: "..."}; claude's {type: assistant, message:
/// {content: [{type: text, text}]}} and its final {type: result, result}.
fn texts(v: &Value) -> Vec<String> {
let mut out = Vec::new();
if v["role"] == "assistant"
&& let Some(s) = v["content"].as_str()
{
out.push(s.to_string());
}
for c in v["message"]["content"].as_array().into_iter().flatten() {
if c["type"] == "text"
&& let Some(s) = c["text"].as_str()
{
out.push(s.to_string());
}
}
if v["type"] == "result"
&& let Some(s) = v["result"].as_str()
{
out.push(s.to_string());
}
out
/// One fresh judging session of this project's own agent over DIR's sheets, through the host (RAEA_JUDGE_URL): its
/// verdict JSON.
pub fn ask(kind: Option<&str>, dir: &Path, brief: &Value, target: Option<&Path>) -> Result<Value, String> {
let dir = dunce::canonicalize(dir).map_err(|e| format!("judge: {}: {e}", dir.display()))?;
eprintln!("judge: a fresh session of this project's agent is reading the sheets");
let text = raea_io_clef::critic::ask(&dir, &prompt(kind, &dir, brief, target)).map_err(|e| format!("judge: {e}"))?;
last_verdict(&text).ok_or_else(|| format!("judge: the critic gave no verdict JSON: {}", text.trim().chars().rev().take(300).collect::<String>().chars().rev().collect::<String>()))
}
+6 -5
View File
@@ -3,7 +3,7 @@
//! ~/.raea/judge/eye.jsonl. `raea judge calibrate` fits, per category, a line from the judge's score to his
//! (least squares), and says how often the mapped judge's pass agrees with his. The judge gates only once it has 10
//! rounds or more, some passed by the eye and some not, and agrees on 8 in 10 or better; until then `gating` is false and its verdict is advice
//! (clef has rated almost everything acceptable: docs/craft-system.md). `raea judge eye DIR --by kimi|claude` records a
//! (clef has rated almost everything acceptable: docs/craft-system.md). `raea judge eye DIR --read` records a
//! fresh agent session's reading instead (Shane, 11-06), each row saying whose eye it is.
use std::path::PathBuf;
@@ -17,7 +17,7 @@ fn home() -> PathBuf {
}
/// A kind's calibration file: calibration.json for the default rubric, calibration.KIND.json for a `raea make` kind's
/// (docs/make.feature MK6), each fitted on that kind's rounds alone.
/// (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")))
}
@@ -46,9 +46,10 @@ pub fn record(args: &[String]) -> Result<String, String> {
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(kind, by, &dir, &json!({}), None)?;
// the session's agent's reading as the eye (`--read`): a fresh session's scores, and its pass by the same rule in code
if args.iter().any(|a| a == "--read") {
let by = "agent";
let v = crate::agent::ask(kind, &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()));
+10 -9
View File
@@ -2,11 +2,13 @@
//! 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 [--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 DIR [--kind scene|kit|shot] [--brief brief.ts] [--target T.png] [--json] [--dry]
//! raea judge eye DIR composition=6 form=5 ... [--pass yes|no] (or --read: the session's agent's reading as the eye)
//! Who judges is never asked: a fresh session of the project's own agent where its host offers one (agent.rs), else
//! clef-omni.
//! raea judge calibrate [--kind scene|kit|shot] [--json]
//!
//! `--kind` asks a `raea make` job's own rubric (docs/make.feature MK5): a scene's, a kit's or a shot list's categories,
//! `--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,
@@ -16,13 +18,12 @@ 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/make.feature MK6).
/// 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;
use std::path::{Path, PathBuf};
@@ -30,7 +31,7 @@ use raea_core_facts::{Finding, Level, finding};
use raea_runtime_bundle::flag;
use serde_json::{Value, json};
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 raea make job'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)";
pub const USAGE: &str = "raea judge DIR [--kind scene|kit|shot] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR [--read] [CATEGORY=SCORE ...] [--pass yes|no] | judge calibrate [--kind scene|kit|shot] [--json] (a --review folder's sheets judged blind: a fresh session of the project's own agent on the judge prompt where its host offers one, else clef-omni on the frozen rubric; --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> {
@@ -107,12 +108,12 @@ pub fn cli(args: &[String]) -> Result<String, String> {
let brief = brief_of(flag(args, "--brief").as_deref())?;
let target = flag(args, "--target").map(PathBuf::from);
let dry = args.iter().any(|a| a == "--dry");
let by = flag(args, "--by").unwrap_or_else(|| "clef".into());
let by = if agent::critic() { "agent".to_string() } else { "clef".into() };
if by != "clef" {
if dry {
return Ok(agent::prompt(kind, &dir, &brief, target.as_deref()));
}
let v = agent::ask(kind, &by, &dir, &brief, target.as_deref())?;
let v = agent::ask(kind, &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"]}));
}
@@ -190,7 +191,7 @@ fn finish(args: &[String], kind: Option<&str>, dir: &Path, scores: serde_json::M
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 model = if by == "clef" { "@cf/cloudflare/clef-omni".to_string() } else { "the project's agent".to_string() };
let found = findings(&defects, by, advice);
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)});
+2 -2
View File
@@ -32,7 +32,7 @@ pub const SCORES: [Score; 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/make.feature MK5): `raea judge DIR --kind scene|kit|shot`.
/// 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.
@@ -79,7 +79,7 @@ pub fn scores(kind: Option<&str>) -> &'static [Score] {
}
}
/// What a kind's critic is told the bar is (AnyKit's own words, docs/make.feature MK5).
/// 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.
+5 -5
View File
@@ -70,15 +70,15 @@ fn an_agent_verdict_is_read_from_the_end_of_its_thinking() {
assert!(!pass && why[0].starts_with("blocking"));
assert!(crate::agent::last_verdict("no json here").is_none());
// what it saw, as Findings (DR3): a gating judge's blocking defect is an error, an advising one's a warn
let f = &crate::findings(&defects, "kimi", false)[0];
assert_eq!((f.check.as_str(), f.level, f.fix.as_deref(), f.by.as_str()), ("judge.iso", raea_core_facts::Level::Error, Some("model legs"), "raea judge (kimi)"));
let f = &crate::findings(&defects, "agent", false)[0];
assert_eq!((f.check.as_str(), f.level, f.fix.as_deref(), f.by.as_str()), ("judge.iso", raea_core_facts::Level::Error, Some("model legs"), "raea judge (agent)"));
assert!(f.says.starts_with("iso sheet: "), "{}", f.says);
assert_eq!(crate::findings(&defects, "kimi", true)[0].level, raea_core_facts::Level::Warn);
assert_eq!(crate::findings(&defects, "agent", true)[0].level, raea_core_facts::Level::Warn);
}
#[test]
fn each_make_kind_has_its_own_rubric_and_the_default_is_unchanged() {
// docs/make.feature MK5: a kit's categories, a shot list's on the framing sheet alone, the bar said to each
// 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}");
@@ -117,7 +117,7 @@ fn an_agent_critic_is_asked_its_kinds_categories() {
#[test]
fn a_kind_is_calibrated_on_its_own_categories() {
// docs/make.feature MK6
// 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);
+1 -1
View File
@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "raea 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)"
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)
+1 -1
View File
@@ -1,5 +1,5 @@
{
"about": "the bake's test set (docs/bake.feature BK0), for `raea 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",
"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"] },
+6 -6
View File
@@ -1,4 +1,4 @@
//! `raea bake light EDIT.tsx [--composition ID] [--samples N] [--compare DIR]` (docs/bake.feature): raea's own bake of a
//! `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
@@ -16,7 +16,7 @@ use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use std::path::{Path, PathBuf};
pub const USAGE: &str = "raea bake light EDIT.tsx [--composition ID] [--samples N] | raea 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)";
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 {
@@ -136,8 +136,8 @@ pub fn cli(args: &[String]) -> R<String> {
}
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 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 bake light --compare DIR` measures the test set against Cycles".into());
// 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");
@@ -145,7 +145,7 @@ pub fn cli(args: &[String]) -> R<String> {
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 bake light: {} ...", s.name);
eprintln!("raea make bake light: {} ...", s.name);
reports.push(compare::set(s, samples, &out.join(&s.name), fresh)?);
}
if reports.is_empty() {
@@ -154,5 +154,5 @@ pub fn cli(args: &[String]) -> R<String> {
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 bake light: wrote {}", compare::table(&reports), path.display()))
Ok(format!("{}raea make bake light: wrote {}", compare::table(&reports), path.display()))
}
+1 -5
View File
@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "raea make: a scene, kit or shot held to its frozen plan; what's missing and whether it's done, decided in code (docs/make.feature)"
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
@@ -13,10 +13,6 @@ raea-core-brief = { path = "../../core/brief" }
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" }
# a cut job's gates: its client's brief as rules, held over the delivered files (MK25-MK27)
raea-runtime-cut-plan = { path = "../../runtime/cut-plan" }
# a goal job's gates: its commands and a fresh critic's verdict on its words (/goal)
raea-runtime-goal-plan = { path = "../../runtime/goal-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)
+3 -3
View File
@@ -1,6 +1,6 @@
//! The second tier of the gate (docs/make.feature MK4): the `make` set of `raea ask` questions (core/ask
//! 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 status. An
//! (`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.
@@ -10,7 +10,7 @@ use std::path::{Path, PathBuf};
use raea_core_ask::{Calibration, Question};
use serde_json::{Value, json};
/// The ledger as status reads it: every call's ident by id, every answer, and the person's calibrations.
/// 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>,
+9 -9
View File
@@ -1,14 +1,14 @@
//! The plan stop (docs/make.feature MK18, from AnyScene's endpoint/floorplan.py, MIT): before anything is generated,
//! 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 plan [DIR] -> review/plan/floor-plan.png, blockout.tsx, blockout.png, comparison.png, colour/clay sheets
//! 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::make::{Make, Object, Origin};
use raea_core_brief::goal::{Goal, Object, Origin};
use crate::sheet::{Tile, esc, sheet, svg_png};
use crate::shots::raea;
@@ -27,7 +27,7 @@ fn height(o: &Object) -> f64 {
}
/// 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: &Make) -> (Vec<&Object>, [f64; 4]) {
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 {
@@ -40,10 +40,10 @@ pub fn extent(m: &Make) -> (Vec<&Object>, [f64; 4]) {
}
/// 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: &Make) -> Result<String, String> {
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 plan: no object has an `at` (where it stands, in metres: x right, z away from the entrance)".into());
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);
@@ -93,7 +93,7 @@ pub fn floor_svg(m: &Make) -> Result<String, String> {
}
/// 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: &Make) -> String {
pub fn blockout_tsx(m: &Goal) -> String {
let (placed, [x0, z0, x1, z1]) = extent(m);
let mut boxes = String::new();
for o in &placed {
@@ -119,7 +119,7 @@ pub fn blockout_tsx(m: &Make) -> String {
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 plan: 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",
"// 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,
)
@@ -130,7 +130,7 @@ pub fn plan_dir(dir: &Path) -> PathBuf {
}
/// 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: &Make, review: bool) -> Result<String, String> {
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");
@@ -1,18 +1,18 @@
//! Whether a job is done (docs/make.feature MK1), from what's on disk and nothing the agent says: the deliverables, the
//! notes, the record of renders and checks, and the judge's rounds. Pure over a `Job` so it is tested on fixtures.
//! 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::make::{self, Make};
use raea_core_brief::goal::{self, Goal};
use raea_core_facts::{Level, record::Entry};
use serde_json::{Value, json};
/// The heading the notes end with, so the next job (and the skill) learns from this one.
pub const SKILL_HEADING: &str = "What the skill got wrong";
/// Everything status reads, gathered by `lib.rs` (or a test).
/// Everything the gates read, gathered by `lib.rs` (or a test).
pub struct Job<'a> {
pub make: &'a Make,
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
@@ -45,14 +45,14 @@ pub fn round_dir(dir: &Path, round: &Value) -> Option<PathBuf> {
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 == make::Kind::Shot {
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 == make::Kind::Kit {
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()
@@ -140,9 +140,9 @@ 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 {
make::Kind::Kit => "raea render shared/components/KIT/lineup.tsx --review review/r1",
make::Kind::Shot => "raea make framing --out review/r1",
make::Kind::Scene | make::Kind::Cut | make::Kind::Goal => "raea render EDIT.tsx --review review/r1",
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 | goal::Kind::Playable => "raea render EDIT.tsx --review review/r1",
};
return vec![gate("critic", None, false, format!("no round yet: {what}, then raea judge review/r1 --kind {kind} --by claude --brief brief.ts"))];
};
@@ -171,76 +171,32 @@ fn critic(job: &Job, newest: Option<SystemTime>, notes: &str) -> Vec<Value> {
out
}
/// The job's status: what's missing, each gate, the judge's rounds, and whether the agent may stop.
pub fn status(job: &Job) -> Value {
let mut missing = Vec::new();
let mut newest: Option<SystemTime> = None;
for want in make::deliverables(job.make) {
match answered(job.dir, &want) {
Ok(files) => newest = files.iter().filter_map(|f| mtime(f)).chain(newest).max(),
Err(why) => missing.push(why),
}
}
/// 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();
if job.make.kind != make::Kind::Goal && !notes.to_lowercase().contains(&SKILL_HEADING.to_lowercase()) {
missing.push(format!("NOTES.md with a \"{SKILL_HEADING}\" section (one line per thing that cost time; what the guide got wrong for this job)"));
}
let mut gates = checks(job);
gates.extend(lods(job, &notes));
// a cut job: its brief's rules over every delivered file (MK25-MK27), and the person's review its critic; a goal's
let plan = |g: make::Gate| gate(g.name, g.of.as_deref(), g.clear, g.says);
match (&job.make.cut, job.make.kind) {
(Some(c), make::Kind::Cut) => gates.extend(raea_runtime_cut_plan::gates(c, job.dir).into_iter().map(plan)),
(_, make::Kind::Goal) => gates.extend(job.make.goal.iter().flat_map(|g| raea_runtime_goal_plan::gates(g, job.dir)).map(plan)),
_ => gates.extend(critic(job, newest, &notes)),
}
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(make::ROUNDS) as usize;
let capped = job.rounds.len() >= cap;
let stalled = stalled(job.rounds);
let clear = missing.is_empty() && gates.iter().all(|g| g["clear"] == true);
let mut why = Vec::new();
if capped && !clear {
why.push(format!("capped: {} critic rounds, the most this job gets; delivered with what's still missing", job.rounds.len()));
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 && !clear {
why.push("stalled: three rounds without beating the best before them; delivered with what's still missing".into());
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,
"done": clear || capped || stalled,
"short": !clear && (capped || stalled),
"missing": missing,
"clear": clear,
"short": short,
"gates": gates,
"judge": {"rounds": job.rounds.len(), "cap": cap, "passesInARow": advice["passesInARow"], "changeApproach": advice["stall"], "again": advice["again"]},
"plan": make::doctor(job.make),
"files": {"deliverables": make::deliverables(job.make), "previews": make::previews(job.make)},
"advice": said,
"why": why,
})
}
/// The status for a person or an agent to read.
pub fn text(s: &Value) -> String {
let mut t = vec![format!("make: {} {}", s["kind"].as_str().unwrap_or("?"), if s["done"] == true { if s["short"] == true { "delivered short" } else { "done" } } else { "not done" })];
for w in s["why"].as_array().into_iter().flatten() {
t.push(format!(" {}", w.as_str().unwrap_or("")));
}
for (key, head) in [("plan", "plan:"), ("missing", "missing:"), ("advice", "advice (raea ask, not calibrated yet):")] {
let items: Vec<&str> = s[key].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
if !items.is_empty() {
t.push(head.into());
t.extend(items.iter().map(|i| format!(" {i}")));
}
}
t.push("gates:".into());
for g in s["gates"].as_array().into_iter().flatten() {
let of = g["of"].as_str().map(|o| format!(" {o}")).unwrap_or_default();
t.push(format!(" {} {}{of}: {}", if g["clear"] == true { "ok " } else { "open" }, g["gate"].as_str().unwrap_or(""), g["says"].as_str().unwrap_or("")));
}
let j = &s["judge"];
if s["kind"] != "goal" { t.push(format!("judge: {} of {} rounds, {} passes in a row{}", j["rounds"], j["cap"], j["passesInARow"], if j["changeApproach"] == true { "; the same defect keeps coming back: change the approach for that part, not the dose" } else { "" })); }
t.join("\n")
}
+11 -11
View File
@@ -1,4 +1,4 @@
//! A kit's steps (docs/make.feature MK10-MK12, from AnyKit): every object's reference made in one style from the
//! 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.
@@ -11,7 +11,7 @@
use std::path::{Path, PathBuf};
use raea_core_brief::make::{Make, Object};
use raea_core_brief::goal::{Goal, Object};
use serde_json::{Value, json};
use crate::sheet::{Tile, sheet};
@@ -27,12 +27,12 @@ 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 Make, only: &[String]) -> Vec<&'a Object> {
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: &Make, o: &Object) -> String {
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}")
@@ -105,7 +105,7 @@ pub fn refs_dir(dir: &Path) -> PathBuf {
}
/// Every object's reference, made from the style images (`references`) in the plan's style; then the sheet.
pub fn refs(dir: &Path, m: &Make, only: &[String], model: Option<&str>, dry: bool) -> Result<String, String> {
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());
}
@@ -144,7 +144,7 @@ pub fn refs(dir: &Path, m: &Make, only: &[String], model: Option<&str>, dry: boo
}
/// 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: &Make) -> Result<String, String> {
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
@@ -162,7 +162,7 @@ pub fn sheet_refs(dir: &Path, m: &Make) -> Result<String, String> {
}
/// The flow that sends one reference to both generators, each at its face limit.
pub fn gen_flow(m: &Make, o: &Object, reference: &Path, tripo: &str, meshy: &str) -> Value {
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;
@@ -178,7 +178,7 @@ pub fn gen_dir(dir: &Path, id: &str) -> PathBuf {
}
/// Every reference to both generators: out/kit/gen/ID/tripo.glb and meshy.glb.
pub fn generate(dir: &Path, m: &Make, only: &[String], tripo: &str, meshy: &str, dry: bool) -> Result<String, String> {
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) {
@@ -229,7 +229,7 @@ pub fn picks(dir: &Path) -> serde_json::Map<String, Value> {
}
/// One object's pick and why, recorded (MK11).
pub fn choose(dir: &Path, m: &Make, id: &str, generator: &str, why: &str) -> Result<String, String> {
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"));
}
@@ -256,7 +256,7 @@ fn triangles(glb: &Path) -> Result<u64, String> {
/// 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: &Make, only: &[String]) -> Result<String, String> {
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) {
@@ -284,7 +284,7 @@ pub fn prep(dir: &Path, m: &Make, only: &[String]) -> Result<String, String> {
// 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/make.feature)", "route": "gen", "generator": generator, "model": model, "why": pick["why"], "prompt": o.prompt, "reference": format!("out/kit/refs/{}.png", o.id),
"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())?;
+8 -8
View File
@@ -1,4 +1,4 @@
//! The kit's sheets and its landing (docs/make.feature MK11, MK13): the pick sheet (each object's reference beside
//! 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.
@@ -8,7 +8,7 @@
use std::path::{Path, PathBuf};
use raea_core_brief::make::{Make, Object};
use raea_core_brief::goal::{Goal, Object};
use serde_json::{Value, json};
use crate::kit::{gen_dir, objects, picks};
@@ -53,7 +53,7 @@ pub fn draw(model: &Path, h: f64) -> Result<(PathBuf, PathBuf), String> {
}
/// 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: &Make, only: &[String]) -> Result<String, String> {
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);
@@ -99,7 +99,7 @@ pub fn component_name(id: &str) -> String {
pub fn component(o: &Object, why: &str) -> String {
let n = component_name(&o.id);
format!(
"// raea 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",
"// 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,
@@ -109,7 +109,7 @@ pub fn component(o: &Object, why: &str) -> String {
/// 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: &Make, kit: &str) -> String {
pub fn lineup(m: &Goal, kit: &str) -> String {
let mut imports = String::new();
let mut parts = String::new();
let mut x = 0.0;
@@ -176,7 +176,7 @@ fn copy(a: &Path, b: &Path) -> Result<(), String> {
/// 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: &Make, name: Option<&str>, to: Option<&str>) -> Result<String, String> {
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()))?;
@@ -214,10 +214,10 @@ pub fn land(dir: &Path, m: &Make, name: Option<&str>, to: Option<&str>) -> Resul
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/make.feature MK13)"}});
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 make status` counts (core/brief deliverables)
// 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()))
+60 -61
View File
@@ -1,27 +1,27 @@
//! `raea make`: a scene, kit or shot made to its frozen plan (`make` on brief.ts, core/brief make.rs) and held to the
//! review loop (docs/make.feature). `status` decides, in code, what's missing and whether the agent may stop; the Stop
//! hook (apps/check hook.rs) asks it at the end of every turn.
//! 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 make status [DIR] [--json] [--plan] (--plan: the gates as check lines in plan.org, MK3)
//! raea make plan|refs|sheet refs|gen|pick-sheet|pick|prep|kit|framing|lenschart ... (the steps, USAGE)
//! 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 plan;
pub mod sheet;
pub mod shots;
pub mod status;
pub mod gates;
use std::path::{Path, PathBuf};
use raea_core_brief::make::Make;
use raea_core_brief::goal::Goal;
use serde_json::Value;
pub const USAGE: &str = "raea make status [DIR] [--json] [--plan] (a scene, kit, shot, cut or goal held to its plan, `make` on brief.ts: what's missing, each gate (renders and checks, raea ask's calibrated questions, the critic on the kind's rubric), the judge's rounds, and whether it's done, decided in code; --plan writes the gates as check lines under the job's task in plan.org; the agent's Stop hook holds it there)
raea make judge [DIR] [--by claude|kimi] (a goal job: a fresh critic, which only reads, judges each `says` rule; review/goal.judge.json)
raea make plan [DIR] [--no-review] (the plan stop: review/plan/floor-plan.png, a grey-box blockout from the entrance and its review sheets, comparison.png beside reference 0)
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/)
@@ -48,23 +48,45 @@ pub fn brief_path(dir: &Path) -> Option<PathBuf> {
None
}
/// Whether a brief.ts has a job at all, read from its words: cheap enough for a hook at every turn's end, so the
/// 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_make(brief: &Path) -> bool {
std::fs::read_to_string(brief).is_ok_and(|t| t.contains("make:") || t.contains("make :"))
pub fn has_goal(brief: &Path) -> bool {
std::fs::read_to_string(brief).is_ok_and(|t| t.contains("goal:") || t.contains("goal :"))
}
/// The plan from brief.ts, evaluated by `raea spec FILE --as brief` (the module runs; Rust checks it against core/brief).
pub fn read_make(brief: &Path) -> Result<Option<Make>, String> {
/// 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("make") {
None | Some(Value::Null) => Ok(None),
Some(m) => serde_json::from_value(m.clone()).map(Some).map_err(|e| format!("{}: make: {e}", brief.display())),
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(", "))),
}
}
@@ -74,7 +96,7 @@ fn judged(dir: &Path) -> (Vec<Value>, Option<Value>, Option<std::time::SystemTim
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 = status::round_dir(dir, 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()
});
@@ -82,28 +104,21 @@ fn judged(dir: &Path) -> (Vec<Value>, Option<Value>, Option<std::time::SystemTim
(rounds, verdict, at)
}
/// The status of the job whose brief is at `brief`, with its plan already read.
pub fn status_of(brief: &Path, make: &Make) -> Value {
/// 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 = status::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 = status::status(&job);
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
}
/// For the hook: the job's status from a folder, None when there's no job there (no brief.ts, or no `make` on it).
pub fn status_in(dir: &Path) -> Result<Option<Value>, String> {
let Some(brief) = brief_path(dir).filter(|b| has_make(b)) else { return Ok(None) };
let Some(make) = read_make(&brief)? else { return Ok(None) };
Ok(Some(status_of(&brief, &make)))
}
/// The flags that take a value: what follows them isn't a positional argument.
const VALUED: [&str; 8] = ["--only", "--model", "--tripo", "--meshy", "--name", "--to", "--out", "--by"];
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)
@@ -138,10 +153,10 @@ pub(crate) fn only<'a, T>(all: &'a [T], only: &[String], name: impl Fn(&T) -> &s
}
/// The job's brief and plan from a folder.
fn job(dir: &Path) -> Result<(PathBuf, Make), String> {
let brief = brief_path(dir).ok_or_else(|| format!("raea make: no brief.ts at or above {} in its project", dir.display()))?;
let make = read_make(&brief)?.ok_or_else(|| format!("raea make: {} has no `make` (scene(), kit() or shot() from raea/brief)", brief.display()))?;
Ok((brief, make))
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.
@@ -157,13 +172,13 @@ fn step(verb: &str, args: &[String]) -> Result<String, String> {
return Err(USAGE.into());
}
let dir = pos.get(dir_at).map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."));
let (brief, m) = job(&dir)?;
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 {
"plan" => floor::draw_plan(&here, &m, !args.iter().any(|a| a == "--no-review")),
"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),
@@ -184,30 +199,14 @@ fn step(verb: &str, args: &[String]) -> Result<String, String> {
pub fn cli(args: &[String]) -> Result<String, String> {
match args.get(1).map(String::as_str) {
Some("status") => {}
Some("judge") => return job(&PathBuf::from(positional(args, 2).first().map_or(".", String::as_str))).and_then(|(b, m)| raea_runtime_goal_plan::judge(m.goal.as_ref().ok_or("raea make judge: the job isn't a goal({...})")?, b.parent().unwrap_or(Path::new(".")), flag(args, "--by").unwrap_or("claude")).map(|v| serde_json::to_string_pretty(&v).unwrap_or_default())),
Some(v @ ("plan" | "refs" | "sheet" | "gen" | "pick-sheet" | "pick" | "prep" | "kit" | "framing" | "lenschart")) => return step(v, args),
_ => return Err(USAGE.into()),
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()),
}
let dir = positional(args, 2).first().map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."));
let (brief, make) = job(&dir)?;
let mut s = status_of(&brief, &make);
if args.iter().any(|a| a == "--plan") {
let dir = brief.parent().unwrap_or(Path::new("."));
let root = raea_core_facts::record::up(dir, ".raea/project").unwrap_or_else(|| dir.to_path_buf());
let kind = s["kind"].as_str().unwrap_or("make").to_string();
let (file, task) = plan::write(&root, &brief, &kind, &s)?;
s["planOrg"] = Value::String(file.display().to_string());
s["planTask"] = Value::String(task);
}
if args.iter().any(|a| a == "--json") {
return Ok(serde_json::to_string_pretty(&s).unwrap_or_default());
}
let mut t = status::text(&s);
if let (Some(p), Some(task)) = (s["planOrg"].as_str(), s["planTask"].as_str()) {
t.push_str(&format!("\nplan.org: the gates are check lines under task {task} in {p}"));
}
Ok(t)
}
#[cfg(test)]
-95
View File
@@ -1,95 +0,0 @@
//! The job's gates in the project's plan.org (docs/make.feature MK3; docs/plan.feature PL1): one task, its :ID: from the
//! brief's path, each gate and each missing thing a check line under it with a progress cookie, so the person, the app
//! and raea cloud read the same list the Stop hook holds the agent to. MAKING while it isn't done, REVIEW once it is
//! (the person closes it); a task the person marked DONE or DROPPED keeps their mark, and their own lines under it stay.
use std::path::Path;
use serde_json::Value;
/// The task's id: t- and eight letters and digits (PL1b), the same for the same brief.
pub fn task_id(brief_rel: &str) -> String {
let h = brief_rel.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ b as u64).wrapping_mul(0x0100_0000_01b3));
format!("t-mk{:06x}", h & 0xff_ffff)
}
fn is_check(line: &str) -> bool {
let t = line.trim_start();
let rest = t.strip_prefix("- ").or_else(|| t.strip_prefix("+ "));
rest.is_some_and(|r| r.starts_with("[ ]") || r.starts_with("[X]") || r.starts_with("[x]") || r.starts_with("[-]"))
}
fn short(s: &str) -> String {
let s = s.replace('\n', " ");
if s.chars().count() > 140 { format!("{}…", s.chars().take(139).collect::<String>()) } else { s }
}
/// The check lines for a status: what's missing, then each gate.
pub fn checks(status: &Value) -> Vec<(bool, String)> {
let mut out: Vec<(bool, String)> = Vec::new();
for m in status["missing"].as_array().into_iter().flatten().filter_map(Value::as_str) {
out.push((false, format!("missing: {}", short(m))));
}
for g in status["gates"].as_array().into_iter().flatten() {
let of = g["of"].as_str().map(|o| format!(" {o}")).unwrap_or_default();
out.push((g["clear"] == true, format!("{}{of}: {}", g["gate"].as_str().unwrap_or("gate"), short(g["says"].as_str().unwrap_or("")))));
}
out
}
/// plan.org's text with the job's task brought up to date (made at the end when it isn't there).
pub fn update(text: &str, title: &str, brief_rel: &str, kind: &str, status: &Value) -> String {
let id = task_id(brief_rel);
let lines: Vec<&str> = text.lines().collect();
let done = status["done"] == true;
let cs = checks(status);
let cookie = format!("[{}/{}]", cs.iter().filter(|c| c.0).count(), cs.len());
let check_lines: Vec<String> = cs.iter().map(|(d, t)| format!("- [{}] {t}", if *d { "X" } else { " " })).collect();
let id_line = lines.iter().position(|l| l.trim() == format!(":ID: {id}") || l.trim() == format!(":ID: {id}"));
let Some(id_at) = id_line else {
let mut out = if text.trim().is_empty() { format!("#+TITLE: {title}\n#+TODO: TODO MAKING REVIEW | DONE DROPPED\n") } else { text.trim_end().to_string() + "\n" };
out.push_str(&format!("\n* {} make: {kind} ({brief_rel}) {cookie}\n:PROPERTIES:\n:ID: {id}\n:KIND: make\n:VERB: {kind}\n:END:\n", if done { "REVIEW" } else { "MAKING" }));
out.push_str(&(check_lines.join("\n") + "\n"));
return out;
};
let head = (0..id_at).rev().find(|&i| lines[i].starts_with('*')).unwrap_or(0);
let stars = lines[head].chars().take_while(|c| *c == '*').count();
let end = (id_at + 1..lines.len()).find(|&i| lines[i].starts_with('*') && lines[i].chars().take_while(|c| *c == '*').count() <= stars).unwrap_or(lines.len());
let drawer_end = (id_at..end).find(|&i| lines[i].trim() == ":END:").unwrap_or(id_at);
// the headline: its keyword brought up to date unless the person closed it, its cookie replaced
let words: Vec<&str> = lines[head][stars..].split_whitespace().collect();
let kw = words.first().copied().unwrap_or("");
let closed = kw == "DONE" || kw == "DROPPED";
let rest: Vec<&str> = words.iter().skip(if ["TODO", "MAKING", "REVIEW", "DONE", "DROPPED"].contains(&kw) { 1 } else { 0 }).copied().filter(|w| !(w.starts_with('[') && w.ends_with(']') && w.contains('/'))).collect();
let kw = if closed { kw } else if done { "REVIEW" } else { "MAKING" };
let headline = format!("{} {kw} {} {cookie}", "*".repeat(stars), rest.join(" "));
let theirs: Vec<&str> = lines[drawer_end + 1..end].iter().copied().filter(|l| !is_check(l)).collect();
let mut out: Vec<String> = lines[..head].iter().map(|l| l.to_string()).collect();
out.push(headline);
out.extend(lines[head + 1..=drawer_end].iter().map(|l| l.to_string()));
out.extend(check_lines);
out.extend(theirs.iter().map(|l| l.to_string()));
out.extend(lines[end..].iter().map(|l| l.to_string()));
out.join("\n") + "\n"
}
/// Writes the job's task into plan.org at the top of `root` (the project's folder, else the brief's): the file and the
/// task's id.
pub fn write(root: &Path, brief: &Path, kind: &str, status: &Value) -> Result<(std::path::PathBuf, String), String> {
let file = root.join("plan.org");
let rel = brief.strip_prefix(root).unwrap_or(brief).to_string_lossy().replace('\\', "/");
let title = root.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "plan".into());
let text = std::fs::read_to_string(&file).unwrap_or_default();
let next = update(&text, &title, &rel, kind, status);
if next != text {
replace(&file, &next).map_err(|e| format!("{}: {e}", file.display()))?;
}
Ok((file, task_id(&rel)))
}
/// A file's text replaced: written beside it, then moved over it, so a reader never sees half a plan.
fn replace(file: &Path, text: &str) -> std::io::Result<()> {
let tmp = file.with_extension("org.tmp");
std::fs::write(&tmp, text)?;
std::fs::rename(&tmp, file)
}
+1 -1
View File
@@ -1,4 +1,4 @@
//! The contact sheets a gate looks at (docs/make.feature MK10, MK11, MK15): pictures in rows, each labelled under it,
//! 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`.
+4 -4
View File
@@ -1,4 +1,4 @@
//! Blocking a shot list (docs/make.feature MK15): `raea make framing` renders each shot's first, middle and last
//! 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
@@ -6,7 +6,7 @@
use std::path::{Path, PathBuf};
use raea_core_brief::make::{Make, Shot};
use raea_core_brief::goal::{Goal, Shot};
use crate::sheet::{Tile, sheet};
@@ -62,7 +62,7 @@ fn composition(dir: &Path, s: &Shot) -> Result<PathBuf, String> {
}
/// 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: &Make, only: &[String], out: &Path) -> Result<String, String> {
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());
@@ -86,7 +86,7 @@ pub fn framing(dir: &Path, m: &Make, only: &[String], out: &Path) -> Result<Stri
}
/// One shot's first frame at every lens of the chart, on one sheet (OUT/lens-SHOT.png).
pub fn lenschart(dir: &Path, m: &Make, name: &str, out: &Path) -> Result<String, String> {
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);
+28 -70
View File
@@ -1,12 +1,12 @@
use std::path::PathBuf;
use std::time::{Duration, SystemTime};
use raea_core_brief::{make::Make, read};
use raea_core_brief::{goal::Goal, read};
use raea_core_facts::record::Entry;
use serde_json::{Value, json};
use crate::asked::Ledger;
use crate::status::{Job, status, stalled};
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()));
@@ -21,7 +21,7 @@ fn put(d: &PathBuf, rel: &str, text: &str) {
std::fs::write(p, text).unwrap();
}
fn kit() -> Make {
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()
}
@@ -36,35 +36,25 @@ fn round(pass: bool, mean: f64, defects: Value) -> Value {
json!({"dir": "review/r1", "kind": "kit", "pass": pass, "mean": mean, "defects": defects})
}
fn run(make: &Make, d: &PathBuf, record: &[Entry], rounds: &[Value], judged_at: Option<SystemTime>) -> Value {
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: &Make, d: &PathBuf, record: &[Entry], rounds: &[Value], judged_at: Option<SystemTime>, ledger: &Ledger) -> Value {
status(&Job { make, dir: d, project: None, record, rounds, verdict: None, judged_at, ledger, score_gates: false })
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 nothing_made_is_not_done_and_says_what_is_missing() {
let d = dir("empty");
let s = run(&kit(), &d, &[], &[], None);
assert_eq!(s["done"], false);
let missing = s["missing"].to_string();
assert!(missing.contains("out/kit/phone/phone_lod1.glb") && missing.contains("NOTES.md"), "{missing}");
assert!(s["gates"].as_array().unwrap().iter().any(|g| g["gate"] == "critic" && g["clear"] == false));
}
#[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["done"], true, "{s:#}");
assert_eq!(s["short"], false);
assert_eq!(s["clear"], true, "{s:#}");
assert_eq!(s["short"], json!([]));
}
#[test]
@@ -72,7 +62,7 @@ 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["done"], false);
assert_eq!(s["clear"], false);
assert!(s["gates"].to_string().contains("came after the last round"), "{s:#}");
}
@@ -82,25 +72,27 @@ fn a_blocking_defect_must_be_fixed_or_answered_in_the_notes() {
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["done"], false);
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["done"], true, "{s:#}");
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 = status(&Job { make: &kit(), dir: &d, project: None, record: &[], rounds: &rounds, verdict: None, judged_at: later(), ledger: &ledger, score_gates: true });
assert_eq!(s["done"], false, "{s:#}");
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");
let rounds: Vec<Value> = (0..8).map(|i| round(false, 5.0 + i as f64 * 0.5, json!([]))).collect();
// 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["done"].clone(), s["short"].clone()), (json!(true), json!(true)), "{s:#}");
assert!(s["why"].to_string().contains("capped"));
assert_eq!(s["clear"], false, "{s:#}");
assert!(s["short"].to_string().contains("capped"), "{s:#}");
}
#[test]
@@ -129,7 +121,7 @@ fn a_composition_needs_a_clean_check_newer_than_it() {
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["done"], true, "a warn doesn't block: {s:#}");
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:#}");
}
@@ -145,34 +137,25 @@ fn a_part_seen_closer_than_planned_holds_the_job() {
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["done"] == false && s["gates"].to_string().contains("seen closer than planned at r1: kiosk"), "{s:#}");
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())["done"], true);
}
#[test]
fn a_scene_wants_three_stills() {
let d = dir("scene");
let make: Make = read("make", r#"{"kind": "scene", "objects": [{"id": "stool", "label": "Stool", "h": 0.45, "route": "gen", "prompt": "a red stool"}]}"#).unwrap();
put(&d, "out/stills/a.png", "x");
let s = run(&make, &d, &[], &[], None);
assert!(s["missing"].to_string().contains("holds 1 picture"), "{s:#}");
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/make.feature MK5: a kit is judged on the kit's rubric
// 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["done"], false);
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/make.feature MK4
// docs/goal.feature MK4
let d = dir("ask");
delivered(&d);
put(&d, "review/r1/clay.png", "clay sheet bytes");
@@ -182,12 +165,12 @@ fn a_calibrated_ask_question_gates_and_an_uncalibrated_one_advises() {
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["done"], true, "{s:#}");
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["done"], false);
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
@@ -195,11 +178,11 @@ fn a_calibrated_ask_question_gates_and_an_uncalibrated_one_advises() {
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["done"], false);
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["done"], true, "{s:#}");
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);
@@ -211,28 +194,3 @@ fn a_calibrated_ask_question_gates_and_an_uncalibrated_one_advises() {
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
assert!(s["advice"].to_string().contains("make.colour.plastic says yes"), "{s:#}");
}
#[test]
fn the_gates_are_check_lines_under_the_jobs_task_in_plan_org() {
// docs/make.feature MK3
let not_done = json!({"done": false, "missing": ["out/kit/lineup.png"], "gates": [{"gate": "critic", "clear": false, "says": "no round yet"}, {"gate": "checks", "of": "kit.tsx", "clear": true, "says": "clean"}]});
let t = crate::plan::update("", "desk", "brief.ts", "kit", &not_done);
let id = crate::plan::task_id("brief.ts");
assert!(id.len() == 10 && id.starts_with("t-") && id[2..].chars().all(|c| c.is_ascii_alphanumeric()), "{id}");
assert!(t.starts_with("#+TITLE: desk\n#+TODO: TODO MAKING REVIEW | DONE DROPPED\n"), "{t}");
assert!(t.contains("* MAKING make: kit (brief.ts) [1/3]") && t.contains(&format!(":ID: {id}")), "{t}");
assert!(t.contains("- [ ] missing: out/kit/lineup.png") && t.contains("- [X] checks kit.tsx: clean"), "{t}");
// the person's own line under it stays; the checks are brought up to date; done is REVIEW
let mut mine = t.replace("- [X] checks kit.tsx: clean\n", "- [X] checks kit.tsx: clean\nShane: keep the phone's cord\n");
mine = format!("{mine}* TODO another task\n");
let done = json!({"done": true, "missing": [], "gates": [{"gate": "critic", "clear": true, "says": "round 2 judged"}]});
let t2 = crate::plan::update(&mine, "desk", "brief.ts", "kit", &done);
assert!(t2.contains("* REVIEW make: kit (brief.ts) [1/1]") && t2.contains("Shane: keep the phone's cord") && t2.contains("* TODO another task"), "{t2}");
assert!(!t2.contains("missing:"), "{t2}");
assert_eq!(t2.matches(":ID: ").count(), 1);
// a task the person closed keeps their mark
let closed = t2.replace("* REVIEW make", "* DONE make");
assert!(crate::plan::update(&closed, "desk", "brief.ts", "kit", &not_done).contains("* DONE make: kit (brief.ts) [1/3]"));
// once written, writing the same again changes nothing
assert_eq!(crate::plan::update(&t2, "desk", "brief.ts", "kit", &done), t2);
}
+4 -4
View File
@@ -3,7 +3,7 @@
use std::path::PathBuf;
use image::{Rgba, RgbaImage};
use raea_core_brief::{make::Make, read};
use raea_core_brief::{goal::Goal as Make, read};
use crate::sheet::{Tile, sheet};
@@ -109,7 +109,7 @@ 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 component add: Rotary phone, 0.12 m"), "{c}");
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");
@@ -148,7 +148,7 @@ fn a_shot_frames_its_start_middle_and_end() {
// a shot with no composition can't be framed, and says what's needed
let d = dir("framing");
assert!(crate::shots::framing(&d, &m, &["hold".to_string()], &d).unwrap_err().contains("no composition"));
assert!(raea_core_brief::make::doctor(&m).iter().any(|w| w.contains("shot `hold` has no composition")));
assert!(raea_core_brief::goal::doctor(&m).iter().any(|w| w.contains("shot `hold` has no composition")));
}
// MK18: the floor plan draws every placed footprint (invented ones dashed); the blockout boxes them from the entrance
@@ -193,7 +193,7 @@ fn a_quote_reads_as_one_line() {
#[test]
fn a_boxy_model_is_fitted_by_its_height_and_turned_to_lie_front_to_back() {
use raea_core_brief::make::Object;
use raea_core_brief::goal::Object;
let stapler: Object = serde_json::from_value(serde_json::json!({"id": "stapler", "label": "Stapler", "dims": [0.05, 0.17, 0.07]})).unwrap();
// long across (x) where the plan's is front to back (z): a quarter turn
assert_eq!(crate::kit::fit_args(&stapler, Some([1.9, 0.72, 0.58])), ["--dims", "0.05,0.17,0.07", "--h", "0.07", "--turn", "90"]);
+26 -4
View File
@@ -40,6 +40,29 @@ pub fn still(path: &Path, at: f64, out: &Path, width: Option<u32>) -> R<Value> {
Ok(json!({"wrote": out, "at": at, "width": img.width(), "height": img.height()}))
}
/// `f(0..n)`, up to four at a time, in order: a sheet's frames are each a seek and a decode of their own (16 of a 4K
/// interview: 7 s one after another, 4 s so).
fn at_once<T: Send>(n: usize, f: impl Fn(usize) -> R<T> + Sync) -> R<Vec<T>> {
use std::sync::{Mutex, atomic::{AtomicUsize, Ordering}};
let workers = std::thread::available_parallelism().map_or(2, |c| c.get()).clamp(1, 4).min(n.max(1));
let next = AtomicUsize::new(0);
let out: Vec<Mutex<Option<R<T>>>> = (0..n).map(|_| Mutex::new(None)).collect();
std::thread::scope(|s| {
for _ in 0..workers {
s.spawn(|| {
loop {
let i = next.fetch_add(1, Ordering::Relaxed);
if i >= n {
break;
}
*out[i].lock().unwrap() = Some(f(i));
}
});
}
});
out.into_iter().map(|m| m.into_inner().unwrap().unwrap_or_else(|| Err("a frame wasn't read".into()))).collect()
}
pub fn sheet(files: &[PathBuf], n: usize, w: u32, out: &Path) -> R<Value> {
if files.is_empty() {
return Err("raea media sheet FILE... -o OUT: which files?".into());
@@ -47,10 +70,9 @@ pub fn sheet(files: &[PathBuf], n: usize, w: u32, out: &Path) -> R<Value> {
let mut tiles = Vec::new();
if files.len() == 1 {
let p = probe_of(&files[0])?;
for i in 0..n.max(1) {
let t = (i as f64 + 0.5) / n.max(1) as f64 * p.duration;
tiles.push((t, frame(&files[0], t)?));
}
let at: Vec<f64> = (0..n.max(1)).map(|i| (i as f64 + 0.5) / n.max(1) as f64 * p.duration).collect();
let read = at_once(at.len(), |i| frame(&files[0], at[i]))?;
tiles.extend(at.into_iter().zip(read));
} else {
for f in files {
let p = probe_of(f)?;
+69 -62
View File
@@ -1,6 +1,7 @@
//! `media probe`: what a file is (duration, size, fps, codec, audio), with the MP4 boxes read directly for a track's own timing.
use super::*;
use raea_io_media::mp4box::{be32, be64, boxes, child, moov_of};
pub(crate) fn round3(x: f64) -> f64 {
(x * 1000.0).round() / 1000.0
@@ -38,7 +39,11 @@ pub fn probe_of(path: &Path) -> R<Probe> {
}
i
});
let audio = soft()?.decode_audio(path).ok().filter(|a| a.len() > 0).map(|a| (a.rate, a.channels.len(), a.duration()));
// what the file states, when it does; else the track decoded (WAV, MP3, a container read no other way)
let audio = match audio_track(path) {
Some(a) => Some(a),
None => soft()?.decode_audio(path).ok().filter(|a| a.len() > 0).map(|a| (a.rate, a.channels.len(), a.duration())),
};
if video.is_none() && audio.is_none() {
// what each backend said about the picture: a missing FFmpeg, a codec none of them reads
let why = why.map(|w| format!(" ({})", w.split_once(": no backend reads it (").map_or(w.as_str(), |(_, r)| r.trim_end_matches(')')).to_string())).unwrap_or_default();
@@ -124,74 +129,37 @@ impl Track {
}
}
/// The boxes inside `b` (a box's payload): (type, payload).
pub(crate) fn boxes(b: &[u8]) -> Vec<([u8; 4], &[u8])> {
let mut out = Vec::new();
let mut i = 0usize;
while i + 8 <= b.len() {
let mut size = u32::from_be_bytes(b[i..i + 4].try_into().unwrap()) as usize;
let kind: [u8; 4] = b[i + 4..i + 8].try_into().unwrap();
let mut hdr = 8;
if size == 1 && i + 16 <= b.len() {
size = u64::from_be_bytes(b[i + 8..i + 16].try_into().unwrap()) as usize;
hdr = 16;
} else if size == 0 {
size = b.len() - i;
/// The first sound track as the file states it (rate, channels, seconds), for MP4 and QuickTime files: `media probe`
/// decoded the whole track to learn these, which read every byte of a 1 GB interview (two minutes on a network disk).
pub fn audio_track(path: &Path) -> Option<(u32, usize, f64)> {
audio_in(&moov_of(path)?)
}
pub(crate) fn audio_in(moov: &[u8]) -> Option<(u32, usize, f64)> {
for (k, trak) in boxes(moov) {
if &k != b"trak" {
continue;
}
if size < hdr || i + size > b.len() {
break;
let Some(mdia) = child(trak, b"mdia") else { continue };
if child(mdia, b"hdlr").and_then(|h| h.get(8..12)) != Some(&b"soun"[..]) {
continue;
}
out.push((kind, &b[i + hdr..i + size]));
i += size;
let mdhd = child(mdia, b"mdhd")?;
let (scale, dur) = if mdhd.first() == Some(&1) { (be32(mdhd, 20)? as f64, be64(mdhd, 24)? as f64) } else { (be32(mdhd, 12)? as f64, be32(mdhd, 16)? as f64) };
// the first sample description: version at 24, channels at 32, rate (16.16) at 40; QuickTime's version 2 states
// them again as a double at 48 and a count at 56
let stsd = child(child(child(mdia, b"minf")?, b"stbl")?, b"stsd")?;
let v2 = stsd.get(24..26) == Some(&[0u8, 2][..]);
let rate = if v2 { f64::from_bits(be64(stsd, 48)?) } else { be32(stsd, 40)? as f64 / 65536.0 };
let channels = if v2 { be32(stsd, 56)? as usize } else { u16::from_be_bytes(stsd.get(32..34)?.try_into().ok()?) as usize };
return (scale > 0.0 && dur > 0.0 && rate >= 1.0 && (1..=64).contains(&channels)).then_some((rate.round() as u32, channels, dur / scale));
}
out
}
pub(crate) fn child<'a>(b: &'a [u8], kind: &[u8; 4]) -> Option<&'a [u8]> {
boxes(b).into_iter().find(|(k, _)| k == kind).map(|(_, p)| p)
}
pub(crate) fn be32(b: &[u8], at: usize) -> Option<u32> {
Some(u32::from_be_bytes(b.get(at..at + 4)?.try_into().ok()?))
}
pub(crate) fn be64(b: &[u8], at: usize) -> Option<u64> {
Some(u64::from_be_bytes(b.get(at..at + 8)?.try_into().ok()?))
None
}
/// The first video track's timing, for MP4 and QuickTime files.
pub fn video_track(path: &Path) -> Option<Track> {
use std::io::{Read, Seek, SeekFrom};
let mut f = std::fs::File::open(path).ok()?;
let len = f.metadata().ok()?.len();
// the top-level boxes, to moov (read alone: mdat can be gigabytes)
let mut at = 0u64;
let moov = loop {
if at + 8 > len {
return None;
}
let mut h = [0u8; 16];
f.seek(SeekFrom::Start(at)).ok()?;
f.read_exact(&mut h[..8]).ok()?;
let mut size = u32::from_be_bytes(h[..4].try_into().ok()?) as u64;
let mut hdr = 8u64;
if size == 1 {
f.read_exact(&mut h[8..]).ok()?;
size = u64::from_be_bytes(h[8..].try_into().ok()?);
hdr = 16;
} else if size == 0 {
size = len - at;
}
if size < hdr {
return None;
}
if &h[4..8] == b"moov" {
let mut m = vec![0u8; (size - hdr).min(256 << 20) as usize];
f.read_exact(&mut m).ok()?;
break m;
}
at += size;
};
let moov = moov_of(path)?;
for (k, trak) in boxes(&moov) {
if &k != b"trak" {
continue;
@@ -295,3 +263,42 @@ pub(crate) fn rate_fraction(fps: f64) -> String {
}
// ---- pictures
#[cfg(test)]
mod tests {
use super::*;
fn bx(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
let mut v = ((body.len() + 8) as u32).to_be_bytes().to_vec();
v.extend_from_slice(kind);
v.extend_from_slice(body);
v
}
#[test]
fn a_sound_track_is_read_from_the_file_s_own_tables() {
// mdhd v0: 48 kHz timescale, 10 s; stsd: one mp4a entry, 2 channels, 48000 Hz
let mut mdhd = vec![0u8; 24];
mdhd[12..16].copy_from_slice(&48000u32.to_be_bytes());
mdhd[16..20].copy_from_slice(&480000u32.to_be_bytes());
let mut hdlr = vec![0u8; 24];
hdlr[8..12].copy_from_slice(b"soun");
let mut stsd = vec![0u8; 44];
stsd[7] = 1;
stsd[12..16].copy_from_slice(b"mp4a");
stsd[32..34].copy_from_slice(&2u16.to_be_bytes());
stsd[40..44].copy_from_slice(&(48000u32 << 16).to_be_bytes());
let mdia = [bx(b"mdhd", &mdhd), bx(b"hdlr", &hdlr), bx(b"minf", &bx(b"stbl", &bx(b"stsd", &stsd)))].concat();
// a picture track ahead of it is passed over
let mut vh = vec![0u8; 24];
vh[8..12].copy_from_slice(b"vide");
let moov = [bx(b"trak", &bx(b"mdia", &bx(b"hdlr", &vh))), bx(b"trak", &bx(b"mdia", &mdia))].concat();
assert_eq!(audio_in(&moov), Some((48000, 2, 10.0)));
// no sound track, or one that states no rate: nothing (the track is decoded instead)
assert_eq!(audio_in(&bx(b"trak", &bx(b"mdia", &bx(b"hdlr", &vh)))), None);
let mut silent = stsd.clone();
silent[40..44].copy_from_slice(&0u32.to_be_bytes());
let mdia = [bx(b"mdhd", &mdhd), bx(b"hdlr", &hdlr), bx(b"minf", &bx(b"stbl", &bx(b"stsd", &silent)))].concat();
assert_eq!(audio_in(&bx(b"trak", &bx(b"mdia", &mdia))), None);
}
}
+1 -1
View File
@@ -4,7 +4,7 @@ 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)
+1 -1
View File
@@ -1,4 +1,4 @@
//! `raea motion` without the rest of the CLI, for working on this crate while the workspace's other crates are mid-change:
//! `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();
+6 -6
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).
@@ -15,11 +15,11 @@ 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] [--seeds 1] [--steps 100] [-o CLIP.json]";
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) {
@@ -131,7 +131,7 @@ 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()
));
@@ -233,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") {
@@ -257,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() }));
}
+1 -1
View File
@@ -1,4 +1,4 @@
//! A take scored for the faults a body shows (sheet3d plan E3), so `raea motion --seeds N` can keep the best of N:
//! 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;
+5
View File
@@ -14,4 +14,9 @@ raea-runtime-bundle = { path = "../../runtime/bundle" }
raea-io-home = { path = "../../io/home" }
regex = "1"
serde_json = "1"
# the faces the native page draws with (core/fonts), inlined in the page under the families the game names (PA8)
raea-core-fonts = { path = "../../core/fonts" }
# a game's generated sounds made at export, as a render makes them, and FFmpeg to compress them (PA6)
raea-io-assets = { path = "../../io/assets" }
base64 = "0.22"
zip = { version = "9", default-features = false, features = ["deflate-flate2"] }
+127
View File
@@ -0,0 +1,127 @@
//! The page's fonts as the native render draws them (docs/playables.feature PA8). A composition's page draws with
//! raea's bundled faces (core/fonts: Fontsource latin subsets, a few weights a family), each family the page names
//! aliased onto one (Helvetica, Arial and SF Pro draw as Inter, Times as EB Garamond, ...) and each weight drawn by the
//! nearest face (core/fonts `face`). A phone has none of them, so brick-rush's Inter fell back to a serif. The export
//! inlines, for every family the game's script names that raea aliases, its faces as @font-face data URLs under that
//! name, each face's weight a range that makes the browser's choice the native one (Inter 400/700/900: 1-550, 551-800,
//! 801-1000; a weight halfway between two faces takes the lighter, as `face`'s first-found minimum does). The page's
//! own default family is Inter, the native page's.
use base64::Engine;
use std::collections::BTreeMap;
/// The family a page with no family of its own draws in
const DEFAULT: &str = "Inter";
/// Each family name the script writes (fontFamily values and CSS font-family declarations), as written, with the
/// bundled family raea draws it as; the default first
pub fn families(script: &str) -> Vec<(String, &'static str)> {
let mut out: Vec<(String, &'static str)> = vec![(DEFAULT.into(), "inter")];
let res = [
r#"fontFamily["']?\s*:\s*["'`]([^"'`]+)["'`]"#,
r#"font-family\s*:\s*([^;"'`}]+)"#,
];
for re in res {
let re = regex::Regex::new(re).expect("a valid pattern");
for cap in re.captures_iter(script) {
for name in cap[1].split(',') {
let name = name.trim().trim_matches(|c| c == '"' || c == '\'').trim();
if let Some(c) = raea_core_fonts::canonical(name) {
if !out.iter().any(|(n, _)| n.eq_ignore_ascii_case(name)) {
out.push((name.to_string(), c));
}
}
}
}
}
out
}
/// A bundled family's faces as (weight range, style, woff2): each style's weights split halfway between neighbours,
/// the halfway weight to the lighter face
pub fn faces(canonical: &str) -> Vec<((u16, u16), &'static str, &'static [u8])> {
let mut by_style: BTreeMap<&str, Vec<(u16, &'static [u8])>> = BTreeMap::new();
for (f, w, st, bytes) in raea_core_fonts::BUNDLED {
if *f == canonical {
by_style
.entry(st)
.or_default()
.push((w.parse().unwrap_or(400), bytes));
}
}
let mut out = Vec::new();
for (st, mut ws) in by_style {
ws.sort_by_key(|(w, _)| *w);
let mut lo = 1u16;
for (i, (w, bytes)) in ws.iter().enumerate() {
let hi = ws.get(i + 1).map_or(1000, |(next, _)| (w + next) / 2);
out.push(((lo, hi), st, *bytes));
lo = hi + 1;
}
}
out
}
/// The page's <style>: each family the script names that raea aliases, its faces inlined under that name, and the
/// page's default family
pub fn style(script: &str) -> String {
let b64 = base64::engine::general_purpose::STANDARD;
let mut css = String::from("<style>\n");
for (name, canonical) in families(script) {
for ((lo, hi), st, bytes) in faces(canonical) {
css.push_str(&format!(
"@font-face{{font-family:\"{}\";font-style:{st};font-weight:{lo} {hi};src:url(data:font/woff2;base64,{}) format(\"woff2\")}}\n",
name.replace('"', ""),
b64.encode(bytes)
));
}
}
css.push_str(&format!("html,body{{font-family:\"{DEFAULT}\"}}\n</style>"));
css
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn each_family_the_game_names_is_aliased_as_the_native_page_does() {
let script = r#"h("div",{style:{fontFamily:"Inter, system-ui, sans-serif",fontWeight:900}});x={fontFamily:'Helvetica Neue'};y="b{font-family: Georgia, serif;}""#;
let f = families(script);
assert_eq!(
f,
[
("Inter".to_string(), "inter"),
("Helvetica Neue".into(), "inter"),
("Georgia".into(), "eb-garamond")
]
);
}
#[test]
fn a_weight_takes_the_face_the_native_page_takes() {
let r: Vec<(u16, u16)> = faces("inter").iter().map(|(r, _, _)| *r).collect();
assert_eq!(r, [(1, 550), (551, 800), (801, 1000)]);
// the native pick for each weight is the face whose range holds it
for w in [100u16, 400, 550, 551, 700, 800, 801, 900] {
let native = raea_core_fonts::face("Inter", w, false).unwrap();
let ours = faces("inter")
.into_iter()
.find(|((lo, hi), _, _)| (*lo..=*hi).contains(&w))
.unwrap()
.2;
assert!(native == ours, "weight {w}");
}
}
#[test]
fn the_style_holds_inter_and_sets_the_default() {
let css = style("var x=1;");
assert_eq!(css.matches("@font-face").count(), 3);
assert!(
css.contains("font-weight:801 1000")
&& css.contains("html,body{font-family:\"Inter\"}")
);
assert!(css.len() < 110_000, "{} bytes", css.len());
}
}
+170 -18
View File
@@ -1,15 +1,19 @@
//! `raea playable GAME.tsx -o DIR`: a raea game exported as a playable ad (docs/playables.feature PA13). The same TSX
//! that renders with `raea render` as the video ad (it plays itself) is linted (lint.rs), bundled once with
//! sdk/playable's browser host by raea's own bundler (Rolldown, in process: minified, its pictures and tables carried
//! in the script, one three.js), and written as each network's page or ZIP (pages.rs), each checked against its cap.
//! in the script; three.js only when the lint found a 3D kind, PA15; a sound player only for a game with sound, Tone.js
//! only for a raea/tone graph, and its generated sounds made and carried in the page, PA6), and written as each
//! network's page or ZIP (pages.rs), each checked against its cap.
mod fonts;
mod lint;
mod pages;
mod sound;
use std::path::{Path, PathBuf};
type R<T> = Result<T, String>;
pub const USAGE: &str = "raea playable GAME.tsx -o DIR [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both]";
pub const USAGE: &str = "raea playable GAME.tsx -o DIR [--name NAME] [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both]";
pub const ABOUT: &str = "a game as a playable ad: one page or ZIP per network (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff, preview), each under its 5 MB cap, from the TSX that renders as the video ad";
/// A path as an import specifier (no Windows verbatim prefix, which Rolldown can't open): raea-bundle's own
@@ -19,12 +23,13 @@ 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> {
/// The folder whose node_modules holds a package the page carries (three.js to draw 3D, Tone.js to play a raea/tone
/// graph): the project's own (`raea add [email protected]`), else the copy beside sdk/playable or sdk/r3f in raea's own files
fn package_dir(game: &Path, home: &Path, name: &str, why: &str, add: &str) -> R<PathBuf> {
let has = |d: &Path| d.join("node_modules").join(name).join("package.json").is_file();
let mut d = game.parent();
while let Some(dir) = d {
if dir.join("node_modules/three/package.json").is_file() {
if has(dir) {
return Ok(dir.to_path_buf());
}
d = dir.parent();
@@ -32,21 +37,80 @@ fn three_dir(game: &Path, home: &Path) -> R<PathBuf> {
["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())
.find(|d| has(d))
.ok_or_else(|| format!("a playable {why} with {name}, which this project doesn't have: `raea add {add}` in it"))
}
/// runtime/ecs as wasm (sdk/playable/ecs/build.sh), base64
fn ecs_wasm(home: &Path) -> R<String> {
use base64::Engine;
let f = home.join("sdk/playable/src/host/ecs.wasm");
let b = std::fs::read(&f).map_err(|e| format!("{}: raea/ecs's world as wasm isn't there ({e}): bash sdk/playable/ecs/build.sh", f.display()))?;
Ok(base64::engine::general_purpose::STANDARD.encode(b))
}
/// What sound a game makes, as the lint found it: none, media only (<Audio>, generated sounds) or a raea/tone graph
#[derive(Clone, Copy, PartialEq, Debug)]
enum Sounds {
None,
Media,
Tone,
}
/// What a page carries beside the game and the host, as the lint found the game needs it
#[derive(Clone, Copy, PartialEq, Debug)]
struct Carry {
/// a 3D drawer (Bevy's programs, its scene read by three.js), for a game with a 3D kind (PA11, PA15)
with_3d: bool,
sounds: Sounds,
/// Bevy's world as wasm, for a game that makes a raea/ecs World (PA12)
ecs: bool,
}
/// The bundle's entry: Bevy's world first for a game on raea/ecs (PA12: a World made as the game's module loads is
/// already Bevy's), the game, then the host started with Bevy's PBR programs as its 3D drawer (PA11) only for a game
/// with 3D (PA15: a 2D game's page carries no renderer) and a sound player only for a game with sound, Tone.js in it only for a
/// raea/tone graph (PA6)
fn entry(game: &Path, host: &Path, carry: Carry) -> String {
let Carry { with_3d, sounds, ecs } = carry;
let first = if ecs { format!("import {:?};\n", spec(&host.join("ecs.ts"))) } else { String::new() };
let mut e = format!("{first}import {:?};\nimport {{ start }} from {:?};\n", spec(game), spec(&host.join("main.tsx")));
if with_3d {
e.push_str(&format!("import {{ bevy3d }} from {:?};\n", spec(&host.join("bevy.ts"))));
}
if sounds != Sounds::None {
e.push_str(&format!("import {{ sound }} from {:?};\n", spec(&host.join("sound.ts"))));
}
if sounds == Sounds::Tone {
e.push_str(&format!("import {{ tone }} from {:?};\n", spec(&host.join("tone.ts"))));
}
let d3 = if with_3d { "bevy3d" } else { "undefined" };
e.push_str(&match sounds {
Sounds::None if with_3d => "start(bevy3d);\n".into(),
Sounds::None => "start();\n".into(),
Sounds::Media => format!("start({d3}, sound());\n"),
Sounds::Tone => format!("start({d3}, sound(tone));\n"),
});
e
}
/// The game and the host in one minified script that carries its files
fn bundle(game: &Path, home: &Path) -> R<String> {
let host = home.join("sdk/playable/src/host/main.tsx");
if !host.is_file() {
fn bundle(game: &Path, home: &Path, carry: Carry) -> R<String> {
let Carry { with_3d, sounds, .. } = carry;
let host = home.join("sdk/playable/src/host");
if !host.join("main.tsx").is_file() {
return Err(format!("{}: raea's playable host isn't there", host.display()));
}
let three = three_dir(game, home)?;
let out = std::env::temp_dir().join(format!("raea-playable-{}.js", std::process::id()));
let entry = format!("import {:?};\nimport {:?};\n", spec(game), spec(&host));
let alias = format!("three/={}", three.display());
let r = raea_runtime_bundle::bundle_entry(&entry, &out, &["--minify", "1", "--inline", "1", "--alias", &alias]);
let mut flags = vec!["--minify".to_string(), "1".into(), "--inline".into(), "1".into()];
if with_3d {
flags.extend(["--alias".into(), format!("three/={}", package_dir(game, home, "three", "draws its 3D", "[email protected]")?.display())]);
}
if sounds == Sounds::Tone {
flags.extend(["--alias".into(), format!("tone/={}", package_dir(game, home, "tone", "plays raea/tone", "[email protected]")?.display())]);
}
let flags: Vec<&str> = flags.iter().map(String::as_str).collect();
let r = raea_runtime_bundle::bundle_entry(&entry(game, &host, carry), &out, &flags);
let js = r.and_then(|_| std::fs::read_to_string(&out).map_err(|e| e.to_string()));
let _ = std::fs::remove_file(&out);
js
@@ -66,7 +130,12 @@ pub fn cli(args: &[String]) -> R<String> {
}
let store = serde_json::json!({"ios": flag(args, "--ios").unwrap_or(""), "android": flag(args, "--android").unwrap_or("")}).to_string();
let card = serde_json::json!({"title": flag(args, "--title").unwrap_or(""), "cta": flag(args, "--cta").unwrap_or("Play now")}).to_string();
let name = game.file_stem().and_then(|s| s.to_str()).unwrap_or("playable").to_string();
// the files' name: the brief's (`playable({ playable: { name } })`), else the game's file name
let stem = game.file_stem().map(|s| s.to_string_lossy().into_owned());
let name = flag(args, "--name").map(str::to_string).or(stem).unwrap_or_else(|| "playable".into());
if name.is_empty() || name.contains(['/', '\\']) {
return Err(format!("--name {name:?}: a file name, no folders"));
}
let mut report = Vec::new();
let found = lint::lint(&game)?;
@@ -83,16 +152,45 @@ pub fn cli(args: &[String]) -> R<String> {
return Err(why.join("\n"));
}
let js = bundle(&game, &raea_io_home::home())?;
let is = |k: &str| found.sound[k].as_bool() == Some(true);
let sounds = if is("tone") { Sounds::Tone } else if is("media") { Sounds::Media } else { Sounds::None };
let carry = Carry { with_3d: !found.kinds.is_empty(), sounds, ecs: found.ecs };
let home = raea_io_home::home();
let js = bundle(&game, &home, carry)?;
// its generated sounds, made (or found made) beside the game and carried in the page (PA6)
let assets = found.sound["assets"].as_array().cloned().unwrap_or_default();
let made = sound::make(&game, &assets)?;
report.push(match sounds {
Sounds::None => "sound: none".into(),
_ => format!("sound: {}{} generated ({} KB), played after the first touch", if sounds == Sounds::Tone { "a raea/tone graph, " } else { "" }, made.count, made.bytes / 1024),
});
// Bevy's world, for a game on raea/ecs (PA12): the wasm the host loads before the game
let ecs = if found.ecs { ecs_wasm(&home)? } else { String::new() };
report.push(if found.ecs { format!("ecs: Bevy's world as wasm ({} KB)", ecs.len() * 3 / 4 / 1024) } else { "ecs: none".into() });
let ecs = if ecs.is_empty() { ecs } else { format!("globalThis.__raeaEcsWasm={ecs:?};") };
let js = format!("{ecs}{}{js}", made.script);
// the faces the native page draws with, for the families the game names (PA8)
let style = fonts::style(&js);
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
let mut over = false;
let mut written = Vec::new();
for net in networks {
let script = format!("{}\n{js}", pages::preamble(net, &store, &card));
let w = pages::write(net, &name, &script, &out, orientation)?;
let w = pages::write(net, &name, &script, &out, orientation, &style)?;
let ok = w.bytes <= pages::CAP;
over |= !ok;
report.push(format!("{:<10} {:<40} {:>6} KB / {} KB {}", w.network, w.file.display(), w.bytes / 1024, pages::CAP / 1024, if ok { "ok" } else { "OVER" }));
written.push(w);
}
// what was written, for raea goal's playable pack (sdk/goal packs/playable.ts) and raea cloud's review
let manifest = serde_json::json!({
"name": name, "game": game.display().to_string(), "orientation": orientation, "kinds": found.kinds,
"compositions": found.comps.iter().map(|c| serde_json::json!({"id": c.id, "width": c.width, "height": c.height, "fps": c.fps, "frames": c.frames})).collect::<Vec<_>>(),
"pages": written.iter().map(|w| serde_json::json!({"network": w.network, "file": w.file.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_default(), "bytes": w.bytes})).collect::<Vec<_>>(),
"cap": pages::CAP,
});
let mf = out.join(format!("{name}.playable.json"));
std::fs::write(&mf, serde_json::to_string_pretty(&manifest).unwrap_or_default()).map_err(|e| format!("{}: {e}", mf.display()))?;
if over {
report.insert(0, format!("a page is over its network's {} KB cap", pages::CAP / 1024));
return Err(report.join("\n"));
@@ -100,3 +198,57 @@ pub fn cli(args: &[String]) -> R<String> {
report.push(format!("APPLIED {name} exported as a playable to {}", out.display()));
Ok(report.join("\n"))
}
#[cfg(test)]
mod tests {
use super::{Carry, Sounds, entry};
use std::path::Path;
fn e(with_3d: bool, sounds: Sounds, ecs: bool) -> String {
entry(Path::new("/g/game.tsx"), Path::new("/h/host"), Carry { with_3d, sounds, ecs })
}
#[test]
fn a_2d_game_starts_with_no_drawer() {
let e = e(false, Sounds::None, false);
assert!(e.contains("start();") && !e.contains("three") && !e.contains("sound") && !e.contains("ecs"), "{e}");
}
#[test]
fn a_3d_game_starts_with_three() {
let e = e(true, Sounds::None, false);
assert!(e.contains("bevy3d } from \"/h/host/bevy.ts\"") && e.contains("start(bevy3d);"), "{e}");
}
#[test]
fn a_game_with_sound_starts_with_its_player_and_tone_only_for_a_graph() {
let media = e(false, Sounds::Media, false);
assert!(media.contains("start(undefined, sound());") && !media.contains("tone"), "{media}");
let tone = e(true, Sounds::Tone, false);
assert!(tone.contains("tone } from \"/h/host/tone.ts\"") && tone.contains("start(bevy3d, sound(tone));"), "{tone}");
}
#[test]
fn a_game_on_raea_ecs_loads_bevys_world_before_the_game() {
let e = e(false, Sounds::None, true);
assert!(e.starts_with("import \"/h/host/ecs.ts\";\nimport \"/g/game.tsx\";"), "{e}");
}
#[test]
fn the_carried_ecs_wasm_is_built_from_runtime_ecs_as_it_is() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let out = std::process::Command::new("bash").arg(root.join("sdk/playable/ecs/from.sh")).output().expect("bash");
let now = String::from_utf8_lossy(&out.stdout).trim().to_string();
let built = std::fs::read_to_string(root.join("sdk/playable/src/host/ecs.wasm.from")).unwrap_or_default();
assert_eq!(built.trim(), now, "runtime/ecs changed since ecs.wasm was built: bash sdk/playable/ecs/build.sh");
}
#[test]
fn the_carried_bevy_programs_are_made_from_bevys_shaders_as_they_are() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let out = std::process::Command::new("bash").arg(root.join("sdk/playable/bevy/from.sh")).output().expect("bash");
let now = String::from_utf8_lossy(&out.stdout).trim().to_string();
let built = std::fs::read_to_string(root.join("sdk/playable/src/host/bevy/programs.from")).unwrap_or_default();
assert_eq!(built.trim(), now, "Bevy's shaders or tools/bevy-glsl changed since programs.ts was made: bash sdk/playable/bevy/build.sh");
}
}
+7 -3
View File
@@ -20,6 +20,10 @@ pub struct Found {
pub kinds: Vec<String>,
pub notes: Vec<String>,
pub refusals: Vec<String>,
/// its sound (walk.ts): `tone` (a raea/tone graph), `media` (an <Audio>) and `assets` (each generated sound to make)
pub sound: Value,
/// whether it makes a raea/ecs World (walk.ts), whose page carries Bevy's world as wasm (PA12)
pub ecs: bool,
}
const SOURCE_RULES: &[(&str, &str)] = &[
@@ -27,7 +31,7 @@ const SOURCE_RULES: &[(&str, &str)] = &[
(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)"),
(r"<(Video|OffthreadVideo)\b", "<Video> plays footage through the native media stack, which a playable doesn't carry: render the clip as frames or an image sequence"),
];
/// The game's source and its compositions, judged
@@ -48,7 +52,7 @@ pub fn lint(game: &Path) -> R<Found> {
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(_) if !refusals.is_empty() => return Ok(Found { comps: vec![], kinds: vec![], notes, refusals, sound: Value::Null, ecs: false }),
Err(e) => return Err(e),
};
let comps: Vec<Comp> = walked["comps"]
@@ -73,7 +77,7 @@ pub fn lint(game: &Path) -> R<Found> {
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 })
Ok(Found { comps, kinds: strings("kinds"), notes, refusals, sound: walked["sound"].clone(), ecs: walked["ecs"].as_bool() == Some(true) })
}
/// 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
+4 -3
View File
@@ -43,9 +43,10 @@ fn zip(file: &Path, entries: &[(String, String)]) -> R<()> {
Ok(())
}
/// `network`'s package of `script` (its preamble already first) written into `out` as NAME-NETWORK.html or .zip
pub fn write(network: &str, name: &str, script: &str, out: &Path, orientation: &str) -> R<Written> {
let html = |head: &str, body: &str| page(name, head, body, script);
/// `network`'s package of `script` (its preamble already first) written into `out` as NAME-NETWORK.html or .zip, its
/// `style` (the fonts, fonts.rs) first in the head
pub fn write(network: &str, name: &str, script: &str, out: &Path, orientation: &str, style: &str) -> R<Written> {
let html = |head: &str, body: &str| page(name, &format!("{style}\n{head}"), body, script);
let file = match network {
// a ZIP with index.html; exitapi.js and the orientation tag in the head (Google Ads help 9981650)
"google" => {
+89
View File
@@ -0,0 +1,89 @@
//! A playable's generated sounds (docs/playables.feature PA6). A game's `sao(...)` effects and TokenSynth notes are
//! made by the native renderer the first time a render meets them (runtime/sound: raea's asset store, beside the edit).
//! A playable makes no requests, so the export makes each one the game describes (sdk/playable walk.ts lists them,
//! each with its model, prompt, seed and params as the renderer passes them, so the store's cache is shared with
//! renders) and carries it in the page as a data URL under its src (`asset:sao/...`), AAC at 64 kb/s mono when FFmpeg
//! is there (a two-second effect is about 16 KB), else the file as made. The host plays it after the first touch.
use super::R;
use base64::Engine;
use serde_json::Value;
use std::path::Path;
/// The page's sounds: a script that sets `__raeaSounds` (src -> data URL), how many and their bytes
pub struct Made {
pub script: String,
pub count: usize,
pub bytes: usize,
}
/// Each generated sound the game describes, made (or found made) beside the game and inlined
pub fn make(game: &Path, assets: &[Value]) -> R<Made> {
let store = raea_io_assets::Store::beside(game);
let ffmpeg = raea_io_assets::ffmpeg_tool("ffmpeg", false).ok();
let mut out = serde_json::Map::new();
let mut bytes = 0;
for a in assets {
let (Some(src), Some(model), Some(prompt)) =
(a["src"].as_str(), a["model"].as_str(), a["prompt"].as_str())
else {
continue;
};
let seed = a["seed"].as_u64().unwrap_or(1);
let made = store
.make(model, prompt, seed, &a["params"])
.map_err(|e| format!("the sound {model} \"{prompt}\" couldn't be made: {e}"))?;
let file = store.path(&made);
let (mime, data) = match ffmpeg.as_deref().and_then(|f| aac(f, &file)) {
Some(d) => ("audio/mp4", d),
None => (
mime(&made.ext),
std::fs::read(&file).map_err(|e| format!("{}: {e}", file.display()))?,
),
};
bytes += data.len();
out.insert(
src.into(),
Value::from(format!(
"data:{mime};base64,{}",
base64::engine::general_purpose::STANDARD.encode(&data)
)),
);
}
let count = out.len();
let script = if count == 0 {
String::new()
} else {
format!("globalThis.__raeaSounds={};", Value::Object(out))
};
Ok(Made {
script,
count,
bytes,
})
}
/// The file as AAC in an MP4 (what WebKit and every other browser decode), mono at 64 kb/s
fn aac(ffmpeg: &Path, file: &Path) -> Option<Vec<u8>> {
let to = std::env::temp_dir().join(format!("raea-playable-sound-{}.m4a", std::process::id()));
let ok = std::process::Command::new(ffmpeg)
.args(["-v", "error", "-y", "-i"])
.arg(file)
.args(["-vn", "-ac", "1", "-c:a", "aac", "-b:a", "64k", "-f", "mp4"])
.arg(&to)
.status()
.is_ok_and(|s| s.success());
let data = if ok { std::fs::read(&to).ok() } else { None };
let _ = std::fs::remove_file(&to);
data
}
fn mime(ext: &str) -> &'static str {
match ext {
"mp3" => "audio/mpeg",
"ogg" => "audio/ogg",
"flac" => "audio/flac",
"m4a" | "mp4" | "aac" => "audio/mp4",
_ => "audio/wav",
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
//! Camera clearance (docs/make.feature MK16, from AnyShot's clearance pass): every frame, how near the camera passes to
//! 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
+1 -1
View File
@@ -1,7 +1,7 @@
//! `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). `lod` is
//! each part's planned detail beside how large the frames show it (docs/make.feature MK23).
//! each part's planned detail beside how large the frames show it (docs/goal.feature MK23).
use serde_json::json;
+1 -1
View File
@@ -1,4 +1,4 @@
//! `raea scene lod EDIT.tsx [--composition ID] [--from N] [--to N] [--json]` (docs/make.feature MK23): every part's
//! `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,
+4 -4
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,11 +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" }
# a scene, kit or shot held to its plan (docs/make.feature)
# a scene, kit or shot held to its plan (docs/goal.feature)
raea-app-make = { path = "../make" }
# `raea solid export`: the solid built, written as .glb and read back (core/shape), named and coloured (core/meshcheck)
# `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!(
+8 -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,7 +91,7 @@ fn parse_set(s: &str) -> Result<Map<String, Value>, String> {
Ok(m)
}
/// `raea solid ...`, `raea judge ...`, `raea make ...` (docs/make.feature) 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) {
@@ -134,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;
@@ -179,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"] {
@@ -200,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" }
+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(" ");
+6 -6
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;
+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") => {
+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(),
},
))
}
+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 });
}
}
+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));
}
+2 -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);
}
+1 -1
View File
@@ -1,6 +1,6 @@
// 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 bake light --compare` makes media/baked/.
// 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";
+1 -1
View File
@@ -1,5 +1,5 @@
// 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 bake light --compare` makes media/baked/cornell/.
// 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";
+1 -1
View File
@@ -1,5 +1,5 @@
// The table 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 bake light --compare` makes media/baked/table/.
// own bake is measured against (docs/bake.feature BK0). `raea make bake light --compare` makes media/baked/table/.
import { AbsoluteFill, Composition, registerRoot } from "raea";
import { Baked } from "./baked";
import { Look } from "./parts/table";
+1 -1
View File
@@ -1,5 +1,5 @@
// The window 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 bake light --compare` makes media/baked/window/.
// own bake is measured against (docs/bake.feature BK0). `raea make bake light --compare` makes media/baked/window/.
import { AbsoluteFill, Composition, registerRoot } from "raea";
import { Baked } from "./baked";
import { Look } from "./parts/window";
-1
View File
@@ -16,7 +16,6 @@ mkdir -p "$OUT"
export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
expected() { case $1 in
examples/games/animated-character.tsx) echo "its media/RobotExpressive.glb was deleted" ;;
examples/playables/brick-rush.tsx) echo "RAEA_LIVE3D_CHECK panics on frame 1: the fast rows carry the sun's rotation and the full rows don't (runtime/scene/src/live.rs; docs/playables.feature PA18)" ;;
sdk/raea/bench/bevy-parity/3d/rotate_environment_map.tsx) echo "clearcoat textures need raea-sys-material's multi-layer feature, off by default (as bench/bevy-parity/runs.tsv leaves it out)" ;;
esac; }
SAME=0 DIFF=0 ERR=0 SKIP=0
+1 -1
View File
@@ -42,7 +42,7 @@ run() {
frames=$(ffprobe -v error -count_frames -select_streams v:0 -show_entries stream=nb_read_frames -of csv=p=0 "$out" 2>/dev/null)
secs=$(ffprobe -v error -show_entries format=duration -of csv=p=0 "$out" 2>/dev/null)
local bake
bake=$(grep -m1 '^raea bake:' "$log" | sed 's/^raea bake: //')
bake=$(grep -m1 '^raea make bake:' "$log" | sed 's/^raea make bake: //')
printf '%s\texit %s\t%.2f s\t%s ms a frame\t%s frames, %s s of video\tbake: %s\tstartup: %s\n' "$tag" "$rc" "$(echo "$t1 - $t0" | bc)" "${per:-?}" "${frames:-?}" "${secs:-?}" "${bake:-none}" "$marks"
}
while IFS=$'\t' read -r path comp from to scale sign; do
+1 -1
View File
@@ -1,6 +1,6 @@
//! What a file is, cheaply: its size and a hash of its first and last MB. The ledger keeps it on every call
//! (apps/ask record.rs), so a render is known again by its copy in the feed, a later render to the same path isn't
//! taken for it, and `raea make status` knows an answer was about exactly the sheet on disk now (docs/make.feature MK4).
//! taken for it, and `raea goal gates` knows an answer was about exactly the sheet on disk now (docs/goal.feature MK4).
use std::io::{Read as _, Seek as _, SeekFrom};
use std::path::Path;
+1 -1
View File
@@ -1,7 +1,7 @@
//! The questions that come standard (docs/ask.feature AK1), each set named: `rubric` (the craft rubric's own questions,
//! read from sdk/guides/craft/rubric.md, so there's one copy), `av` (picture with sound), `defects` (the fingerprint's
//! axes with no labels yet), `platform` (the check packs' questions with their calibration), `decide` (picks and
//! comparisons) and `make` (the review loop's gate questions, asked of a job's sheets: docs/make.feature MK4; each id
//! comparisons) and `make` (the review loop's gate questions, asked of a job's sheets: docs/goal.feature MK4; each id
//! says its sheet, make.clay.*, make.colour.*, make.refs.*, make.framing.*). The JSON sets ship inside raea; the
//! rubric is read from the guide the caller hands in.
+12 -7
View File
@@ -1,5 +1,5 @@
//! A project's brief: who it's for, the one thing they should believe and what it delivers. The facts an agent guessed
//! are listed in `assumed`, for the person to confirm. Its tasks are in the project's plan.org, not here
//! are listed in `assumed`, for the person to confirm. Its tasks are in the project's plan.ts, not here
//! (docs/plan.feature PL8a).
use serde::{Deserialize, Serialize};
@@ -48,7 +48,7 @@ pub struct Brief {
#[serde(default)]
#[ts(as = "Option<Vec<Reference>>", optional)]
pub references: Vec<Reference>,
/// an older brief's tasks, read only so it still loads: they belong in plan.org (docs/plan.feature PL8a), and
/// an older brief's tasks, read only so it still loads: they belong in plan.ts (docs/plan.feature PL8a), and
/// `raea doctor` says so; never written, and not in the schema an agent writes to
#[serde(default, skip_serializing)]
#[ts(skip)]
@@ -61,11 +61,16 @@ pub struct Brief {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(type = "unknown", optional)]
pub story: Option<serde_json::Value>,
/// a scene, kit or shot made to a frozen plan and held to the review loop (docs/make.feature): `scene()`, `kit()`
/// or `shot()` from "raea/brief"; `raea make status` decides when it's done
/// the project's tasks (raea/task `plan({...})`, docs/plan.feature): written inline or imported from a module, read
/// from the brief's run by `raea goal tasks`; kept as written, raea/task reads it
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(type = "import(\"raea/task\").PlanFile", optional)]
pub plan: Option<serde_json::Value>,
/// what the work is held to (docs/goal.feature): one goal, or several in order (a workflow inline), each a `cut()`,
/// `shot()`, `kit()`, `scene()` or `rules()` from "raea/brief"; `raea goal check` decides when each is done
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub make: Option<crate::make::Make>,
pub goal: Option<crate::goal::Goals>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
@@ -129,8 +134,8 @@ pub fn doctor(b: &Brief) -> Vec<String> {
for a in &b.assumed {
out.push(format!("`{a}` is assumed: confirm it with the person"));
}
if let Some(m) = &b.make {
out.extend(crate::make::doctor(m).into_iter().map(|d| format!("make: {d}")));
if let Some(g) = &b.goal {
out.extend(crate::goal::doctor_all(g).into_iter().map(|d| format!("goal: {d}")));
}
out
}
+52 -13
View File
@@ -1,8 +1,8 @@
//! A cut job's contract (docs/make.feature MK25): `make: cut({...})` on brief.ts, the client's brief made into rules
//! A cut goal's contract (docs/goal.feature MK25): `goal: cut({...})` on brief.ts, the client's brief made into rules
//! before anything is planned or cut. A brief read as context gets lost (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"). Every rule quotes the brief line it came
//! from (`from`), and `raea make status` (apps/make cut.rs) finds each quote in the brief's text, so a rule can't be
//! from (`from`), and raea/goal's quotes pack (sdk/goal) finds each quote in the brief's text, so a rule can't be
//! invented and a brief line can't drift; then it holds every delivered file to the rules, from what's on disk.
use serde::{Deserialize, Serialize};
@@ -11,7 +11,7 @@ use ts_rs::TS;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "MakeCut")]
#[ts(rename = "CutGoal")]
pub struct Cut {
/// the brief as text, relative to brief.ts (`pdftotext -layout brief.pdf media/brief.txt`): every `from` is found in it
pub brief: String,
@@ -47,7 +47,7 @@ pub struct Cut {
/// A value with the brief's words for it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(deny_unknown_fields)]
#[ts(rename = "MakeQuoted")]
#[ts(rename = "Quoted")]
pub struct Quoted<T: TS> {
pub value: T,
/// the brief's own words, as they are in its text
@@ -57,7 +57,7 @@ pub struct Quoted<T: TS> {
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "MakeCutPlan")]
#[ts(rename = "CutPlan")]
pub struct CutPlan {
/// [a-z0-9_], unique: each format lands as out/cuts/<id>_<W>x<H>.mp4 ("a1_s1_9x16.mp4")
pub id: String,
@@ -72,12 +72,35 @@ pub struct CutPlan {
#[ts(as = "Option<Vec<String>>", optional)]
pub formats: Vec<String>,
pub seconds: Option<[f64; 2]>,
/// the cut's beats in order (docs/goal.feature MK48): what each must make the viewer feel and understand, decided
/// before the cut (Murch: emotion and story weigh most), and its pace
#[serde(default)]
#[ts(as = "Option<Vec<Beat>>", optional)]
pub beats: Vec<Beat>,
}
/// One beat of a cut, from `at` seconds to the next beat's (or the end).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "Beat")]
pub struct Beat {
/// where it starts, in seconds from the cut's start (0 for the first)
pub at: f64,
/// what the viewer feels here, in the person's words ("the itch of a chore left undone")
pub feel: String,
/// what the viewer understands by its end ("the app does the reminding")
pub story: Option<String>,
/// its average shot length in seconds: the shots inside it average within a third of this
pub asl: Option<f64>,
/// how its shot lengths move: "build" (shorter as it goes), "release" (longer) or "hold" (even)
pub tempo: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "MakePhrase")]
#[ts(rename = "Phrase")]
pub struct Phrase {
/// as it's said or shown; compared in lower case, by letters and digits ("24/7" and "24-7" are the same)
pub text: String,
@@ -89,7 +112,7 @@ pub struct Phrase {
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "MakeCta")]
#[ts(rename = "Cta")]
pub struct Cta {
pub text: String,
pub from: String,
@@ -104,7 +127,7 @@ pub struct Cta {
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "MakeOpen")]
#[ts(rename = "CutOpen")]
pub struct Open {
pub question: String,
pub from: String,
@@ -115,9 +138,6 @@ pub struct Open {
pub by: Option<String>,
}
/// How near the end the CTA lands when the contract says nothing.
pub const CTA_WITHIN: f64 = 8.0;
/// A format's frame shape, "9:16" -> (9, 16).
pub fn ratio(f: &str) -> Option<(u32, u32)> {
let (w, h) = f.split_once(':')?;
@@ -142,7 +162,8 @@ pub fn deliverables(c: &Cut) -> Vec<String> {
c.cuts.iter().flat_map(|p| formats(c, p).iter().map(move |f| file(p, f))).collect()
}
/// Every `from` in the contract, with what it backs: the quotes `raea make status` finds in the brief's text.
/// Every `from` in the contract, with what it backs: what doctor holds to have a quote (raea/goal's quotes pack finds
/// each in the brief's text).
pub fn quotes(c: &Cut) -> Vec<(String, &str)> {
let mut q: Vec<(String, &str)> = Vec::new();
if let Some(n) = &c.count {
@@ -185,7 +206,7 @@ pub fn doctor(c: &Cut) -> Vec<String> {
if !seen.insert(p.id.as_str()) {
out.push(format!("cut `{}` is listed twice", p.id));
}
if !crate::make::is_name(&p.id) {
if !crate::goal::is_name(&p.id) {
out.push(format!("cut `{}`: ids are [a-z0-9_], the file it lands as", p.id));
}
let fs = formats(c, p);
@@ -205,6 +226,24 @@ pub fn doctor(c: &Cut) -> Vec<String> {
{
out.push(format!("cut `{}`: text is captions, hook or none, not `{t}`", p.id));
}
let mut last = -1.0;
for (i, b) in p.beats.iter().enumerate() {
if b.at < 0.0 || b.at <= last || (i == 0 && b.at != 0.0) {
out.push(format!("cut `{}`: beat {} at {} s: beats start at 0 and go in order", p.id, i + 1, b.at));
}
last = b.at;
if b.feel.trim().is_empty() {
out.push(format!("cut `{}`: beat {} has no `feel`: what the viewer feels there, in the person's words", p.id, i + 1));
}
if let Some(t) = &b.tempo
&& !matches!(t.as_str(), "build" | "release" | "hold")
{
out.push(format!("cut `{}`: beat {}'s tempo is build, release or hold, not `{t}`", p.id, i + 1));
}
if b.asl.is_some_and(|a| !(a > 0.0)) {
out.push(format!("cut `{}`: beat {}'s asl is seconds a shot, above 0", p.id, i + 1));
}
}
}
for (what, from) in quotes(c) {
if from.trim().is_empty() {
+393 -44
View File
@@ -1,67 +1,416 @@
//! A goal job's contract: `make: goal({...})` on brief.ts, the person's goal written as rules before the work starts
//! (11-26, Shane: "we essentially just need to make sure that it can't stop unless all the goals pass, or all the rules
//! in the brief"). `/goal` in raea.app and an agent's own goal are this: the goal in the person's words, then each
//! thing that must hold, as a command that must pass, a file that must exist, or words a fresh critic must find true.
//! `raea make status` (runtime/goal-plan) decides from them whether the agent may stop; the agent saying so never does.
//! A goal (docs/goal.feature): one step of the work, on a project's brief.ts as `goal:` (one, or several in order: a
//! workflow), written with `cut()`, `shot()`, `kit()`, `scene()`, `playable()` or `rules()` from "raea/brief" before
//! anything is built, and read here. Each kind turns its packs on: a scene (a dressed, lit place), a kit (props that
//! belong together), a shot (stills or camera moves of a built scene), a cut (ads from footage to a client's brief), a
//! playable (a game exported as a playable ad, playable.rs), and rules (any other work: only its own rules). Any goal can carry `rules` and an `aim`. Every object carries its real
//! size and whether it came from the reference or was invented; every dial its value, where the value came from, and
//! what it meant here. `raea goal check` (sdk/goal) holds each goal to it.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use ts_rs::TS;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "lowercase")]
#[ts(rename = "GoalKind")]
pub enum Kind {
/// a dressed, lit place from references or a brief
Scene,
/// a set of props in one style, at real size, to drop into any scene
Kit,
/// stills or camera moves of a built scene, from words
Shot,
/// ads cut from footage to a client's brief: its deliverables, phrases, claims and CTA as rules (cut.rs, MK25)
Cut,
/// any other work, held only to its rules: commands that must pass, files that must exist, words a critic judges
Rules,
/// a game exported as a playable ad by `raea playable`: each network's page, the preview, both orientations unless
/// the brief says one (playable.rs, docs/playables.feature PA19)
Playable,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "MakeGoal")]
pub struct Goal {
/// the goal as the person said it
pub goal: String,
/// what must hold before the agent may stop: every one, each checked in code or by a fresh critic
pub kind: Kind,
/// how the plan, the report and other goals' `after` name it ([a-z0-9_]); the kind when left out
pub name: Option<String>,
/// the workflow step it serves, by the workflow's name for it (`edit`, `deliver`)
pub step: Option<String>,
/// the goals that must be done before this one starts, by name
#[serde(default)]
#[ts(as = "Option<Vec<GoalRule>>", optional)]
pub rules: Vec<GoalRule>,
#[ts(as = "Option<Vec<String>>", optional)]
pub after: Vec<String>,
/// what the goal is, in the person's words
pub aim: Option<String>,
/// what must hold before the agent may stop, beside the kind's packs: each checked in code or by a fresh critic
#[serde(default)]
#[ts(as = "Option<Vec<crate::rules::Rule>>", optional)]
pub rules: Vec<crate::rules::Rule>,
/// the pictures the job answers to (paths beside the brief): what is in it and where for a scene, the style for a kit
#[serde(default)]
#[ts(as = "Option<Vec<String>>", optional)]
pub references: Vec<String>,
/// one paragraph every reference prompt carries: era, palette, materials, wear, and one fictional maker
pub style: Option<String>,
/// by name, from the kind's set (DIALS); one left out is read from the references
#[serde(default)]
#[ts(as = "Option<BTreeMap<String, Dial>>", optional)]
pub dials: BTreeMap<String, Dial>,
#[serde(default)]
#[ts(as = "Option<Vec<Object>>", optional)]
pub objects: Vec<Object>,
#[serde(default)]
#[ts(as = "Option<Vec<Shot>>", optional)]
pub shots: Vec<Shot>,
/// the compositions the job's checks hold (relative to the brief): each needs a clean render or check newer than it
#[serde(default)]
#[ts(as = "Option<Vec<String>>", optional)]
pub compositions: Vec<String>,
/// what must exist when it's done, relative to the brief; replaces the kind's own list (`deliverables`)
#[serde(default)]
#[ts(as = "Option<Vec<String>>", optional)]
pub deliverables: Vec<String>,
/// the most critic rounds the job gets; at the cap it is delivered with what's still missing (8 by default)
pub rounds: Option<u32>,
/// a cut job's contract: the brief as rules (cut.rs)
pub cut: Option<crate::cut::Cut>,
/// a playable job's game, networks and orientation (playable.rs)
pub playable: Option<crate::playable::Playable>,
/// what the job shows but never delivers, relative to the brief (pictures, render tests, examples): each a file or a
/// `dir/` (review/ and previews/ when left out). Deliverables are what it hands over; previews are how it got there
#[serde(default)]
#[ts(as = "Option<Vec<String>>", optional)]
pub previews: Vec<String>,
/// raea's packs switched by name over the kind's defaults (`{ surprise: true, place: false }`): which of
/// raea/goal's rules hold this goal (docs/goal.feature)
#[serde(default)]
#[ts(as = "Option<BTreeMap<String, bool>>", optional)]
pub packs: BTreeMap<String, bool>,
/// the project's own checks (raea/check `check()`, imported into brief.ts), run by `raea goal check`; as data, only
/// their declarations (id, text, over, at) reach Rust
#[serde(default)]
#[ts(type = "Array<unknown>", optional)]
pub checks: Vec<serde_json::Value>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "lowercase")]
#[ts(rename = "GoalSource")]
pub enum Source {
/// set by the person who asked: an instruction, even when the reference says otherwise
Customer,
/// read from the references, because nobody set it
Reference,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(untagged)]
#[ts(rename = "GoalDialValue")]
pub enum DialValue {
Number(f64),
Text(String),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(untagged)]
#[ts(rename = "GoalDial")]
pub enum Dial {
/// `wear: 0.4`: the value alone, set by the person
Bare(DialValue),
/// `wear: { value: 0.4, source: "reference", means: "scuffed bakelite, worn paint on the edges" }`
Full {
value: DialValue,
#[ts(optional)]
source: Option<Source>,
/// what the value meant for this job, in one line
#[ts(optional)]
means: Option<String>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "lowercase")]
#[ts(rename = "GoalRoute")]
pub enum Route {
/// defined by numbers: Manifold solids, raea/room
Solid,
/// defined by a rule: fields, growth, instances
Rule,
/// defined by its looks: generated (raea gen)
Gen,
/// an exact asset that already exists
Library,
/// far background: a picture on a plane
Picture,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "lowercase")]
#[ts(rename = "GoalOrigin")]
pub enum Origin {
/// seen in a reference
Reference,
/// added to complete the place or the set, in the same world
Invented,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "GoalPick")]
pub struct Pick {
/// "tripo-h31", "meshy", ...
pub generator: String,
/// one line: why this one ("sharper dial numerals; Tripo fused the handset to the cradle")
pub why: String,
}
/// One thing that must hold. Exactly one of `run`, `file` or `says`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "MakeGoalRule")]
pub struct GoalRule {
/// a short name: [a-z0-9_], how status, the critic and NOTES.md name it
#[ts(rename = "GoalObject")]
pub struct Object {
/// snake_case, unique in the job
pub id: String,
/// a command that must exit 0, run in the brief's folder (`bun test`, `raea check edit.tsx`)
pub run: Option<String>,
/// the seconds `run` gets before it counts as failed (300 when left out)
pub timeout: Option<u32>,
/// a file that must exist, relative to the brief (`a|b`: either; `dir/`: three or more pictures in it)
pub file: Option<String>,
/// words that must be true of the work, judged by a fresh critic (`raea make judge`), never by the agent that did it
pub says: Option<String>,
pub label: String,
/// real height in metres
pub h: Option<f64>,
/// [width, depth, height] in metres, for boxy things (generators invent depth)
pub dims: Option<[f64; 3]>,
/// largest extent in metres, for things that lie flat (tools, papers)
pub max: Option<f64>,
pub route: Option<Route>,
/// one object, its condition and its materials; never a real brand
pub prompt: Option<String>,
pub source: Option<Origin>,
/// where it is in reference 0: [x0, y0, x1, y1] in 0..1
pub crop: Option<[f64; 4]>,
/// where it stands in a scene: metres, the floor's front-left corner at the origin, rot 0 = facing the entrance
pub at: Option<[f64; 3]>,
pub rot: Option<f64>,
pub hero: Option<bool>,
/// how large it is planned to be seen, which is how much of it gets built: 0 the hero (half the frame or more),
/// 1 featured (under 50%), 2 dressing (under 20%), 3 background (under 8%: a grey box reads), 4 far (under 2%: a
/// silhouette). A render that shows it finer than this says so (`lod-closer`; `raea scene lod` lists every part)
pub lod: Option<u8>,
pub pick: Option<Pick>,
/// what was fixed by script ("glass made transmissive, label kept opaque")
#[serde(default)]
#[ts(as = "Option<Vec<String>>", optional)]
pub fixes: Vec<String>,
}
/// What the goal's rules still lack, each with what to do. Empty when it's ready.
pub fn doctor(g: &Goal) -> Vec<String> {
let mut out = Vec::new();
if g.goal.trim().is_empty() {
out.push("no `goal`: the goal in the person's own words".into());
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "GoalShot")]
pub struct Shot {
/// [a-z0-9_]: the file it lands as (out/shots/<name>.png or .mp4)
pub name: String,
/// in a crew's words: "slow push along the counter, rack focus to the register"
pub description: Option<String>,
/// static, dolly, truck, pedestal, crane, pan, tilt, orbit, dollyZoom, path
#[serde(rename = "move")]
#[ts(rename = "move")]
pub move_: Option<String>,
pub seconds: Option<f64>,
pub lens: Option<f64>,
/// none, subtle, walk
pub handheld: Option<String>,
/// a still rather than a move
pub still: Option<bool>,
/// the composition that renders it (relative to the brief): `raea make shots` draws its framing sheet and lens chart
pub composition: Option<String>,
/// its frame rate, for the frames `seconds` spans (30 when left out)
pub fps: Option<f64>,
}
impl Kind {
/// as brief.ts writes it, and as raea judge's rubrics are named
pub fn name(self) -> &'static str {
// in the enum's order
["scene", "kit", "shot", "cut", "rules", "playable"][self as usize]
}
if g.rules.is_empty() {
out.push("no `rules`: what must hold before you stop, each a `run` command, a `file` or words a critic judges (`says`)".into());
}
/// Each kind's dials: what may be set, and what an unset one is read from the references as.
pub fn dials(kind: Kind) -> &'static [&'static str] {
match kind {
Kind::Scene => &["density", "tidiness", "wear", "wetness", "time_of_day", "weather", "atmosphere", "power", "warmth", "look"],
Kind::Kit => &["count", "variety", "detail", "wear", "wetness", "warmth", "look"],
Kind::Shot => &["res", "seconds", "lens", "handheld", "look"],
Kind::Cut => &["look"],
Kind::Rules => &[],
Kind::Playable => &["look"],
}
let mut seen = std::collections::BTreeSet::new();
for r in &g.rules {
if !crate::make::is_name(&r.id) {
out.push(format!("rule `{}`: ids are [a-z0-9_]", r.id));
}
if !seen.insert(r.id.as_str()) {
out.push(format!("rule `{}` is listed twice", r.id));
}
let n = [r.run.is_some(), r.file.is_some(), r.says.is_some()].iter().filter(|x| **x).count();
if n != 1 {
out.push(format!("rule `{}` needs exactly one of `run`, `file` or `says` (it has {n})", r.id));
}
if r.timeout.is_some() && r.run.is_none() {
out.push(format!("rule `{}` has a `timeout` but no `run`", r.id));
}
/// The round cap when the plan names none: AnyKit's and raea judge's 8.
pub const ROUNDS: u32 = 8;
/// What must exist when the goal is done, relative to the brief's folder: its own list, else its kind's; and each of
/// its `file` rules.
pub fn deliverables(m: &Goal) -> Vec<String> {
let mut out = if m.deliverables.is_empty() { by_kind(m) } else { m.deliverables.clone() };
for f in m.rules.iter().filter_map(|r| r.file.clone()) {
if !out.contains(&f) {
out.push(f);
}
}
out
}
fn by_kind(m: &Goal) -> Vec<String> {
match m.kind {
// the stills are counted (three or more), not named: apps/make checks the folder
Kind::Scene => vec!["out/stills/".into()],
Kind::Kit => {
let mut v: Vec<String> = m
.objects
.iter()
.flat_map(|o| [format!("out/kit/{0}/{0}.glb", o.id), format!("out/kit/{0}/{0}_lod1.glb", o.id), format!("out/kit/thumbs/{}.png", o.id)])
.collect();
// the reference sheet every reference was checked on before any 3D (MK10)
v.extend(["out/kit/lineup.png".into(), "out/kit/kit.json".into(), "review/refs.png".into()]);
v
}
// a shot is a still or a move, so either file answers; apps/make reads `a|b`
Kind::Shot => m.shots.iter().map(|s| format!("out/shots/{0}.png|out/shots/{0}.mp4", s.name)).collect(),
Kind::Cut => m.cut.as_ref().map(crate::cut::deliverables).unwrap_or_default(),
// only its `file` rules, added above
Kind::Rules => vec![],
Kind::Playable => m.playable.as_ref().map(crate::playable::deliverables).unwrap_or_default(),
}
}
/// What the job shows but doesn't deliver: the plan's own list, else review/ and previews/.
pub fn previews(m: &Goal) -> Vec<String> {
if m.previews.is_empty() { vec!["review/".into(), "previews/".into()] } else { m.previews.clone() }
}
/// A name a file lands as: [a-z0-9_], not empty.
pub fn is_name(s: &str) -> bool {
!s.is_empty() && s.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
}
/// What the plan still lacks before it can be built against, each with what to do. Empty when it's ready.
pub fn doctor(m: &Goal) -> Vec<String> {
let mut out = Vec::new();
let allowed = dials(m.kind);
for name in m.dials.keys().filter(|k| !allowed.contains(&k.as_str())) {
out.push(format!("dial `{name}` isn't one of a {:?}'s ({}): drop it or say it in `style`", m.kind, allowed.join(", ")));
}
match m.kind {
Kind::Shot if m.shots.is_empty() => out.push("no shots: list each with a name and a description".into()),
Kind::Scene | Kind::Kit if m.objects.is_empty() => out.push("no objects: list every object with its real size and route".into()),
_ => {}
}
match (&m.cut, m.kind) {
(Some(c), Kind::Cut) => out.extend(crate::cut::doctor(c)),
(None, Kind::Cut) => out.push("no `cut`: the brief as rules (count, cuts, say, never, cta, open), each quoting it".into()),
(Some(_), k) => out.push(format!("`cut` is for a cut job, not a {k:?}: drop it, or make this `cut({{...}})`")),
_ => {}
}
match (&m.playable, m.kind) {
(Some(p), Kind::Playable) => out.extend(crate::playable::doctor(p)),
(None, Kind::Playable) => out.push("no `playable`: the game's TSX (`game`), and its networks and orientation when the brief names them".into()),
(Some(_), k) => out.push(format!("`playable` is for a playable job, not a {k:?}: drop it, or make this `playable({{...}})`")),
_ => {}
}
out.extend(crate::rules::doctor(&m.rules));
if m.kind == Kind::Rules {
if m.aim.as_deref().is_none_or(|a| a.trim().is_empty()) {
out.push("no `aim`: the goal in the person's own words".into());
}
if m.rules.is_empty() {
out.push("no `rules`: what must hold before you stop, each a `run` command, a `file` or words a critic judges (`says`)".into());
}
}
if let Some(n) = m.name.as_deref().filter(|n| !is_name(n)) {
out.push(format!("name `{n}`: names are [a-z0-9_]"));
}
if m.kind == Kind::Kit && m.style.is_none() {
out.push("no `style`: one paragraph (era, palette, materials, wear, one fictional maker) every reference carries".into());
}
let mut seen = std::collections::BTreeSet::new();
for o in &m.objects {
if !seen.insert(o.id.as_str()) {
out.push(format!("object `{}` is listed twice", o.id));
}
if o.h.is_none() && o.dims.is_none() && o.max.is_none() {
out.push(format!("object `{}` has no size: give `h` (metres), `dims` for boxy things or `max` for flat ones", o.id));
}
if o.lod.is_some_and(|l| l > 4) {
out.push(format!("object `{}` has lod {}: 0 (the hero, half the frame or more) to 4 (far, under 2% of it)", o.id, o.lod.unwrap_or(0)));
}
if o.route.is_none() && m.kind == Kind::Scene {
out.push(format!("object `{}` has no route: solid, rule, gen, library or picture", o.id));
}
if matches!(o.route, Some(Route::Gen)) || m.kind == Kind::Kit {
if o.prompt.is_none() {
out.push(format!("object `{}` is generated but has no prompt: one object, its condition and materials", o.id));
}
}
}
let mut names = std::collections::BTreeSet::new();
for s in &m.shots {
if !names.insert(s.name.as_str()) {
out.push(format!("shot `{}` is listed twice", s.name));
}
if !is_name(&s.name) {
out.push(format!("shot `{}`: names are [a-z0-9_], the file it lands as", s.name));
}
if s.composition.is_none() {
out.push(format!("shot `{}` has no composition: the .tsx that renders it, for its framing sheet and lens chart", s.name));
}
}
out
}
/// A brief's `goal`: one goal, or several in order (a workflow inline). `after` orders them past the list's order.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(untagged)]
pub enum Goals {
One(Box<Goal>),
Many(Vec<Goal>),
}
impl Goals {
/// every goal, in the order written
pub fn all(&self) -> Vec<&Goal> {
match self {
Goals::One(g) => vec![g.as_ref()],
Goals::Many(v) => v.iter().collect(),
}
}
}
/// A goal's name: its own, else its kind's.
pub fn name_of(g: &Goal) -> String {
g.name.clone().unwrap_or_else(|| g.kind.name().to_string())
}
/// What the goals still lack together: names given twice, an `after` naming no goal.
pub fn doctor_all(gs: &Goals) -> Vec<String> {
let all = gs.all();
let mut out = Vec::new();
let names: Vec<String> = all.iter().map(|g| name_of(g)).collect();
let mut seen = std::collections::BTreeSet::new();
for n in &names {
if !seen.insert(n.as_str()) && all.len() > 1 {
out.push(format!("two goals are named `{n}`: give each its own `name`"));
}
}
for g in &all {
for a in g.after.iter().filter(|a| !names.contains(a)) {
out.push(format!("goal `{}` comes after `{a}`, which no goal is named", name_of(g)));
}
let n = name_of(g);
out.extend(doctor(g).into_iter().map(|d| if all.len() > 1 { format!("{n}: {d}") } else { d }));
}
out
}
+25 -7
View File
@@ -6,13 +6,14 @@
pub mod brief;
pub mod cut;
pub mod goal;
pub mod make;
pub mod parts;
pub mod playable;
pub mod rules;
pub mod script;
pub mod taste;
pub use brief::Brief;
pub use make::Make;
pub use goal::{Goal, Goals};
pub use parts::Parts;
pub use script::Script;
pub use taste::Taste;
@@ -30,19 +31,36 @@ macro_rules! decls {
($cfg:ident; $($t:ty),* $(,)?) => { vec![$(format!("export {}", <$t as TS>::decl(&$cfg))),*] };
}
/// The TypeScript declarations of every schema, one file's worth: sdk/raea/src/brief.gen.ts is this, checked by a test, and
/// `raea/brief` (sdk/raea/src/brief.ts) types its builders with it, so the declarations ship with the SDK.
/// The file the goal's declarations are written to, beside brief.gen.ts (which re-exports them)
pub const GOAL_FILE: &str = "brief-goal.gen";
/// The TypeScript declarations of every schema, two files' worth (a file stays under 500 lines, tools/size.sh):
/// sdk/raea/src/brief.gen.ts is this, the goal's (`goal_declarations`) re-exported from it, each checked by a test,
/// and `raea/brief` (sdk/raea/src/brief.ts) types its builders with them, so the declarations ship with the SDK.
pub fn declarations() -> String {
let cfg = Config::new();
let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `declarations`; edit the Rust, not this.".to_string()];
let mut out = vec![format!(
"// Generated from raea-core-brief (core/brief) by its `declarations`; edit the Rust, not this.\nimport type {{ Goals }} from \"./{GOAL_FILE}\";\nexport type * from \"./{GOAL_FILE}\";"
)];
out.extend(decls!(cfg;
brief::Brief, brief::Section, brief::Deliverable, brief::Reference, brief::Agent,
script::Script, script::Scene, script::Beat, script::Line,
taste::Taste, taste::TasteSection, taste::Rule, taste::RuleCheck, taste::RuleLevel, taste::Check,
parts::Parts, parts::Concept, parts::Level, parts::Count, parts::Part,
make::Make, make::Kind, make::Source, make::DialValue, make::Dial, make::Route, make::Origin, make::Pick, make::Object, make::Shot,
));
out.join("\n\n") + "\n"
}
/// The goal's declarations (what the work is held to: goal.rs, cut.rs, playable.rs, rules.rs): sdk/raea/src/brief-goal.gen.ts
pub fn goal_declarations() -> String {
let cfg = Config::new();
// a cut's beats are a script's (script.rs Beat)
let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `goal_declarations`; edit the Rust, not this.\nimport type { Beat } from \"./brief.gen\";".to_string()];
out.extend(decls!(cfg;
goal::Goal, goal::Kind, goal::Source, goal::DialValue, goal::Dial, goal::Route, goal::Origin, goal::Pick, goal::Object, goal::Shot, goal::Goals,
cut::Cut, cut::Quoted<u32>, cut::CutPlan, cut::Phrase, cut::Cta, cut::Open,
goal::Goal, goal::GoalRule,
playable::Playable, playable::Orientation,
rules::Rule,
));
out.join("\n\n") + "\n"
}
-330
View File
@@ -1,330 +0,0 @@
//! A job made to a frozen plan (docs/make.feature MK0): `make` on a project's brief.ts, written with `scene()`, `kit()`
//! or `shot()` from "raea/brief" before anything is built, and read here. One loop, three kinds: a scene (a dressed,
//! lit place), a kit (props that belong together) and a shot (stills or camera moves of a built scene). Every object
//! carries its real size and whether it came from the reference or was invented; every dial its value, where the value
//! came from, and what it meant here. `raea make status` (apps/make) holds the job to it.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use ts_rs::TS;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "lowercase")]
#[ts(rename = "MakeKind")]
pub enum Kind {
/// a dressed, lit place from references or a brief
Scene,
/// a set of props in one style, at real size, to drop into any scene
Kit,
/// stills or camera moves of a built scene, from words
Shot,
/// ads cut from footage to a client's brief: its deliverables, phrases, claims and CTA as rules (cut.rs, MK25)
Cut,
/// any other work held to a goal: commands that must pass, files that must exist, words a critic judges (goal.rs)
Goal,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
pub struct Make {
pub kind: Kind,
/// the pictures the job answers to (paths beside the brief): what is in it and where for a scene, the style for a kit
#[serde(default)]
#[ts(as = "Option<Vec<String>>", optional)]
pub references: Vec<String>,
/// one paragraph every reference prompt carries: era, palette, materials, wear, and one fictional maker
pub style: Option<String>,
/// by name, from the kind's set (DIALS); one left out is read from the references
#[serde(default)]
#[ts(as = "Option<BTreeMap<String, Dial>>", optional)]
pub dials: BTreeMap<String, Dial>,
#[serde(default)]
#[ts(as = "Option<Vec<Object>>", optional)]
pub objects: Vec<Object>,
#[serde(default)]
#[ts(as = "Option<Vec<Shot>>", optional)]
pub shots: Vec<Shot>,
/// the compositions the job's checks hold (relative to the brief): each needs a clean render or check newer than it
#[serde(default)]
#[ts(as = "Option<Vec<String>>", optional)]
pub compositions: Vec<String>,
/// what must exist when it's done, relative to the brief; replaces the kind's own list (`deliverables`)
#[serde(default)]
#[ts(as = "Option<Vec<String>>", optional)]
pub deliverables: Vec<String>,
/// the most critic rounds the job gets; at the cap it is delivered with what's still missing (8 by default)
pub rounds: Option<u32>,
/// a cut job's contract: the brief as rules (cut.rs)
pub cut: Option<crate::cut::Cut>,
/// a goal job's contract: the goal and its rules (goal.rs)
pub goal: Option<crate::goal::Goal>,
/// what the job shows but never delivers, relative to the brief (pictures, render tests, examples): each a file or a
/// `dir/` (review/ and previews/ when left out). Deliverables are what it hands over; previews are how it got there
#[serde(default)]
#[ts(as = "Option<Vec<String>>", optional)]
pub previews: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "lowercase")]
#[ts(rename = "MakeSource")]
pub enum Source {
/// set by the person who asked: an instruction, even when the reference says otherwise
Customer,
/// read from the references, because nobody set it
Reference,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(untagged)]
#[ts(rename = "MakeDialValue")]
pub enum DialValue {
Number(f64),
Text(String),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(untagged)]
#[ts(rename = "MakeDial")]
pub enum Dial {
/// `wear: 0.4`: the value alone, set by the person
Bare(DialValue),
/// `wear: { value: 0.4, source: "reference", means: "scuffed bakelite, worn paint on the edges" }`
Full {
value: DialValue,
#[ts(optional)]
source: Option<Source>,
/// what the value meant for this job, in one line
#[ts(optional)]
means: Option<String>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "lowercase")]
#[ts(rename = "MakeRoute")]
pub enum Route {
/// defined by numbers: Manifold solids, raea/room
Solid,
/// defined by a rule: fields, growth, instances
Rule,
/// defined by its looks: generated (raea gen)
Gen,
/// an exact asset that already exists
Library,
/// far background: a picture on a plane
Picture,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "lowercase")]
#[ts(rename = "MakeOrigin")]
pub enum Origin {
/// seen in a reference
Reference,
/// added to complete the place or the set, in the same world
Invented,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "MakePick")]
pub struct Pick {
/// "tripo-h31", "meshy", ...
pub generator: String,
/// one line: why this one ("sharper dial numerals; Tripo fused the handset to the cradle")
pub why: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "MakeObject")]
pub struct Object {
/// snake_case, unique in the job
pub id: String,
pub label: String,
/// real height in metres
pub h: Option<f64>,
/// [width, depth, height] in metres, for boxy things (generators invent depth)
pub dims: Option<[f64; 3]>,
/// largest extent in metres, for things that lie flat (tools, papers)
pub max: Option<f64>,
pub route: Option<Route>,
/// one object, its condition and its materials; never a real brand
pub prompt: Option<String>,
pub source: Option<Origin>,
/// where it is in reference 0: [x0, y0, x1, y1] in 0..1
pub crop: Option<[f64; 4]>,
/// where it stands in a scene: metres, the floor's front-left corner at the origin, rot 0 = facing the entrance
pub at: Option<[f64; 3]>,
pub rot: Option<f64>,
pub hero: Option<bool>,
/// how large it is planned to be seen, which is how much of it gets built: 0 the hero (half the frame or more),
/// 1 featured (under 50%), 2 dressing (under 20%), 3 background (under 8%: a grey box reads), 4 far (under 2%: a
/// silhouette). A render that shows it finer than this says so (`lod-closer`; `raea scene lod` lists every part)
pub lod: Option<u8>,
pub pick: Option<Pick>,
/// what was fixed by script ("glass made transmissive, label kept opaque")
#[serde(default)]
#[ts(as = "Option<Vec<String>>", optional)]
pub fixes: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "MakeShot")]
pub struct Shot {
/// [a-z0-9_]: the file it lands as (out/shots/<name>.png or .mp4)
pub name: String,
/// in a crew's words: "slow push along the counter, rack focus to the register"
pub description: Option<String>,
/// static, dolly, truck, pedestal, crane, pan, tilt, orbit, dollyZoom, path
#[serde(rename = "move")]
#[ts(rename = "move")]
pub move_: Option<String>,
pub seconds: Option<f64>,
pub lens: Option<f64>,
/// none, subtle, walk
pub handheld: Option<String>,
/// a still rather than a move
pub still: Option<bool>,
/// the composition that renders it (relative to the brief): `raea make framing` and `lenschart` draw it
pub composition: Option<String>,
/// its frame rate, for the frames `seconds` spans (30 when left out)
pub fps: Option<f64>,
}
impl Kind {
/// as brief.ts writes it, and as raea judge's rubrics are named
pub fn name(self) -> &'static str {
// in the enum's order
["scene", "kit", "shot", "cut", "goal"][self as usize]
}
}
/// Each kind's dials: what may be set, and what an unset one is read from the references as.
pub fn dials(kind: Kind) -> &'static [&'static str] {
match kind {
Kind::Scene => &["density", "tidiness", "wear", "wetness", "time_of_day", "weather", "atmosphere", "power", "warmth", "look"],
Kind::Kit => &["count", "variety", "detail", "wear", "wetness", "warmth", "look"],
Kind::Shot => &["res", "seconds", "lens", "handheld", "look"],
Kind::Cut => &["look"],
Kind::Goal => &[],
}
}
/// The round cap when the plan names none: AnyKit's and raea judge's 8.
pub const ROUNDS: u32 = 8;
/// What must exist when the job is done, relative to the brief's folder: the plan's own list, else the kind's.
pub fn deliverables(m: &Make) -> Vec<String> {
if !m.deliverables.is_empty() {
return m.deliverables.clone();
}
match m.kind {
// the stills are counted (three or more), not named: apps/make checks the folder
Kind::Scene => vec!["out/stills/".into()],
Kind::Kit => {
let mut v: Vec<String> = m
.objects
.iter()
.flat_map(|o| [format!("out/kit/{0}/{0}.glb", o.id), format!("out/kit/{0}/{0}_lod1.glb", o.id), format!("out/kit/thumbs/{}.png", o.id)])
.collect();
// the reference sheet every reference was checked on before any 3D (MK10)
v.extend(["out/kit/lineup.png".into(), "out/kit/kit.json".into(), "review/refs.png".into()]);
v
}
// a shot is a still or a move, so either file answers; apps/make reads `a|b`
Kind::Shot => m.shots.iter().map(|s| format!("out/shots/{0}.png|out/shots/{0}.mp4", s.name)).collect(),
Kind::Cut => m.cut.as_ref().map(crate::cut::deliverables).unwrap_or_default(),
// a goal's `file` rules
Kind::Goal => m.goal.iter().flat_map(|g| &g.rules).filter_map(|r| r.file.clone()).collect(),
}
}
/// What the job shows but doesn't deliver: the plan's own list, else review/ and previews/.
pub fn previews(m: &Make) -> Vec<String> {
if m.previews.is_empty() { vec!["review/".into(), "previews/".into()] } else { m.previews.clone() }
}
/// A name a file lands as: [a-z0-9_], not empty.
pub fn is_name(s: &str) -> bool {
!s.is_empty() && s.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
}
/// What the plan still lacks before it can be built against, each with what to do. Empty when it's ready.
pub fn doctor(m: &Make) -> Vec<String> {
let mut out = Vec::new();
let allowed = dials(m.kind);
for name in m.dials.keys().filter(|k| !allowed.contains(&k.as_str())) {
out.push(format!("dial `{name}` isn't one of a {:?}'s ({}): drop it or say it in `style`", m.kind, allowed.join(", ")));
}
match m.kind {
Kind::Shot if m.shots.is_empty() => out.push("no shots: list each with a name and a description".into()),
Kind::Scene | Kind::Kit if m.objects.is_empty() => out.push("no objects: list every object with its real size and route".into()),
_ => {}
}
match (&m.cut, m.kind) {
(Some(c), Kind::Cut) => out.extend(crate::cut::doctor(c)),
(None, Kind::Cut) => out.push("no `cut`: the brief as rules (count, cuts, say, never, cta, open), each quoting it".into()),
(Some(_), k) => out.push(format!("`cut` is for a cut job, not a {k:?}: drop it, or make this `cut({{...}})`")),
_ => {}
}
match (&m.goal, m.kind) {
(Some(g), Kind::Goal) => out.extend(crate::goal::doctor(g)),
(None, Kind::Goal) => out.push("no `goal`: the goal in the person's words and its `rules`".into()),
(Some(_), k) => out.push(format!("`goal` is for a goal job, not a {k:?}: drop it, or make this `goal({{...}})`")),
_ => {}
}
if m.kind == Kind::Kit && m.style.is_none() {
out.push("no `style`: one paragraph (era, palette, materials, wear, one fictional maker) every reference carries".into());
}
let mut seen = std::collections::BTreeSet::new();
for o in &m.objects {
if !seen.insert(o.id.as_str()) {
out.push(format!("object `{}` is listed twice", o.id));
}
if o.h.is_none() && o.dims.is_none() && o.max.is_none() {
out.push(format!("object `{}` has no size: give `h` (metres), `dims` for boxy things or `max` for flat ones", o.id));
}
if o.lod.is_some_and(|l| l > 4) {
out.push(format!("object `{}` has lod {}: 0 (the hero, half the frame or more) to 4 (far, under 2% of it)", o.id, o.lod.unwrap_or(0)));
}
if o.route.is_none() && m.kind == Kind::Scene {
out.push(format!("object `{}` has no route: solid, rule, gen, library or picture", o.id));
}
if matches!(o.route, Some(Route::Gen)) || m.kind == Kind::Kit {
if o.prompt.is_none() {
out.push(format!("object `{}` is generated but has no prompt: one object, its condition and materials", o.id));
}
}
}
let mut names = std::collections::BTreeSet::new();
for s in &m.shots {
if !names.insert(s.name.as_str()) {
out.push(format!("shot `{}` is listed twice", s.name));
}
if !is_name(&s.name) {
out.push(format!("shot `{}`: names are [a-z0-9_], the file it lands as", s.name));
}
if s.composition.is_none() {
out.push(format!("shot `{}` has no composition: the .tsx that renders it, for its framing sheet and lens chart", s.name));
}
}
out
}
/// One gate as `raea make status` lists it: its name, the file, item or rule it's about, whether it's clear, and what
/// it says. A cut's gates come from raea-runtime-cut-plan, a goal's from raea-runtime-goal-plan.
#[derive(Debug, Clone, PartialEq)]
pub struct Gate {
pub name: &'static str,
pub of: Option<String>,
pub clear: bool,
pub says: String,
}
+1 -1
View File
@@ -1,6 +1,6 @@
//! An object's parts (NAME.parts.ts, `parts()` from "raea/brief"), written before any geometry and frozen when
//! building starts (docs/handoff/solids.md, "The plan is the contract"; named parts since 11-20, so "plan" is only a
//! project's plan.org, docs/plan.feature PL8a). Generic over what's made: a crown, a feather and a rocking horse are all a concept and a tree of
//! project's plan.ts, docs/plan.feature PL8a). Generic over what's made: a crown, a feather and a rocking horse are all a concept and a tree of
//! named parts, each with a level, a count, and a material and style it has or inherits.
use std::collections::BTreeMap;
+125
View File
@@ -0,0 +1,125 @@
//! A playable goal (docs/playables.feature PA19): a raea game exported as a playable ad by `raea playable`, held to its
//! pages. The game is one TSX that renders as the video ad and exports for each network; the goal names it, the
//! networks it ships to and its orientation (both, unless the brief says one), and its deliverables are what the export
//! writes into out/playable/: each network's page or ZIP, the preview, and the export's manifest, which raea goal's
//! playable pack reads (sizes, compositions, when it was exported).
use serde::{Deserialize, Serialize};
use ts_rs::TS;
/// The networks `raea playable` writes for (apps/playable pages.rs NETWORKS, preview last)
pub const NETWORKS: &[&str] = &[
"applovin",
"unity",
"google",
"meta",
"moloco",
"mintegral",
"tiktok",
"liftoff",
];
/// The networks whose package is a ZIP (the rest are one HTML page)
const ZIPPED: &[&str] = &["google", "mintegral", "tiktok"];
/// Where the export writes, relative to the brief
pub const OUT: &str = "out/playable";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "lowercase")]
#[ts(rename = "PlayableOrientation")]
pub enum Orientation {
/// a portrait and a landscape composition, the host playing the one nearest the screen
Both,
Portrait,
Landscape,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields, rename = "PlayableGoal")]
pub struct Playable {
/// the game's TSX, relative to the brief: it renders as the video ad and exports as the playable
pub game: String,
/// the files' name ([a-z0-9_], `NAME-NETWORK.html`); the game's file name when left out
pub name: Option<String>,
/// the networks it ships to (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff); all of them when
/// left out. The preview page is always made: it's what the review plays
#[serde(default)]
#[ts(as = "Option<Vec<String>>", optional)]
pub networks: Vec<String>,
/// both unless the brief says one: Unity, AppLovin, Moloco and Mintegral want both
pub orientation: Option<Orientation>,
/// [least, most] seconds of play before the end card (15 to 60 by default)
pub seconds: Option<[f64; 2]>,
/// the same game rendered as the video ad too, as out/cuts/NAME_9x16.mp4 (PA17)
pub video: Option<bool>,
}
/// The name its files land as: its own, else the game's file name, as `raea playable` names them
pub fn name(p: &Playable) -> String {
p.name.clone().unwrap_or_else(|| {
std::path::Path::new(&p.game)
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("playable")
.to_string()
})
}
/// The networks it ships to, in raea's order
pub fn networks(p: &Playable) -> Vec<&'static str> {
NETWORKS
.iter()
.copied()
.filter(|n| p.networks.is_empty() || p.networks.iter().any(|m| m == n))
.collect()
}
/// What the export must have written: each network's page or ZIP, the preview and the manifest, and the video ad
pub fn deliverables(p: &Playable) -> Vec<String> {
let n = name(p);
let mut out: Vec<String> = networks(p)
.iter()
.map(|net| {
format!(
"{OUT}/{n}-{net}.{}",
if ZIPPED.contains(net) { "zip" } else { "html" }
)
})
.collect();
out.push(format!("{OUT}/{n}-preview.html"));
out.push(format!("{OUT}/{n}.playable.json"));
if p.video == Some(true) {
out.push(format!("out/cuts/{n}_9x16.mp4"));
}
out
}
/// What the playable still lacks before it can be built against
pub fn doctor(p: &Playable) -> Vec<String> {
let mut out = Vec::new();
if !p.game.ends_with(".tsx") {
out.push(format!(
"`game` {:?}: the game's TSX beside the brief (playable.tsx)",
p.game
));
}
if let Some(n) = p.name.as_deref().filter(|n| !crate::goal::is_name(n)) {
out.push(format!("playable name `{n}`: names are [a-z0-9_]"));
}
for n in p
.networks
.iter()
.filter(|n| !NETWORKS.contains(&n.as_str()))
{
out.push(format!(
"network `{n}` isn't one raea exports to ({})",
NETWORKS.join(", ")
));
}
if let Some([a, b]) = p.seconds {
if !(a > 0.0 && a <= b) {
out.push(format!("seconds [{a}, {b}]: least then most, both over 0"));
}
}
out
}
+49
View File
@@ -0,0 +1,49 @@
//! A goal's rules (docs/goal.feature): what must hold before the agent may stop, on any goal of brief.ts (11-26, Shane:
//! "we essentially just need to make sure that it can't stop unless all the goals pass, or all the rules in the
//! brief"). `/goal` in raea.app and an agent's own goal are this: the goal's `aim` in the person's words, then each
//! thing that must hold, as a command that must pass, a file that must exist, or words a fresh critic must find true.
//! raea/goal's rule packs (sdk/goal/src/packs/goal.ts) decide from them whether the agent may stop; the agent saying so
//! never does.
use serde::{Deserialize, Serialize};
use ts_rs::TS;
/// One thing that must hold. Exactly one of `run`, `file` or `says`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "GoalRule")]
pub struct Rule {
/// a short name: [a-z0-9_], how status, the critic and NOTES.md name it
pub id: String,
/// a command that must exit 0, run in the brief's folder (`bun test`, `raea check edit.tsx`)
pub run: Option<String>,
/// the seconds `run` gets before it counts as failed (300 when left out)
pub timeout: Option<u32>,
/// a file that must exist, relative to the brief (`a|b`: either; `dir/`: three or more pictures in it)
pub file: Option<String>,
/// words that must be true of the work, judged by a fresh critic (`raea goal judge`), never by the agent that did it
pub says: Option<String>,
}
/// What a goal's rules still lack, each with what to do. Empty when they're ready.
pub fn doctor(rules: &[Rule]) -> Vec<String> {
let mut out = Vec::new();
let mut seen = std::collections::BTreeSet::new();
for r in rules {
if !crate::goal::is_name(&r.id) {
out.push(format!("rule `{}`: ids are [a-z0-9_]", r.id));
}
if !seen.insert(r.id.as_str()) {
out.push(format!("rule `{}` is listed twice", r.id));
}
let n = [r.run.is_some(), r.file.is_some(), r.says.is_some()].iter().filter(|x| **x).count();
if n != 1 {
out.push(format!("rule `{}` needs exactly one of `run`, `file` or `says` (it has {n})", r.id));
}
if r.timeout.is_some() && r.run.is_none() {
out.push(format!("rule `{}` has a `timeout` but no `run`", r.id));
}
}
out
}
+76 -19
View File
@@ -1,14 +1,18 @@
use super::*;
#[test]
fn declarations_match_the_committed_file() {
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/raea/src/brief.gen.ts");
let now = declarations();
if std::env::var_os("RAEA_WRITE").is_some() {
std::fs::write(path, &now).unwrap();
fn declarations_match_the_committed_files() {
let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/raea/src");
for (file, now) in [("brief.gen.ts".to_string(), declarations()), (format!("{GOAL_FILE}.ts"), goal_declarations())] {
let path = format!("{dir}/{file}");
if std::env::var_os("RAEA_WRITE").is_some() {
std::fs::write(&path, &now).unwrap();
}
let committed = std::fs::read_to_string(&path).unwrap_or_default();
assert!(committed == now, "sdk/raea/src/{file} is out of date: RAEA_WRITE=1 cargo test -p raea-core-brief");
let lines = now.lines().count();
assert!(lines <= 500, "sdk/raea/src/{file} is {lines} lines: split it (tools/size.sh)");
}
let committed = std::fs::read_to_string(path).unwrap_or_default();
assert!(committed == now, "sdk/raea/src/brief.gen.ts is out of date: RAEA_WRITE=1 cargo test -p raea-core-brief");
}
#[test]
@@ -99,38 +103,91 @@ fn an_older_brief_with_stages_still_reads_and_never_writes_them() {
}
#[test]
fn a_make_plan_reads_and_its_doctor_names_what_it_lacks() {
let b: Brief = read("brief.ts", r#"{"title": "Flight desk kit", "make": {"kind": "kit",
fn a_goal_reads_and_its_doctor_names_what_it_lacks() {
let b: Brief = read("brief.ts", r#"{"title": "Flight desk kit", "goal": {"kind": "kit",
"dials": {"count": 2, "wear": {"value": 0.4, "source": "customer", "means": "scuffed bakelite"}, "time_of_day": "night"},
"objects": [{"id": "phone", "label": "Rotary phone", "h": 0.12, "prompt": "a rotary desk phone", "source": "invented"},
{"id": "ashtray", "label": "Glass ashtray"}]}}"#).unwrap();
let m = b.make.as_ref().unwrap();
assert_eq!(m.kind, make::Kind::Kit);
let d = make::doctor(m);
let gs = b.goal.as_ref().unwrap();
let m = gs.all()[0];
assert_eq!(m.kind, goal::Kind::Kit);
let d = goal::doctor(m);
assert!(d.iter().any(|x| x.contains("`time_of_day`")), "a scene's dial on a kit: {d:?}");
assert!(d.iter().any(|x| x.contains("no `style`")), "{d:?}");
assert!(d.iter().any(|x| x.contains("`ashtray` has no size")), "{d:?}");
assert!(d.iter().any(|x| x.contains("`ashtray` is generated but has no prompt")), "{d:?}");
assert!(!d.iter().any(|x| x.contains("`phone`")), "{d:?}");
assert!(brief::doctor(&b).iter().any(|x| x.starts_with("make: ")));
let want = make::deliverables(m);
assert!(brief::doctor(&b).iter().any(|x| x.starts_with("goal: ")));
let want = goal::deliverables(m);
assert!(want.contains(&"out/kit/phone/phone_lod1.glb".to_string()) && want.contains(&"out/kit/kit.json".to_string()), "{want:?}");
}
// MK22: an object's planned detail, 0 (the hero) to 4 (far)
#[test]
fn an_object_plans_its_detail_and_the_doctor_holds_it_to_five_levels() {
let m: make::Make = read("make", r#"{"kind": "scene", "objects": [
let m: goal::Goal = read("goal", r#"{"kind": "scene", "objects": [
{"id": "kiosk", "label": "Kiosk", "h": 2.4, "route": "solid", "lod": 3},
{"id": "tower", "label": "Tower", "h": 40, "route": "picture", "lod": 7}]}"#).unwrap();
assert_eq!(m.objects[0].lod, Some(3));
let d = make::doctor(&m);
let d = goal::doctor(&m);
assert!(d.iter().any(|x| x.contains("`tower` has lod 7")) && !d.iter().any(|x| x.contains("`kiosk`")), "{d:?}");
}
#[test]
fn a_shot_plan_wants_a_still_or_a_move_per_shot() {
let m: make::Make = read("make", r#"{"kind": "shot", "shots": [{"name": "counter_push", "move": "push_in"}, {"name": "Bad Name"}]}"#).unwrap();
assert_eq!(make::deliverables(&m)[0], "out/shots/counter_push.png|out/shots/counter_push.mp4");
assert!(make::doctor(&m).iter().any(|x| x.contains("`Bad Name`")));
let m: goal::Goal = read("goal", r#"{"kind": "shot", "shots": [{"name": "counter_push", "move": "push_in"}, {"name": "Bad Name"}]}"#).unwrap();
assert_eq!(goal::deliverables(&m)[0], "out/shots/counter_push.png|out/shots/counter_push.mp4");
assert!(goal::doctor(&m).iter().any(|x| x.contains("`Bad Name`")));
}
// goal.feature GL2: several goals in order are a workflow inline; names, `after` and rules on any kind are held
#[test]
fn several_goals_are_a_workflow_and_each_is_held_to_its_rules() {
let b: Brief = read("brief.ts", r#"{"title": "Spring", "goal": [
{"kind": "cut", "name": "cut", "step": "edit", "rules": [{"id": "tests", "run": "bun test"}]},
{"kind": "rules", "name": "deliver", "after": ["cut", "grade"], "rules": [{"id": "Bad", "file": "out/a.mp4", "says": "x"}]}]}"#).unwrap();
let gs = b.goal.as_ref().unwrap();
assert_eq!(gs.all().len(), 2);
assert_eq!(gs.all()[0].rules[0].run.as_deref(), Some("bun test"));
let d = goal::doctor_all(gs);
assert!(d.iter().any(|x| x.contains("after `grade`, which no goal is named")), "{d:?}");
assert!(d.iter().any(|x| x.starts_with("deliver: no `aim`")), "{d:?}");
assert!(d.iter().any(|x| x.starts_with("deliver: rule `Bad`: ids are")), "{d:?}");
assert!(d.iter().any(|x| x.contains("needs exactly one of")), "{d:?}");
let one: Brief = read("brief.ts", r#"{"title": "x", "goal": {"kind": "rules", "aim": "ship it", "rules": [{"id": "ok", "run": "true"}]}}"#).unwrap();
assert!(goal::doctor_all(one.goal.as_ref().unwrap()).is_empty());
}
#[test]
fn a_playable_goal_delivers_each_networks_page_the_preview_and_the_manifest() {
let g: crate::goal::Goal = serde_json::from_str(r#"{"kind":"playable","aim":"a runner for a tea brand","playable":{"game":"playable.tsx","networks":["applovin","google"],"video":true}}"#).unwrap();
assert_eq!(
crate::goal::deliverables(&g),
[
"out/playable/playable-applovin.html",
"out/playable/playable-google.zip",
"out/playable/playable-preview.html",
"out/playable/playable.playable.json",
"out/cuts/playable_9x16.mp4"
]
);
assert!(
crate::goal::doctor(&g).is_empty(),
"{:?}",
crate::goal::doctor(&g)
);
// both orientations unless the brief names one: `raea playable`'s own default
assert_eq!(g.playable.as_ref().unwrap().orientation, None);
let bad: crate::goal::Goal = serde_json::from_str(
r#"{"kind":"playable","aim":"x","playable":{"game":"game.ts","networks":["vungle"]}}"#,
)
.unwrap();
let d = crate::goal::doctor(&bad).join("\n");
assert!(d.contains("game.ts") && d.contains("vungle"), "{d}");
let none: crate::goal::Goal = serde_json::from_str(r#"{"kind":"playable","aim":"x"}"#).unwrap();
assert!(
crate::goal::doctor(&none)
.iter()
.any(|l| l.starts_with("no `playable`"))
);
}
+2 -2
View File
@@ -1,6 +1,6 @@
//! The project's record (docs/direction.feature DR3): what each render and each `raea check` found, one JSON file
//! apiece under the project's .raea/record/, with the commit the project was at. `raea findings` reads it back across
//! renders (what was fixed, what is new, what is carried) and `raea next` reads what stands. A file outside a raea
//! renders (what was fixed, what is new, what is carried) and `raea goal next` reads what stands. A file outside a raea
//! project (no .raea/project at or above it) has no record.
use std::path::{Path, PathBuf};
@@ -64,7 +64,7 @@ fn real(p: &Path) -> PathBuf {
}
/// A path as the record names it: relative to the project when it's in it, with '/' between its parts on Windows too (a
/// project's record moves between machines, and `raea next` quotes it in commands).
/// project's record moves between machines, and `raea goal next` quotes it in commands).
pub fn rel(project: &Path, p: &Path) -> String {
let full = real(p);
full.strip_prefix(project).map(|r| r.to_string_lossy().replace(std::path::MAIN_SEPARATOR, "/")).unwrap_or_else(|_| full.display().to_string())
+1 -1
View File
@@ -120,7 +120,7 @@ fn wanted() -> Option<&'static ([f64; 3], [f64; 3], Option<f64>)> {
}
/// RAEA_LENS="mm": the scene's own camera kept where it is, with that focal length's field of view on a full-frame
/// sensor (a lens chart, docs/make.feature MK15).
/// sensor (a lens chart, docs/goal.feature MK15).
fn lens() -> Option<f64> {
static LENS: OnceLock<Option<f64>> = OnceLock::new();
*LENS.get_or_init(|| std::env::var("RAEA_LENS").ok()?.trim().parse::<f64>().ok().filter(|mm| *mm > 0.0).map(fov_of_lens))
+29 -7
View File
@@ -109,10 +109,26 @@ fn hash_props(m: &Map<String, Value>, h: &mut impl Hasher, take: impl Fn(&str) -
}
}
/// A standard material's maps whose picture a render swaps frame by frame (raea-sys-material's SwappedMaps,
/// docs/render-memory.feature RM6): a change of picture keys the map's column instead of cutting the part's track.
/// The packed roughness and metalness maps are one texture made from two pictures, so they still cut.
pub const SWAPPED_MAPS: [(&str, &str); 5] = [("map", "map"), ("normalMap", "normal_map"), ("metallicRoughnessMap", "mr_map"), ("aoMap", "ao_map"), ("emissiveMap", "emissive_map")];
/// Whether a part's standard material takes its pictures frame by frame in a render (SWAPPED_MAPS): a plain
/// standard or physical surface, none of the surfaces built over it (a grid, paint, wear, a procedural pattern, a
/// shader), whose maps are made into their own material once.
pub fn swaps_maps(it: &Item) -> bool {
let Some(m) = &it.material else { return false };
matches!(&*m.kind, "MeshStandardMaterial" | "MeshPhysicalMaterial")
&& !["grid", "paint", "wear", "procedural", "shader", "toon"].iter().any(|k| m.props.contains_key(*k))
&& !["shader", "three", "surface"].iter().any(|k| it.props.contains_key(*k))
}
/// A part's kept inputs as one number: what its row takes from the frame it's spawned in (its shape, its material's
/// maps and modes, its words and their glyphs, a model's file). Two frames of a part with the same number make the
/// same kept columns.
pub fn spawn_sig(it: &Item) -> u64 {
/// same kept columns. With `swapped`, a swapped map's picture is left out (whether it has one still counts), as a
/// render keys it (SWAPPED_MAPS) rather than cutting the part's track for it; without, every picture counts.
pub fn spawn_sig(it: &Item, swapped: bool) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
it.kind.hash(&mut h);
match it.kind {
@@ -120,9 +136,14 @@ pub fn spawn_sig(it: &Item) -> u64 {
it.shape.hash(&mut h);
if let Some(m) = &it.material {
m.kind.hash(&mut h);
let swap = swapped && swaps_maps(it);
let picture = |k: &str| swap && SWAPPED_MAPS.iter().any(|(p, _)| *p == k) && m.props.get(k).and_then(Value::as_str).is_some_and(|s| !s.starts_with("render:"));
// a three.js shader's spec is its uniforms and its source, the one keyed and the other its identity
if &*m.kind != "ThreeShaderMaterial" {
hash_props(&m.props, &mut h, |k| !MAT_LIVE.contains(&k));
hash_props(&m.props, &mut h, |k| !MAT_LIVE.contains(&k) && !picture(k));
}
for (p, _) in SWAPPED_MAPS.iter().filter(|(p, _)| picture(p)) {
p.hash(&mut h);
}
}
hash_props(&it.props, &mut h, |k| MESH_KEPT.contains(&k));
@@ -147,7 +168,7 @@ pub fn spawn_sig(it: &Item) -> u64 {
h.finish()
}
/// Tracks cut where a part's kept inputs change: each run of frames with the same spawn_sig is a track of its own
/// Tracks cut where a part's kept inputs change: each run of frames with the same spawn_sig (swapped maps left out) is a track of its own
/// (`ID~1`, `ID~2` after the first), so a render's row never holds one frame's shape or words over another frame's.
pub fn split_kept(tracks: Vec<(String, Vec<Option<Item>>)>) -> Vec<(String, Vec<Option<Item>>)> {
let mut out = Vec::with_capacity(tracks.len());
@@ -161,7 +182,8 @@ pub fn split_kept(tracks: Vec<(String, Vec<Option<Item>>)>) -> Vec<(String, Vec<
let mut runs: Vec<(u64, Vec<Option<Item>>)> = Vec::new();
for (i, slot) in track.into_iter().enumerate() {
let Some(it) = slot else { continue };
let s = spawn_sig(&it);
// a render keys a swapped map's picture (SWAPPED_MAPS) rather than cutting for it
let s = spawn_sig(&it, true);
if runs.last().is_none_or(|(r, _)| *r != s) {
runs.push((s, vec![None; n]));
}
@@ -197,7 +219,7 @@ pub struct KeptInputs {
impl KeptInputs {
pub fn of(it: &Item) -> KeptInputs {
KeptInputs { sig: spawn_sig(it), props: it.props.clone(), mat: it.material.as_ref().map(|m| m.props.clone()), shape: it.shape.clone() }
KeptInputs { sig: spawn_sig(it, false), props: it.props.clone(), mat: it.material.as_ref().map(|m| m.props.clone()), shape: it.shape.clone() }
}
/// Whether `it` has the kept inputs these were taken from; when it has, its props are held from now on.
@@ -210,7 +232,7 @@ impl KeptInputs {
if Arc::ptr_eq(&self.props, &it.props) && held(&self.mat, it.material.as_ref().map(|m| &m.props)) && self.shape == it.shape {
return true;
}
if spawn_sig(it) != self.sig {
if spawn_sig(it, false) != self.sig {
return false;
}
*self = KeptInputs::of(it);
+2
View File
@@ -13,6 +13,8 @@ manifold-rust = "0.16.0"
skrifa = "0.44"
raea-core-fonts = { path = "../fonts" }
serde_json = "1"
# content names for kept BufferMesh text (buffer.rs kept_buffer)
blake3 = "1.8"
# blended distance fields and generators (trees, lofts, terrain, rosettes), meshed then closed into solids
raea-core-sdf = { path = "../sdf" }
raea-core-grow = { path = "../grow" }
+48
View File
@@ -128,6 +128,42 @@ pub fn export_tris(t: &Tris, uvs: Option<&[[f32; 2]]>, path: &str, format: &str)
Ok(bytes.len())
}
/// A <BufferMesh>'s text from this long on is kept on disk and named by its content (kept_buffer).
pub const KEEP_BUFFER_AT: usize = 1 << 16;
/// A long BufferMesh shape (`buffer:{json}`) as `buffer:@NAME`: its JSON written once to raea's caches
/// (buffers/NAME.json, NAME its content's BLAKE3), so what holds the shape holds 40 characters
/// (docs/render-memory.feature RM8). halcyon's palms were 263 MB of vertex arrays as text, held by the React scene,
/// every frame's program row, the store and the evaluator: two of them 51 MB each. None for a short one, one already
/// kept, or when the caches folder can't be written (the text then goes as it is).
pub fn kept_buffer(expr: &str) -> Option<String> {
let json = expr.strip_prefix("buffer:")?;
if json.len() < KEEP_BUFFER_AT || json.starts_with('@') {
return None;
}
let hex = blake3::hash(json.as_bytes()).to_hex();
let name = &hex.as_str()[..32];
let dir = crate::kept::caches()?.join("buffers");
let p = dir.join(format!("{name}.json"));
if !p.exists() {
let part = dir.join(format!(".{name}.{}.part", std::process::id()));
std::fs::create_dir_all(&dir).ok()?;
std::fs::write(&part, json).ok()?;
std::fs::rename(&part, &p).ok()?;
}
Some(format!("buffer:@{name}"))
}
/// A buffer shape's JSON (what follows `buffer:`): its own text, or the kept file `@NAME` names (kept_buffer).
pub fn buffer_json(b: &str) -> Result<std::borrow::Cow<'_, str>, String> {
let Some(name) = b.strip_prefix('@') else { return Ok(std::borrow::Cow::Borrowed(b)) };
if name.len() != 32 || !name.bytes().all(|c| c.is_ascii_hexdigit()) {
return Err(format!("buffer:@{name}: not a kept buffer's name"));
}
let p = crate::kept::caches().ok_or("no caches folder for a kept buffer")?.join("buffers").join(format!("{name}.json"));
std::fs::read_to_string(&p).map(std::borrow::Cow::Owned).map_err(|e| format!("buffer:@{name}: {}: {e}", p.display()))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -160,4 +196,16 @@ mod tests {
assert_eq!((v.len(), i.len()), (18, 6));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_long_buffer_is_kept_by_its_content_and_read_back() {
let pos: Vec<String> = (0..36000).map(|i| format!("{}", i % 7)).collect();
let expr = format!("buffer:{{\"positions\": [{}]}}", pos.join(", "));
assert!(expr.len() > KEEP_BUFFER_AT);
let Some(k) = kept_buffer(&expr) else { return }; // no caches folder here: nothing to check
assert!(k.starts_with("buffer:@") && k.len() == 8 + 32, "{k}");
assert_eq!(kept_buffer(&expr).as_deref(), Some(k.as_str()), "the same text, the same name");
assert_eq!(buffer_json(&k[7..]).unwrap(), &expr[7..]);
assert!(kept_buffer("buffer:{\"positions\": [0, 0, 0]}").is_none(), "a short one stays as it is");
}
}
+60
View File
@@ -0,0 +1,60 @@
//! A cache by key in two generations of at most `cap` bytes each, for what's costly to make and too big to keep all
//! of: core/shape's meshes (`cached`) and runtime/calls' built Manifolds (docs/render-memory.feature). One asked for
//! again moves to the newest generation and stays; one made and never asked for again goes a generation later, so two
//! generations at most are held. An entry's weight is its holder's to say; its key counts too.
use std::collections::HashMap;
pub struct Generations<V> {
now: HashMap<String, (V, usize)>,
old: HashMap<String, (V, usize)>,
/// the newest generation's bytes
bytes: usize,
cap: usize,
}
impl<V: Clone> Generations<V> {
pub fn new(cap: usize) -> Self {
Generations { now: HashMap::new(), old: HashMap::new(), bytes: 0, cap }
}
/// What's held for `key`, in either generation: one from the older is held again in the newest.
pub fn get(&mut self, key: &str) -> Option<V> {
if let Some((v, _)) = self.now.get(key) {
return Some(v.clone());
}
let (v, weight) = self.old.remove(key)?;
self.hold(key, v.clone(), weight);
Some(v)
}
/// `v`, weighing `weight` bytes, held for `key` in the newest generation, which becomes the older one when it
/// would pass the cap.
pub fn hold(&mut self, key: &str, v: V, weight: usize) {
let bytes = weight + key.len();
if self.bytes + bytes > self.cap && !self.now.is_empty() {
self.old = std::mem::take(&mut self.now);
self.bytes = 0;
}
self.bytes += bytes;
self.now.insert(key.to_string(), (v, weight));
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn held_entries_go_a_generation_at_a_time_and_what_is_asked_again_stays() {
// entries of a quarter of a generation each
let mut g = Generations::new(4000);
g.hold("kept", 1u8, 996);
for i in 0..12 {
g.hold(&format!("bar {i:02}"), 1u8, 994);
assert!(g.get("kept").is_some(), "asked each time, it stays (after bar {i})");
}
assert!(g.get("bar 00").is_none(), "made once and never asked again, it went");
assert!(g.now.len() + g.old.len() <= 8, "two generations at most: {} + {}", g.now.len(), g.old.len());
}
}
+1 -1
View File
@@ -10,7 +10,7 @@ use std::path::PathBuf;
/// raea's caches folder, as raea-io-home names it (this crate is below it): ~/Library/Caches/raea on macOS,
/// %LOCALAPPDATA%\raea\cache on Windows, $XDG_CACHE_HOME/raea or ~/.cache/raea elsewhere.
fn caches() -> Option<PathBuf> {
pub(crate) fn caches() -> Option<PathBuf> {
let base = PathBuf::from(std::env::var_os(if cfg!(windows) { "LOCALAPPDATA" } else { "HOME" })?);
if base.as_os_str().is_empty() {
return None;
+12 -48
View File
@@ -34,9 +34,12 @@ mod kept;
mod mesh;
mod parse;
mod sphere;
pub mod generations;
pub use generations::Generations;
pub use sphere::{SphereOf, cuboid_of, cylinder_of, plane_of, sphere_of};
pub use buffer::{buffer_tris, export_tris};
pub use buffer::{buffer_json, buffer_tris, export_tris, kept_buffer, KEEP_BUFFER_AT};
pub use mesh::{export, from_mesh, read_glb, read_obj, to_mesh};
use std::collections::HashMap;
@@ -211,47 +214,22 @@ const KEEP_MS: f64 = 2.0;
/// and the end checks once more.
const GEN_BYTES: usize = 16 << 20;
/// The shapes held, the newest generation and the one before, and the newest's bytes.
#[derive(Default)]
struct Held {
now: HashMap<String, std::sync::Arc<Tris>>,
old: HashMap<String, std::sync::Arc<Tris>>,
bytes: usize,
}
impl Held {
fn get(&mut self, expr: &str) -> Option<std::sync::Arc<Tris>> {
if let Some(t) = self.now.get(expr) {
return Some(t.clone());
}
let t = self.old.remove(expr)?;
self.hold(expr, &t);
Some(t)
}
/// `t` held for `expr` in the newest generation, which becomes the one before when it would pass GEN_BYTES.
fn hold(&mut self, expr: &str, t: &std::sync::Arc<Tris>) {
let bytes = (t.positions.len() + t.normals.len()) * 12 + expr.len();
if self.bytes + bytes > GEN_BYTES && !self.now.is_empty() {
self.old = std::mem::take(&mut self.now);
self.bytes = 0;
}
self.bytes += bytes;
self.now.insert(expr.to_string(), t.clone());
}
/// What a mesh weighs as it's held: its positions and normals.
fn tris_bytes(t: &Tris) -> usize {
(t.positions.len() + t.normals.len()) * 12
}
/// The mesh for an expression, built once per expression (a re-cut or a key that doesn't change the shape costs nothing).
pub fn cached(expr: &str) -> Result<std::sync::Arc<Tris>, String> {
static CACHE: OnceLock<Mutex<Held>> = OnceLock::new();
let cache = CACHE.get_or_init(Default::default);
static CACHE: OnceLock<Mutex<Generations<std::sync::Arc<Tris>>>> = OnceLock::new();
let cache = CACHE.get_or_init(|| Mutex::new(Generations::new(GEN_BYTES)));
if let Some(t) = cache.lock().unwrap().get(expr) {
return Ok(t);
}
// a buffer mesh's own triangles (buffer.rs): data already, so nothing is kept on disk for it
if let Some(b) = expr.strip_prefix("buffer:") {
let t = std::sync::Arc::new(buffer_tris(b)?.0);
cache.lock().unwrap().hold(expr, &t);
let t = std::sync::Arc::new(buffer_tris(&buffer_json(b)?)?.0);
cache.lock().unwrap().hold(expr, t.clone(), tris_bytes(&t));
return Ok(t);
}
// made by this build before, on disk (kept.rs): read back as it was written
@@ -267,7 +245,7 @@ pub fn cached(expr: &str) -> Result<std::sync::Arc<Tris>, String> {
t
}
};
cache.lock().unwrap().hold(expr, &t);
cache.lock().unwrap().hold(expr, t.clone(), tris_bytes(&t));
Ok(t)
}
@@ -275,20 +253,6 @@ pub fn cached(expr: &str) -> Result<std::sync::Arc<Tris>, String> {
mod tests {
use super::*;
#[test]
fn held_shapes_go_a_generation_at_a_time_and_what_is_asked_again_stays() {
let mut h = Held::default();
// a shape of a quarter of a generation
let t = std::sync::Arc::new(Tris { positions: vec![[0.0; 3]; GEN_BYTES / 96], normals: vec![[0.0; 3]; GEN_BYTES / 96] });
h.hold("kept", &t);
for i in 0..12 {
h.hold(&format!("bar {i}"), &t);
assert!(h.get("kept").is_some(), "asked each time, it stays (after bar {i})");
}
assert!(h.get("bar 0").is_none(), "made once and never asked again, it went");
assert!(h.now.len() + h.old.len() <= 8, "two generations at most: {} + {}", h.now.len(), h.old.len());
}
#[test]
fn a_kept_mesh_reads_back_as_it_was_written() {
let dir = std::env::temp_dir().join(format!("raea-shape-kept-{}", std::process::id()));
+1 -1
View File
@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "raea solid info: a solid's parts measured (volume, area, box, centre of mass, pieces, genus), how its parts meet, an expect file's predictions checked and two mutants against them, in scene lint's found shape"
description = "raea make solid info: a solid's parts measured (volume, area, box, centre of mass, pieces, genus), how its parts meet, an expect file's predictions checked and two mutants against them, in scene lint's found shape"
[dependencies]
raea-core-shape = { path = "../shape" }
+1 -1
View File
@@ -1,4 +1,4 @@
//! `raea solid info`: a solid measured, part by part, in scene lint's shape (docs/handoff/solids.md, Next 1; the
//! `raea make solid info`: a solid measured, part by part, in scene lint's shape (docs/handoff/solids.md, Next 1; the
//! 11-06 research: numbers before renders for geometry, and a prediction checked rather than a threshold judged). It
//! takes each named part's shape expression (what a Solid knows of itself) and answers volume, area, box, centre of
//! mass, pieces, genus and triangles for each part and for the whole; how each pair of parts meets; and `found`, each
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "raea-core-tables"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "A row's per-frame tables: the column sets that change from frame to frame (a frame's look, the camera's post-processing, a light's), laid onto the row frame by frame"
[dependencies]
raea-core-program = { path = "../program" }
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
serde_json = "1"
File renamed without changes.
+26
View File
@@ -44,6 +44,32 @@ pub struct VideoFit {
pub scale: f32,
}
/// What a page shows this frame as one number, folded into `seed`: each element's place, kind, props and text, and each
/// video's file and time in it. Not an element's id (React's count, which moves when an element is added before it),
/// not an <audio>, not a video's own sound (muted, volume): frames with one key draw one picture while the files they
/// name stay the same (files are named here, not read: whoever keeps pictures by this key holds the files to it).
/// A path under `dir` (the composition's folder) is named from there, so the same piece in another folder (a render
/// farm's job) has the same keys (11-30: the farm's first try had none in common, each clip named under its job).
pub fn key(seed: u64, want: &[Want], videos: &[VideoAt], dir: &std::path::Path) -> u64 {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
seed.hash(&mut h);
let root = dir.to_string_lossy();
let root = format!("{}/", root.trim_end_matches('/'));
let here = |s: String| if root.len() > 1 { s.replace(&root, "") } else { s };
for w in want.iter().filter(|w| w.kind != "audio") {
// (a <style>'s text names its fonts' files as its props name images)
(&w.path, &w.kind, w.text.clone().map(here)).hash(&mut h);
for (k, v) in w.props.iter().filter(|(k, _)| w.kind != "video" || (*k != "muted" && *k != "volume")) {
(k, here(v.to_string())).hash(&mut h);
}
}
for v in videos {
(v.file.strip_prefix(dir).unwrap_or(&v.file), v.at.to_bits(), v.fit.map(|f| [f.at.0, f.at.1, f.to.0, f.to.1, f.scale].map(f32::to_bits))).hash(&mut h);
}
h.finish()
}
/// What the page was last told about an element.
#[derive(Clone, Debug, PartialEq)]
struct Sent {
+1 -1
View File
@@ -1,4 +1,4 @@
//! Faces lying in one plane over each other (docs/make.feature MK8, the clip check FLOOR3 ran in Blender): two
//! Faces lying in one plane over each other (docs/goal.feature MK8, the clip check FLOOR3 ran in Blender): two
//! triangles facing the same way within about a degree, their planes within 0.2 mm, overlapping by more than a
//! millimetre. The depth buffer can't order them, so the picture flickers between them as the camera moves
//! (z-fighting): between two parts (a rug's top in the floor's, two wall slabs overlapping in line) or inside one model
Loaded 100 of 1817 files, more files were not shown because too many files have changed in this diff. Show more