mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-06 05:33:38 -10:00
Compare commits
324
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4125cceb5f | ||
|
|
6a058856ed | ||
|
|
2c6d51ce66 | ||
|
|
00e1825cd6 | ||
|
|
f75335d6d1 | ||
|
|
e6d739b16b | ||
|
|
1d90ea5743 | ||
|
|
7ef9e7d638 | ||
|
|
6e8f16d849 | ||
|
|
84864ba4e7 | ||
|
|
d80966354c | ||
|
|
a9dd01b07c | ||
|
|
364b06c094 | ||
|
|
768fb4fdc6 | ||
|
|
c7c8bdf655 | ||
|
|
80b2138677 | ||
|
|
3e929cfee8 | ||
|
|
4b4ef8e57d | ||
|
|
be812fc7ba | ||
|
|
2f1e10076a | ||
|
|
1d51c09c0b | ||
|
|
02617df030 | ||
|
|
12ad441266 | ||
|
|
8e7c5a13e7 | ||
|
|
a380418ed5 | ||
|
|
6e35267060 | ||
|
|
05f82ef572 | ||
|
|
563f49a978 | ||
|
|
67277ab967 | ||
|
|
4695f03650 | ||
|
|
41fbcfc2ab | ||
|
|
bec1ab1947 | ||
|
|
c261ecdfbc | ||
|
|
712e5ba3a0 | ||
|
|
51e2d87c76 | ||
|
|
9fed1783dc | ||
|
|
23918c2c23 | ||
|
|
c5c87e2cfb | ||
|
|
743b35677c | ||
|
|
80562f9ef7 | ||
|
|
5f407a1cc2 | ||
|
|
b0437d2d08 | ||
|
|
230f817543 | ||
|
|
8dfd71eb92 | ||
|
|
2cbfa8c608 | ||
|
|
c3765a13bb | ||
|
|
5301beb62f | ||
|
|
5c2a524369 | ||
|
|
4044e442c2 | ||
|
|
d4e39d41f0 | ||
|
|
c7e5534d38 | ||
|
|
788444e127 | ||
|
|
5b72d2e4dc | ||
|
|
33d34e51b5 | ||
|
|
7cd22cecfc | ||
|
|
76e6b00e04 | ||
|
|
88cacbe7f7 | ||
|
|
4fd7210cfe | ||
|
|
06a48730d1 | ||
|
|
28d89f8ffd | ||
|
|
7b8317764a | ||
|
|
c69e28fac3 | ||
|
|
83da71b62d | ||
|
|
4d896d2b2f | ||
|
|
d4d13925fa | ||
|
|
a8d7263235 | ||
|
|
d0f09511fe | ||
|
|
1a8a7df53d | ||
|
|
ef8ea7563d | ||
|
|
6716b6b9f0 | ||
|
|
313ac8ab83 | ||
|
|
cdfb043026 | ||
|
|
35267727b8 | ||
|
|
c72717a635 | ||
|
|
0256cb9673 | ||
|
|
b9b0d76568 | ||
|
|
bda521b3ce | ||
|
|
740f3c2cf4 | ||
|
|
dea4d75c8a | ||
|
|
2563c183e7 | ||
|
|
95b2c01a24 | ||
|
|
c81b4e8c23 | ||
|
|
1430731bf3 | ||
|
|
d873402ac5 | ||
|
|
14cdac0687 | ||
|
|
036a2ddb5e | ||
|
|
e5f4743dee | ||
|
|
4aff22e31a | ||
|
|
c863adef82 | ||
|
|
8627ba7ab4 | ||
|
|
456fd1e153 | ||
|
|
3afc53d45b | ||
|
|
7d79a24f33 | ||
|
|
6af8bfa5bb | ||
|
|
4b2225163e | ||
|
|
57373a9901 | ||
|
|
9ce8f53466 | ||
|
|
28af820668 | ||
|
|
ea5640de8f | ||
|
|
3ac738884c | ||
|
|
096f87d153 | ||
|
|
845f7438d5 | ||
|
|
6f96c78a8b | ||
|
|
e70d9c79c1 | ||
|
|
f4db12c1d0 | ||
|
|
cd159fe0be | ||
|
|
316b612d70 | ||
|
|
aa40a2fa86 | ||
|
|
48705982b6 | ||
|
|
7580433cd2 | ||
|
|
28f3fd814b | ||
|
|
1905dc723c | ||
|
|
c41dd64516 | ||
|
|
1fc3a07655 | ||
|
|
986bd33463 | ||
|
|
c41ec580a9 | ||
|
|
7e25dcc56e | ||
|
|
561e7a569c | ||
|
|
0649788f7f | ||
|
|
1a77da4980 | ||
|
|
1a913e6b06 | ||
|
|
7db0e7e149 | ||
|
|
ab63120653 | ||
|
|
8938819947 | ||
|
|
79cda1dc8c | ||
|
|
f0a266718e | ||
|
|
c8af179033 | ||
|
|
a0f6a95fe7 | ||
|
|
afaeaa0a7a | ||
|
|
65f2a6ae1e | ||
|
|
00deff035c | ||
|
|
7611a96e34 | ||
|
|
6fb27ef9e8 | ||
|
|
0c0de9b3d6 | ||
|
|
84f6c59dd0 | ||
|
|
96adb3ecfb | ||
|
|
4e12541984 | ||
|
|
4cc8f58e0a | ||
|
|
1873676251 | ||
|
|
374426411e | ||
|
|
e435bff43e | ||
|
|
4b2b39edd3 | ||
|
|
063ae93f30 | ||
|
|
2a63d75e1b | ||
|
|
2a005e0e30 | ||
|
|
04098af5af | ||
|
|
22834de9b1 | ||
|
|
300e094b9d | ||
|
|
7e214fedbb | ||
|
|
280437c111 | ||
|
|
11f28ffc52 | ||
|
|
107b591555 | ||
|
|
b7cc2694aa | ||
|
|
2bd30c5fad | ||
|
|
d169848689 | ||
|
|
0d92089f7d | ||
|
|
5885f86ff3 | ||
|
|
e02151cf49 | ||
|
|
49c2c96a1a | ||
|
|
346cacd71a | ||
|
|
ad766214e0 | ||
|
|
745c5f98c8 | ||
|
|
d36b0604bc | ||
|
|
03c2e2ee15 | ||
|
|
21859a5a31 | ||
|
|
f02348c397 | ||
|
|
64d97bac8f | ||
|
|
b9d1beaa2f | ||
|
|
b1a8d57616 | ||
|
|
9adc87dcd9 | ||
|
|
3a1cff770b | ||
|
|
09d87cfa1c | ||
|
|
afa6702c05 | ||
|
|
38f49d623f | ||
|
|
7ded6a7612 | ||
|
|
6416e4ec1b | ||
|
|
2556f42366 | ||
|
|
f2351359c8 | ||
|
|
7595c81782 | ||
|
|
1926af81a5 | ||
|
|
5d5da4f3d8 | ||
|
|
760d8e53c1 | ||
|
|
40757526f8 | ||
|
|
50a7e94f5e | ||
|
|
6735bd940f | ||
|
|
505103dacb | ||
|
|
8cbf438488 | ||
|
|
4447ff2425 | ||
|
|
53f9cba215 | ||
|
|
86f9aa310f | ||
|
|
388285cc7d | ||
|
|
5c6f2fd63b | ||
|
|
7e09ad474a | ||
|
|
420e753583 | ||
|
|
9471ceb76b | ||
|
|
2ff6676cb1 | ||
|
|
a1c8492e8f | ||
|
|
6b12b58ca5 | ||
|
|
fb19fa48a6 | ||
|
|
f321704e77 | ||
|
|
efac2ad5e0 | ||
|
|
3081ab72c6 | ||
|
|
13cc0d7eb5 | ||
|
|
fb37428ddf | ||
|
|
3b24037ceb | ||
|
|
13092a5cfc | ||
|
|
b491a27771 | ||
|
|
38bd094357 | ||
|
|
8c868f23c5 | ||
|
|
8f4f3648c8 | ||
|
|
fdf58ffa16 | ||
|
|
1f17872816 | ||
|
|
ea96626433 | ||
|
|
f95b9072e7 | ||
|
|
28cc2eb72b | ||
|
|
8152c9cfb7 | ||
|
|
cefb0e36a8 | ||
|
|
d55a74c472 | ||
|
|
2c3bcfa0eb | ||
|
|
ba65d342a5 | ||
|
|
d0d283ecaf | ||
|
|
487e62c97b | ||
|
|
a22b940a97 | ||
|
|
12f8521003 | ||
|
|
95d8236e71 | ||
|
|
675aa18daf | ||
|
|
b034e31a61 | ||
|
|
c0417d91ab | ||
|
|
c0d94f8f0c | ||
|
|
8345d76223 | ||
|
|
e9a7b9fd16 | ||
|
|
477b14a0ae | ||
|
|
407dbc5bec | ||
|
|
c1eaaa37f1 | ||
|
|
538bc30f37 | ||
|
|
5d411345ef | ||
|
|
16abfb08b7 | ||
|
|
27b70f7366 | ||
|
|
8b774295e1 | ||
|
|
04cd051788 | ||
|
|
ce46f5151f | ||
|
|
1386761981 | ||
|
|
898a7f8b0e | ||
|
|
6f6362040b | ||
|
|
66eb15448f | ||
|
|
153fbc6267 | ||
|
|
0575660417 | ||
|
|
0b8ec429cb | ||
|
|
0bdc8714a6 | ||
|
|
ac009cb5c5 | ||
|
|
0cd00209bf | ||
|
|
356dacd53f | ||
|
|
3532c93e4c | ||
|
|
5f252f9c13 | ||
|
|
7fe204fe0e | ||
|
|
b8a78ece86 | ||
|
|
0be19d9c5e | ||
|
|
ee9400fcfd | ||
|
|
0a73d6f72f | ||
|
|
fa705757ed | ||
|
|
e3d681b645 | ||
|
|
0735b03adc | ||
|
|
fc8b2198a1 | ||
|
|
9f5b00f0b5 | ||
|
|
16687e6d8b | ||
|
|
ec0e9f0c37 | ||
|
|
735b11054e | ||
|
|
2da197a2f7 | ||
|
|
9b3ad124f8 | ||
|
|
02cd40eb5f | ||
|
|
15bd90ff62 | ||
|
|
2b36c21264 | ||
|
|
20f07dd93f | ||
|
|
05decaa4c9 | ||
|
|
7450537a46 | ||
|
|
02a1050580 | ||
|
|
ab5f4cd138 | ||
|
|
cf369a45aa | ||
|
|
66a190ff46 | ||
|
|
0deac6fe0a | ||
|
|
cedf2607c6 | ||
|
|
bfd69cc2eb | ||
|
|
0af5da5879 | ||
|
|
cb8b06ff7b | ||
|
|
b250367b6c | ||
|
|
813bc24097 | ||
|
|
2127b369d3 | ||
|
|
5650d65c65 | ||
|
|
974148442e | ||
|
|
89fd926258 | ||
|
|
dd9be82976 | ||
|
|
784e156895 | ||
|
|
2161fa0ba0 | ||
|
|
e745f91ae4 | ||
|
|
a0f685b043 | ||
|
|
5c4ddb6989 | ||
|
|
17518a3ac1 | ||
|
|
a4898b764f | ||
|
|
6d6e81d7f4 | ||
|
|
6cd3a2f29f | ||
|
|
a616f42b7c | ||
|
|
2aabccbda3 | ||
|
|
873179a540 | ||
|
|
69c631b662 | ||
|
|
a572288148 | ||
|
|
5879f67686 | ||
|
|
fcbdd55282 | ||
|
|
23220fa002 | ||
|
|
aa9dc07369 | ||
|
|
db596714ab | ||
|
|
16c9932b2a | ||
|
|
b8eee1249d | ||
|
|
212186d907 | ||
|
|
caabca1d90 | ||
|
|
0fec51f6d9 | ||
|
|
f6af08fd69 | ||
|
|
dcb0cf8f49 | ||
|
|
f0372580bb | ||
|
|
79e8ac7af9 | ||
|
|
22dffb4170 | ||
|
|
b6dd19a649 | ||
|
|
0d853cff8e | ||
|
|
cab9f4bb28 | ||
|
|
7e2df514de |
No files matched your search
@@ -8,7 +8,7 @@
|
||||
{
|
||||
"name": "raea",
|
||||
"source": { "source": "git-subdir", "url": "https://github.com/shinyobjectz/raea-skills.git", "path": "skills" },
|
||||
"description": "Make video, motion graphics, games and 3D scenes with raea, the Render Anything Engine: the raea skill, and hooks that run raea's quick check on a composition after it's saved and show media in the raea app instead of the Mac's viewer."
|
||||
"description": "Make video, motion graphics, games and 3D scenes with raea, the Render Anything Engine: the raea skill, and hooks that show media in the raea app instead of the Mac's viewer and run raea check on the brief's goals as a turn ends (nothing is checked after a save: a render checks its own output)."
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
name: Bug report
|
||||
description: Something raea did wrong, with a way to see it happen.
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
For a security problem, use the Security tab, not a public issue. Leave out keys and anything private.
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: Version
|
||||
description: What `raea --version` prints, or the app's version from its About screen.
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: where
|
||||
attributes:
|
||||
label: Where
|
||||
options:
|
||||
- raea CLI (render, play, check, media, ...)
|
||||
- SDK (TypeScript, React)
|
||||
- raea app (desktop)
|
||||
- Install or update
|
||||
- Not sure
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: machine
|
||||
attributes:
|
||||
label: Machine
|
||||
description: OS and version, CPU, and for a picture problem the GPU.
|
||||
placeholder: macOS 27.2, Apple Silicon
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: ran
|
||||
attributes:
|
||||
label: What you ran
|
||||
description: The command, and the smallest composition that shows it (paste the TSX).
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: happened
|
||||
attributes:
|
||||
label: What happened
|
||||
description: The output as printed. For a picture or sound problem, the frame or time and a screenshot.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
label: What you expected
|
||||
validations:
|
||||
required: true
|
||||
@@ -0,0 +1,8 @@
|
||||
blank_issues_enabled: true
|
||||
contact_links:
|
||||
- name: Security problem
|
||||
url: https://github.com/shinyobjectz/raea/security/advisories/new
|
||||
about: Report it privately, not in an issue.
|
||||
- name: Documentation
|
||||
url: https://raea.io/docs
|
||||
about: The CLI and SDK reference and the guides.
|
||||
@@ -0,0 +1,23 @@
|
||||
name: Feature request
|
||||
description: Something you want to make that raea can't do yet, or makes hard.
|
||||
body:
|
||||
- type: textarea
|
||||
id: making
|
||||
attributes:
|
||||
label: What you're trying to make
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: today
|
||||
attributes:
|
||||
label: What you do today
|
||||
description: The command, SDK part or app screen you use now, and where it falls short.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: want
|
||||
attributes:
|
||||
label: What you'd like
|
||||
description: An example of how you'd use it helps most.
|
||||
validations:
|
||||
required: true
|
||||
@@ -0,0 +1,11 @@
|
||||
## What changes
|
||||
|
||||
<!-- What triggered it, what raea did before, and what it does now. Link the issue. -->
|
||||
|
||||
## How it was checked
|
||||
|
||||
<!-- The commands you ran and what they printed. For a picture or sound change: the composition, the frame, your OS and GPU. -->
|
||||
|
||||
## What wasn't checked
|
||||
|
||||
<!-- Platforms or paths you couldn't try, and anything a reviewer should look at closely. -->
|
||||
+44
-11
@@ -1,7 +1,8 @@
|
||||
# raea's public CI (docs/public-first.feature PF5), on GitHub's hosted runners only: it runs code from pull requests,
|
||||
# so it never touches a self-hosted machine. What needs this Mac's GPU, VideoToolbox or audio (P26, UI parity, the
|
||||
# sound gates) stays the maintainers' L1/L2 (docs/agents.md); this is the part anyone can read and rerun.
|
||||
# every pull request and push to main guard (names and secrets), L0's repo-wide gates, cargo check of the engine
|
||||
# every pull request and push to main guard (names and secrets), L0's repo-wide gates, sdk/cloud's local tests,
|
||||
# cargo check of the engine, the tests of every crate that needs no GPU
|
||||
name: ci
|
||||
|
||||
on:
|
||||
@@ -68,6 +69,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
|
||||
@@ -90,6 +94,24 @@ jobs:
|
||||
- name: taxonomy
|
||||
run: bash tools/taxonomy.sh --check
|
||||
|
||||
cloud:
|
||||
# sdk/cloud's tests that need no container or farm (its npm test): the box server's pure parts and memory guard,
|
||||
# what a render sends the farm, and the farm's planner (its encode on ffmpeg), media and volume gate
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
lfs: false
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
- name: ffmpeg
|
||||
run: sudo apt-get update && sudo apt-get install -y ffmpeg
|
||||
- name: sdk/cloud tests
|
||||
working-directory: sdk/cloud
|
||||
run: npm ci --no-fund --no-audit --loglevel=error && npm test
|
||||
|
||||
engine:
|
||||
# a fresh clone builds as the README says (public #14): the toolchain from rust-toolchain.toml, --locked
|
||||
strategy:
|
||||
@@ -104,30 +126,41 @@ jobs:
|
||||
lfs: false
|
||||
- name: Linux libraries
|
||||
if: runner.os == 'Linux'
|
||||
run: sudo apt-get update && sudo apt-get install -y cmake ninja-build libasound2-dev libfontconfig1-dev libvulkan-dev libudev-dev nasm
|
||||
run: sudo apt-get update && sudo apt-get install -y cmake ninja-build libasound2-dev libfontconfig1-dev libvulkan-dev libudev-dev nasm ffmpeg
|
||||
- name: macOS tools
|
||||
if: runner.os == 'macOS'
|
||||
run: brew install cmake ninja nasm
|
||||
run: brew install cmake ninja nasm ffmpeg
|
||||
- uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.4.2
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- name: cargo check
|
||||
run: cargo check --locked -p raea-cli --tests
|
||||
- name: unit tests (the crates with no GPU or media device)
|
||||
- name: unit tests (every crate with no GPU)
|
||||
# debug info off: with it the test binaries of the app crates filled 27 GB of a runner's disk (#90)
|
||||
env:
|
||||
CARGO_PROFILE_TEST_DEBUG: "0"
|
||||
run: cargo test --locked -p raea-runtime-plugins -p raea-io-media -p raea-core-fonts -p raea-native -p raea-core-brief -p raea-core-k -p raea-bundle -p raea-app-check -p raea-app-check-flash -p raea-io-ffmpeg -p raea-app-workspace -p raea-app-tools -p raea-app-targets
|
||||
# The crates come from the lock file, so a new crate's tests run without anyone naming it: every workspace crate
|
||||
# that links neither wgpu nor Rolldown, then the few that link wgpu and whose tests need no GPU. All of wgpu's
|
||||
# side can't join: its test binaries would fill the runner's disk (#90). Left out, with the reason:
|
||||
# raea-sys-mlx its tests run on MLX's GPU device, and a hosted macOS runner has no Metal device
|
||||
# raea-bundle in a call of its own: Rolldown's crates turn on serde_json's arbitrary_precision, features unify
|
||||
# across one cargo call, and with it on an untagged enum can't read a number (raea-core-brief's make dials failed
|
||||
# here from 11-23 while passing alone). raea itself never links Rolldown: it loads it as a library at run time.
|
||||
# --no-fail-fast: one run names every crate whose tests fail, not only the first
|
||||
run: |
|
||||
ws=$(cargo metadata --locked --no-deps --format-version 1 | jq -r '.packages[].name' | sort)
|
||||
linked=$(for k in wgpu rolldown; do cargo tree --locked --workspace -i "$k" -e normal,build,dev --prefix none --format '{p}'; done | grep -F "($PWD/" | sed 's/ v[0-9].*//' | sort -u)
|
||||
light=$(comm -23 <(echo "$ws") <(echo "$linked") | grep -vx raea-sys-mlx | sed 's/^/-p /')
|
||||
cargo test --locked --no-fail-fast $light -p raea-runtime-plugins -p raea-runtime-live -p raea-app-check -p raea-app-workspace -p raea-app-tools -p raea-app-targets
|
||||
cargo test --locked -p raea-bundle
|
||||
- name: Windows' and Linux's own (#169)
|
||||
# what a Windows or Linux user meets that no other step ran: QuickJS's Intl (raea-runtime-jsengine's
|
||||
# quickjs_formats_as_javascriptcore_does, on Linux), openh264 at --quality master (raea-io-soft), git found or
|
||||
# fetched (raea-io-assets), and raea's Node core under the agent shell (raea-native's tests/node.rs: Node's names
|
||||
# for the system, Windows' paths); tests/node.rs needs raea-native's modules feature and tests/quality.rs
|
||||
# raea-io-soft's h264
|
||||
# what a Windows or Linux user meets that needs a feature the step above doesn't turn on: openh264 at --quality
|
||||
# master (raea-io-soft's tests/quality.rs, its h264 feature) and raea's Node core under the agent shell
|
||||
# (raea-native's tests/node.rs, its modules feature: Node's names for the system, Windows' paths). QuickJS's
|
||||
# Intl (raea-runtime-jsengine, on Linux) and git found or fetched (raea-io-assets) run in the step above
|
||||
env:
|
||||
CARGO_PROFILE_TEST_DEBUG: "0"
|
||||
run: |
|
||||
cargo test --locked -p raea-native --features modules --test node
|
||||
cargo test --locked -p raea-io-soft --features h264
|
||||
cargo test --locked -p raea-runtime-jsengine -p raea-io-assets
|
||||
@@ -2,6 +2,7 @@
|
||||
# Apple Silicon, Linux on x86_64 and Windows on x86_64 are built from the tag on GitHub's runners, packed by
|
||||
# tools/release.sh, checked by tools/release-check.sh, attested (anyone can check a download with
|
||||
# `gh attestation verify raea-VERSION-macos-arm64.tar.gz -R shinyobjectz/raea`) and attached to the tag's release.
|
||||
# Linux also packages and checks an AppImage from the same verified archive (tools/release-appimage.sh).
|
||||
# The skills gate reads the feed app, which is private, so it runs in a maintainer's checkout first
|
||||
# (tools/skills.sh check), and the tag names the commit it passed on; tools/release.sh checks the gate's inputs haven't
|
||||
# changed since (tools/release/skills-passed.sh):
|
||||
@@ -181,6 +182,11 @@ jobs:
|
||||
v=${TAG#v}
|
||||
if [ "$RUNNER_OS" = Linux ]; then xvfb-run -a -s "-screen 0 1280x1024x24" bash tools/release.sh "$v" ship HEAD
|
||||
else bash tools/release.sh "$v" ship HEAD; fi
|
||||
- name: Package and check the Linux AppImage
|
||||
if: runner.os == 'Linux'
|
||||
env:
|
||||
RAEA_CHECK_DIR: ${{ runner.temp }}/appimage-check
|
||||
run: xvfb-run -a -s "-screen 0 1280x1024x24" bash tools/release-appimage.sh "${TAG#v}" "dist/raea-${TAG#v}-linux-x86_64.tar.gz"
|
||||
# a failed check's own files (the app check's frames, every step's log), not the unpacked release
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: failure()
|
||||
@@ -189,6 +195,8 @@ jobs:
|
||||
path: |
|
||||
${{ runner.temp }}/release-check/app
|
||||
${{ runner.temp }}/release-check/**/*.log
|
||||
${{ runner.temp }}/appimage-check/app
|
||||
${{ runner.temp }}/appimage-check/**/*.log
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
# the stripped binaries' symbols (#88), for symbolicating a crash report from this release; never published
|
||||
@@ -202,6 +210,10 @@ jobs:
|
||||
if: ${{ !inputs.dry_run }}
|
||||
with:
|
||||
subject-path: dist/raea-*.tar.gz
|
||||
- uses: actions/attest-build-provenance@v2
|
||||
if: ${{ runner.os == 'Linux' && !inputs.dry_run }}
|
||||
with:
|
||||
subject-path: dist/raea-*.AppImage
|
||||
- name: Attach to the release
|
||||
if: ${{ !inputs.dry_run }}
|
||||
env:
|
||||
@@ -209,11 +221,16 @@ jobs:
|
||||
run: |
|
||||
gh release view "$TAG" >/dev/null 2>&1 || gh release create "$TAG" ${{ contains(env.TAG, '-') && '--prerelease' || '' }} --title "raea ${TAG#v}" --notes "Built by .github/workflows/release.yml; notes follow."
|
||||
gh release upload "$TAG" dist/raea-*.tar.gz dist/raea-*.tar.gz.sha256 --clobber
|
||||
if [ "$RUNNER_OS" = Linux ]; then
|
||||
gh release upload "$TAG" dist/raea-*.AppImage dist/raea-*.AppImage.sha256 --clobber
|
||||
fi
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: ${{ inputs.dry_run }}
|
||||
with:
|
||||
name: dry-run-${{ runner.os }}
|
||||
path: dist/raea-*.tar.gz*
|
||||
path: |
|
||||
dist/raea-*.tar.gz*
|
||||
dist/raea-*.AppImage*
|
||||
retention-days: 3
|
||||
compression-level: 0
|
||||
|
||||
@@ -223,6 +240,9 @@ jobs:
|
||||
# (tools/release/win-bundle.sh), as Microsoft documents for app-local deployment.
|
||||
windows:
|
||||
runs-on: ${{ (vars.RELEASE_WINDOWS_RUNNER && fromJSON(vars.RELEASE_WINDOWS_RUNNER)) || 'windows-latest' }}
|
||||
# the signing identity's federated credential trusts this repository's environment "signing" and nothing else
|
||||
# (Azure app raea-release-signing); with no identity set there is no environment, and the zip is unsigned
|
||||
environment: ${{ vars.AZURE_SIGN_CLIENT_ID != '' && 'signing' || '' }}
|
||||
timeout-minutes: 350
|
||||
env:
|
||||
# the compile cache, as build's
|
||||
@@ -352,9 +372,24 @@ jobs:
|
||||
run: bash tools/release/lavapipe.sh
|
||||
- name: Where the skills gate passed
|
||||
run: bash tools/release/skills-passed.sh "$TAG" "${{ inputs.skills_passed }}"
|
||||
# raea's own Windows programs signed (#221), once the repository has the signing identity: the variables
|
||||
# AZURE_SIGN_CLIENT_ID, AZURE_SIGN_TENANT_ID and AZURE_SIGN_SUBSCRIPTION_ID name an Azure app whose federated
|
||||
# credential trusts this workflow and which holds the Artifact Signing Certificate Profile Signer role on the
|
||||
# account (no secret is stored: the job's own token is exchanged). Without them the zip is unsigned, as before
|
||||
- name: Sign in to Azure for signing
|
||||
if: ${{ vars.AZURE_SIGN_CLIENT_ID != '' }}
|
||||
uses: azure/login@v2
|
||||
with:
|
||||
client-id: ${{ vars.AZURE_SIGN_CLIENT_ID }}
|
||||
tenant-id: ${{ vars.AZURE_SIGN_TENANT_ID }}
|
||||
subscription-id: ${{ vars.AZURE_SIGN_SUBSCRIPTION_ID }}
|
||||
- name: jsign (signs raea's programs)
|
||||
if: ${{ vars.AZURE_SIGN_CLIENT_ID != '' }}
|
||||
run: choco install jsign -y --no-progress
|
||||
- name: Pack and check (tools/release.sh)
|
||||
env:
|
||||
RAEA_CHECK_DIR: ${{ runner.temp }}/release-check
|
||||
RAEA_WIN_SIGN: ${{ vars.AZURE_SIGN_CLIENT_ID != '' && '1' || '' }}
|
||||
run: bash tools/release.sh "${TAG#v}" target/dist HEAD
|
||||
# live play on Windows (PT20 left it unproven): bevy-ts's play cases, `play --offscreen` with an input script and
|
||||
# a snapshot's pixels probed, run by the raea just built; check.sh reads the pixels with ImageMagick, which the
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
# raea built natively for Windows on ARM (#82: a Snapdragon X runs the x64 build under emulation, and asked for its
|
||||
# own). GitHub's windows-11-arm runner builds what release.yml's windows job builds, for aarch64-pc-windows-msvc, runs
|
||||
# `raea --version`, packs and checks raea-VERSION-windows-arm64.zip with tools/release.sh (RAEA_WIN_ARCH=arm64)
|
||||
# without drawing (RAEA_CHECK_NO_GPU=1: WARP segfaults in Bevy's compute shaders here as on x64, and Mesa's lavapipe has
|
||||
# no ARM64 build; a Snapdragon PC is what draws, #82), and on a v* tag attaches it to that
|
||||
# release. It runs beside release.yml, not in it, so a release never waits on or fails with the ARM64 build; a
|
||||
# promoted release (release-go.sh) builds it again from the tag. install.ps1 takes it on an ARM64 PC when it's there.
|
||||
name: windows-arm
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
ref:
|
||||
description: "commit, branch or tag to build"
|
||||
required: false
|
||||
version:
|
||||
description: "the version the zip is named for (raea-VERSION-windows-arm64.zip)"
|
||||
required: false
|
||||
push:
|
||||
branches: [windows-arm64]
|
||||
tags: ["v*"]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: windows-11-arm
|
||||
timeout-minutes: 350
|
||||
env:
|
||||
# the release builds' compile cache (tools/release/compile-cache.sh), under this OS and architecture's own prefix
|
||||
RELEASE_CACHE_ENDPOINT: ${{ secrets.RELEASE_CACHE_ENDPOINT }}
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.RELEASE_CACHE_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.RELEASE_CACHE_SECRET }}
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ inputs.ref || github.sha }}
|
||||
submodules: true
|
||||
lfs: false
|
||||
- name: Toolchain (rust-toolchain.toml's pin)
|
||||
run: |
|
||||
if ! command -v rustup >/dev/null; then
|
||||
curl -fsSL --retry 3 -o "$RUNNER_TEMP/rustup-init.exe" https://static.rust-lang.org/rustup/dist/aarch64-pc-windows-msvc/rustup-init.exe
|
||||
"$RUNNER_TEMP/rustup-init.exe" -y --default-toolchain none --profile minimal
|
||||
echo "$USERPROFILE/.cargo/bin" >> "$GITHUB_PATH"
|
||||
export PATH="$USERPROFILE/.cargo/bin:$PATH"
|
||||
fi
|
||||
rustup show active-toolchain || rustup toolchain install
|
||||
rustc -vV
|
||||
# ring builds its aarch64 assembly with clang (and only clang) on Windows
|
||||
- name: clang (ring's assembly)
|
||||
run: |
|
||||
if ! command -v clang >/dev/null; then
|
||||
for d in "/c/Program Files/LLVM/bin" "/c/Program Files/Microsoft Visual Studio"/*/*/VC/Tools/Llvm/ARM64/bin; do
|
||||
[ -x "$d/clang.exe" ] && { echo "$d" >> "$GITHUB_PATH"; export PATH="$d:$PATH"; break; }
|
||||
done
|
||||
fi
|
||||
command -v clang >/dev/null || { winget install -e --id LLVM.LLVM --accept-source-agreements --accept-package-agreements --silent; echo "/c/Program Files/LLVM/bin" >> "$GITHUB_PATH"; export PATH="/c/Program Files/LLVM/bin:$PATH"; }
|
||||
clang --version
|
||||
- name: jq that writes LF
|
||||
run: |
|
||||
mkdir -p "$RUNNER_TEMP/jq"
|
||||
printf '#!/bin/bash\nexec "%s" -b "$@"\n' "$(command -v jq)" > "$RUNNER_TEMP/jq/jq"
|
||||
chmod +x "$RUNNER_TEMP/jq/jq"
|
||||
echo "$RUNNER_TEMP/jq" >> "$GITHUB_PATH"
|
||||
- uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.4.2
|
||||
- name: The runtime's packages
|
||||
run: for d in sdk/react/js sdk/react/tw; do (cd "$d" && bun install --frozen-lockfile); done
|
||||
# (an sccache the action can't fetch for ARM64 Windows leaves the build uncached, as compile-cache.sh does)
|
||||
- name: Compile cache (sccache, as release.yml's)
|
||||
if: env.AWS_ACCESS_KEY_ID != ''
|
||||
continue-on-error: true
|
||||
uses: mozilla-actions/[email protected]
|
||||
- name: Use the compile cache
|
||||
if: env.AWS_ACCESS_KEY_ID != ''
|
||||
run: bash tools/release/compile-cache.sh
|
||||
- name: Build
|
||||
run: |
|
||||
feat=$(bash tools/bevy-plugins.sh features sdk/raea/bench/bevy-plugins)
|
||||
t() { s=$SECONDS; "$@"; echo "::notice::Windows ARM64 $(( (SECONDS - s) / 60 )) min: ${*:7}"; }
|
||||
t cargo build --profile dist --locked -p raea-cli --bin raea --no-default-features --features "$feat"
|
||||
t cargo build --profile dist --locked -p raea-rune-host
|
||||
t cargo build --profile dist --locked -p raea-page-host --features window
|
||||
t cargo build --profile dist --locked -p raea-perceive
|
||||
- name: What raea.exe is and imports
|
||||
run: |
|
||||
file target/dist/raea.exe || true
|
||||
dumpbin=$(ls "/c/Program Files/Microsoft Visual Studio"/*/*/VC/Tools/MSVC/*/bin/Hostarm64/arm64/dumpbin.exe 2>/dev/null | head -1)
|
||||
[ -n "$dumpbin" ] && "$dumpbin" -nologo -headers -dependents target/dist/raea.exe | grep -iE 'machine|\.dll$' | sed 's/^ *//' | tee -a "$GITHUB_STEP_SUMMARY" || true
|
||||
target/dist/raea.exe --version | tee -a "$GITHUB_STEP_SUMMARY"
|
||||
- name: Models (pinned by URL and sha256 in tools/release/models.tsv)
|
||||
run: |
|
||||
while IFS=$'\t' read -r path url sha; do
|
||||
case $path in ''|'#'*) continue ;; esac
|
||||
mkdir -p "$HOME/.local/share/raea-models/$(dirname "$path")"
|
||||
curl -fsSL "$url" -o "$HOME/.local/share/raea-models/$path"
|
||||
echo "$sha $HOME/.local/share/raea-models/$path" | sha256sum -c -
|
||||
done < <(tr -d '\r' < tools/release/models.tsv)
|
||||
# bin\ as release.yml's windows job fills it, with the ARM64 runtime, uv and DXC (RAEA_WIN_ARCH=arm64), then the
|
||||
# zip packed and checked by tools/release.sh as raea-VERSION-windows-arm64.zip. The skills gate is this commit's
|
||||
# (public raea has no feed app; cli.md is still checked against this build's help); nothing is drawn
|
||||
- name: Pack and check (tools/release.sh)
|
||||
env:
|
||||
RAEA_WIN_ARCH: arm64
|
||||
RAEA_CHECK_DIR: ${{ runner.temp }}/release-check
|
||||
RAEA_CHECK_NO_GPU: "1"
|
||||
run: |
|
||||
bash tools/release/onnxruntime.sh target/dist
|
||||
bash tools/release/win-bundle.sh target/dist
|
||||
v="${{ inputs.version }}"
|
||||
case $GITHUB_REF in
|
||||
refs/tags/v*)
|
||||
v=${v:-${GITHUB_REF_NAME#v}}
|
||||
# where the skills gate passed, as release.yml reads it (the tag's skills-passed line)
|
||||
eval "$(GITHUB_ENV= bash tools/release/skills-passed.sh "$GITHUB_REF_NAME" | grep '^RAEA_SKILLS_PASSED=')" ;;
|
||||
*) RAEA_SKILLS_PASSED=$(git rev-parse HEAD) ;;
|
||||
esac
|
||||
export RAEA_SKILLS_PASSED
|
||||
bash tools/release.sh "${v:-0.0.0-arm64}" target/dist HEAD
|
||||
# on a v* tag, beside release.yml's archives (the release made here if release.yml hasn't yet)
|
||||
- name: Attach to the release
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
pre=; case $GITHUB_REF_NAME in *-*) pre=--prerelease ;; esac
|
||||
gh release view "$GITHUB_REF_NAME" -R "$GITHUB_REPOSITORY" >/dev/null 2>&1 ||
|
||||
gh release create "$GITHUB_REF_NAME" -R "$GITHUB_REPOSITORY" $pre --title "raea ${GITHUB_REF_NAME#v}" --notes "Built by .github/workflows/release.yml; notes follow." ||
|
||||
gh release view "$GITHUB_REF_NAME" -R "$GITHUB_REPOSITORY" >/dev/null
|
||||
gh release upload "$GITHUB_REF_NAME" -R "$GITHUB_REPOSITORY" dist/raea-*-windows-arm64.zip dist/raea-*-windows-arm64.zip.sha256 --clobber
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: windows-arm64-zip
|
||||
path: dist/raea-*-windows-arm64.zip*
|
||||
retention-days: 7
|
||||
compression-level: 0
|
||||
if-no-files-found: ignore
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: windows-arm64-bins
|
||||
path: |
|
||||
target/dist/raea.exe
|
||||
target/dist/raea_bundle.dll
|
||||
target/dist/raea-rune-host.exe
|
||||
target/dist/raea-page-host.exe
|
||||
target/dist/raea-perceive.exe
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
|
||||
# vendor/metis-sys's header change reaches release.yml's x64 build too (windows-latest's Visual Studio): metis-sys
|
||||
# alone, in a scratch crate, compiled there
|
||||
metis-x64:
|
||||
runs-on: windows-latest
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ inputs.ref || github.sha }}
|
||||
sparse-checkout: vendor/metis-sys
|
||||
- name: metis-sys on x64 MSVC
|
||||
run: |
|
||||
c="$RUNNER_TEMP/metis-x64"; mkdir -p "$c/src" && : > "$c/src/lib.rs"
|
||||
printf '[package]\nname = "metis-x64"\nversion = "0.0.0"\nedition = "2021"\n[dependencies]\nmetis-sys = { path = "%s" }\n[workspace]\n' "$(cygpath -m "$GITHUB_WORKSPACE/vendor/metis-sys")" > "$c/Cargo.toml"
|
||||
cl 2>&1 | head -1 || true
|
||||
cd "$c" && cargo build
|
||||
@@ -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
|
||||
@@ -0,0 +1,55 @@
|
||||
# Code of conduct
|
||||
|
||||
raea's issues, pull requests, reviews and other project-managed community spaces
|
||||
should let people discuss and improve the work without harassment. This applies
|
||||
to maintainers, contributors and people using automated or AI-assisted tools.
|
||||
Participants remain responsible for the material they submit through those tools.
|
||||
|
||||
## Expected behavior
|
||||
|
||||
- Discuss the code, evidence and ideas respectfully. Technical disagreement is
|
||||
welcome; personal attacks and assumptions about another person's motives are not.
|
||||
- Give actionable feedback, accept corrections and respect requests to stop a
|
||||
conversation or move it out of a thread.
|
||||
- Make room for different experience levels, backgrounds and communication styles.
|
||||
- Respect privacy. Share only logs, screenshots and other information you have
|
||||
permission to publish, with credentials and personal information removed.
|
||||
|
||||
Harassment, discriminatory insults, threats, sexual harassment, unwanted repeated
|
||||
contact, disclosure of private information, deliberate disruption and retaliation
|
||||
against someone raising a concern are unacceptable.
|
||||
|
||||
## Reporting a concern
|
||||
|
||||
For content on GitHub, use the content menu's **Report content** action where it
|
||||
is available. Choose **Report to repository admins** if GitHub offers it.
|
||||
Maintainer reporting depends on repository settings and the reporter's access.
|
||||
For abuse covered by GitHub's rules, use **Report abuse to GitHub Support** or
|
||||
[GitHub's abuse-reporting route](https://docs.github.com/en/communities/maintaining-your-safety-on-github/reporting-abuse-or-spam).
|
||||
GitHub handles those reports under its own policies; it is not the project's
|
||||
appeal body for every technical or moderation disagreement.
|
||||
|
||||
A separate private maintainer inbox for conduct reports has not been designated
|
||||
in this repository. If GitHub's maintainer-reporting option is unavailable, ask
|
||||
for a private contact without posting the incident, personal information or
|
||||
accusations in a public issue. Maintainers can document an additional contact
|
||||
after confirming who will handle it. Use [the security policy](SECURITY.md) for vulnerabilities,
|
||||
not as a general conduct-report channel.
|
||||
|
||||
Include links, the relevant context and your preferred way to be contacted when
|
||||
reporting privately. Do not retaliate, publicly investigate the reporter or
|
||||
pressure someone to disclose an incident.
|
||||
|
||||
## Moderation
|
||||
|
||||
Repository maintainers may clarify expectations, ask participants to change
|
||||
behavior, close or remove disruptive content, restrict interactions, or block
|
||||
continued participation as appropriate to severity and repetition. A technical
|
||||
disagreement or a rejected contribution alone is not misconduct.
|
||||
|
||||
Maintainers should consider context and available evidence, protect sensitive
|
||||
information, explain decisions when doing so does not compromise privacy, and
|
||||
allow a participant to provide relevant additional context privately through the
|
||||
same reporting route. A maintainer involved in a concern should seek an uninvolved
|
||||
reviewer where one is available. This policy does not promise a response deadline
|
||||
or confidentiality beyond what the chosen reporting service and process provide.
|
||||
Generated
+385
-51
@@ -8490,6 +8490,15 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "intel_tex_2"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7980d359170e7da4bc2421aa74c49d338a3153313e006d732a3430f1af375a60"
|
||||
dependencies = [
|
||||
"ispc_rt",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "interpolate_name"
|
||||
version = "0.2.4"
|
||||
@@ -8573,6 +8582,16 @@ version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
|
||||
|
||||
[[package]]
|
||||
name = "ispc_rt"
|
||||
version = "2.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a396f76fd253fab9945bb4c6080f515d0c4036bc30219462d199b58886fd37b4"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"num_cpus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.10.5"
|
||||
@@ -10263,8 +10282,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "metis-sys"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "769ee6be814b21c52afcc631f07051f578487d642f3e89a45f2a086fd94fffa9"
|
||||
dependencies = [
|
||||
"cc",
|
||||
]
|
||||
@@ -13669,6 +13686,7 @@ dependencies = [
|
||||
"raea-app-check-cause",
|
||||
"raea-app-check-flash",
|
||||
"raea-app-check-inbox",
|
||||
"raea-app-check-make",
|
||||
"raea-app-check-read",
|
||||
"raea-app-check-text",
|
||||
"raea-core-brief",
|
||||
@@ -13701,6 +13719,16 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-check-make"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"raea-core-facts",
|
||||
"raea-io-home",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-check-read"
|
||||
version = "0.1.0"
|
||||
@@ -13792,6 +13820,7 @@ dependencies = [
|
||||
"fastrand",
|
||||
"raea-app-check",
|
||||
"raea-app-double",
|
||||
"raea-io-clef",
|
||||
"raea-io-home",
|
||||
"raea-sys-columns",
|
||||
"raea-sys-fingerprint",
|
||||
@@ -13834,19 +13863,6 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-judge"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"raea-core-ask",
|
||||
"raea-core-facts",
|
||||
"raea-io-clef",
|
||||
"raea-io-home",
|
||||
"raea-runtime-bundle",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-layers"
|
||||
version = "0.1.0"
|
||||
@@ -13860,6 +13876,32 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-lightbake"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"libc",
|
||||
"raea-io-home",
|
||||
"raea-light",
|
||||
"raea-runtime-bundle",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-make"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"image",
|
||||
"raea-core-brief",
|
||||
"raea-core-facts",
|
||||
"raea-core-review",
|
||||
"resvg 0.48.1",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-media"
|
||||
version = "0.1.0"
|
||||
@@ -13878,6 +13920,7 @@ dependencies = [
|
||||
name = "raea-app-motion"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"glam 0.33.12",
|
||||
"raea-io-home",
|
||||
"raea-runtime-bundle",
|
||||
"raea-sys-kimodo",
|
||||
@@ -13915,6 +13958,21 @@ dependencies = [
|
||||
"winit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
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",
|
||||
"serde_json",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-registry"
|
||||
version = "0.1.0"
|
||||
@@ -13930,12 +13988,18 @@ dependencies = [
|
||||
name = "raea-app-scene"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"dunce",
|
||||
"raea-core-facts",
|
||||
"raea-core-scene",
|
||||
"raea-runtime-bundle",
|
||||
"raea-runtime-export",
|
||||
"raea-runtime-lod-plan",
|
||||
"raea-sys-body",
|
||||
"raea-sys-contact",
|
||||
"raea-sys-light-meter",
|
||||
"raea-sys-motionfaults",
|
||||
"raea-sys-notice",
|
||||
"raea-sys-stage",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -13945,8 +14009,7 @@ name = "raea-app-solid"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"raea-app-ask",
|
||||
"raea-app-judge",
|
||||
"raea-app-make",
|
||||
"raea-core-facts",
|
||||
"raea-core-meshcheck",
|
||||
"raea-core-shape",
|
||||
@@ -13992,6 +14055,19 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-voice"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"cpal 0.15.3",
|
||||
"ort",
|
||||
"raea-io-trace",
|
||||
"raea-sys-ml",
|
||||
"raea-sys-speech",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-workspace"
|
||||
version = "0.1.0"
|
||||
@@ -14182,6 +14258,7 @@ name = "raea-bundle"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.22.1",
|
||||
"dunce",
|
||||
"lightningcss",
|
||||
"oxc",
|
||||
@@ -14219,7 +14296,6 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"dunce",
|
||||
"raea-app-ask",
|
||||
"raea-app-capcut",
|
||||
"raea-app-check",
|
||||
"raea-app-ci",
|
||||
@@ -14227,22 +14303,28 @@ dependencies = [
|
||||
"raea-app-engines",
|
||||
"raea-app-fingerprint",
|
||||
"raea-app-game",
|
||||
"raea-app-judge",
|
||||
"raea-app-layers",
|
||||
"raea-app-lightbake",
|
||||
"raea-app-make",
|
||||
"raea-app-media",
|
||||
"raea-app-notes",
|
||||
"raea-app-play",
|
||||
"raea-app-playable",
|
||||
"raea-app-scene",
|
||||
"raea-app-solid",
|
||||
"raea-app-sound",
|
||||
"raea-app-targets",
|
||||
"raea-app-tools",
|
||||
"raea-app-voice",
|
||||
"raea-app-workspace",
|
||||
"raea-bevy-plugins",
|
||||
"raea-cli-goal",
|
||||
"raea-cli-refused",
|
||||
"raea-core-alloc",
|
||||
"raea-core-animate",
|
||||
"raea-core-brief",
|
||||
"raea-core-program",
|
||||
"raea-denoise-bench",
|
||||
"raea-io-home",
|
||||
"raea-io-media",
|
||||
"raea-io-npm",
|
||||
@@ -14258,6 +14340,7 @@ dependencies = [
|
||||
"raea-runtime-react",
|
||||
"raea-runtime-sound",
|
||||
"raea-runtime-wear",
|
||||
"raea-sys-fixes",
|
||||
"raea-sys-index",
|
||||
"regex",
|
||||
"serde",
|
||||
@@ -14265,6 +14348,26 @@ dependencies = [
|
||||
"wsx",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-cli-goal"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-app-make",
|
||||
"raea-core-brief",
|
||||
"raea-io-home",
|
||||
"raea-native",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-cli-refused"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"raea-io-home",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-core-alloc"
|
||||
version = "0.1.0"
|
||||
@@ -14285,7 +14388,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"ts-rs",
|
||||
"sha2 0.10.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -14345,6 +14448,15 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-core-modelbox"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-scene",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-core-place"
|
||||
version = "0.1.0"
|
||||
@@ -14382,6 +14494,7 @@ version = "0.1.0"
|
||||
name = "raea-core-shape"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"manifold-rust",
|
||||
"raea-core-fonts",
|
||||
"raea-core-grow",
|
||||
@@ -14400,6 +14513,15 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-core-tables"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-core-wire"
|
||||
version = "0.1.0"
|
||||
@@ -14408,6 +14530,23 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-core-zfight"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-denoise-bench"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"raea-light",
|
||||
"raea-runtime-bundle",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-gpu-device"
|
||||
version = "0.1.0"
|
||||
@@ -14717,7 +14856,9 @@ name = "raea-light"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"raea-core-facts",
|
||||
"raea-io-home",
|
||||
"raea-io-trace",
|
||||
"raea-runtime-bundle",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -14798,6 +14939,20 @@ dependencies = [
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-page-ax"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"accesskit 0.24.1",
|
||||
"bevy",
|
||||
"blitz-dom",
|
||||
"raea-runtime-dom",
|
||||
"raea-sys-a11y",
|
||||
"raea-sys-page",
|
||||
"serde_json",
|
||||
"stylo",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-page-host"
|
||||
version = "0.1.0"
|
||||
@@ -14815,6 +14970,7 @@ dependencies = [
|
||||
"raea-io-os",
|
||||
"raea-io-trace",
|
||||
"raea-page",
|
||||
"raea-page-ax",
|
||||
"raea-page-sound",
|
||||
"raea-page-stage",
|
||||
"raea-page-window",
|
||||
@@ -14824,11 +14980,9 @@ dependencies = [
|
||||
"raea-runtime-js",
|
||||
"raea-runtime-plugins",
|
||||
"raea-runtime-view",
|
||||
"raea-sys-a11y",
|
||||
"raea-sys-fonts",
|
||||
"raea-sys-page",
|
||||
"serde_json",
|
||||
"stylo",
|
||||
"tiny_http",
|
||||
]
|
||||
|
||||
@@ -14868,11 +15022,14 @@ name = "raea-page-window"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"blitz-traits",
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"raea-io-os",
|
||||
"raea-runtime-js",
|
||||
"raea-sys-page",
|
||||
"raw-window-handle",
|
||||
"serde_json",
|
||||
"windows 0.62.2",
|
||||
@@ -14900,34 +15057,68 @@ dependencies = [
|
||||
"bytemuck",
|
||||
"dunce",
|
||||
"image",
|
||||
"raea-core-facts",
|
||||
"raea-core-program",
|
||||
"raea-core-shape",
|
||||
"raea-gpu-device",
|
||||
"raea-io-media",
|
||||
"raea-io-trace",
|
||||
"raea-render-plugins",
|
||||
"raea-render-raytrace",
|
||||
"raea-runtime-gpuframe",
|
||||
"raea-runtime-plugins",
|
||||
"raea-runtime-scene3d",
|
||||
"raea-runtime-view",
|
||||
"raea-sys-compose",
|
||||
"raea-sys-compute",
|
||||
"raea-sys-engine-shaders",
|
||||
"raea-sys-environment",
|
||||
"raea-sys-fog",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-grass",
|
||||
"raea-sys-grid",
|
||||
"raea-sys-hold",
|
||||
"raea-sys-look",
|
||||
"raea-sys-matchmove",
|
||||
"raea-sys-material",
|
||||
"raea-sys-memtally",
|
||||
"raea-sys-meshseq",
|
||||
"raea-sys-page",
|
||||
"raea-sys-post",
|
||||
"raea-sys-procmat",
|
||||
"raea-sys-screen",
|
||||
"raea-sys-shader",
|
||||
"raea-sys-splat",
|
||||
"raea-sys-sprite",
|
||||
"raea-sys-text3d",
|
||||
"raea-sys-three-shader",
|
||||
"raea-sys-toon",
|
||||
"raea-sys-viewbox",
|
||||
"serde_json",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-render-plugins"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-runtime-plugins",
|
||||
"raea-runtime-scene3d",
|
||||
"raea-sys-compose",
|
||||
"raea-sys-compute",
|
||||
"raea-sys-environment",
|
||||
"raea-sys-fog",
|
||||
"raea-sys-fog-half",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-framepass",
|
||||
"raea-sys-gi",
|
||||
"raea-sys-grass",
|
||||
"raea-sys-grid",
|
||||
"raea-sys-hold",
|
||||
"raea-sys-lod",
|
||||
"raea-sys-look",
|
||||
"raea-sys-matchmove",
|
||||
"raea-sys-material",
|
||||
"raea-sys-meshseq",
|
||||
"raea-sys-page",
|
||||
"raea-sys-parity",
|
||||
"raea-sys-phase",
|
||||
"raea-sys-post",
|
||||
@@ -14941,10 +15132,8 @@ dependencies = [
|
||||
"raea-sys-sprite",
|
||||
"raea-sys-text3d",
|
||||
"raea-sys-three-shader",
|
||||
"raea-sys-viewbox",
|
||||
"raea-sys-toon",
|
||||
"raea-sys-volume",
|
||||
"serde_json",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -14959,6 +15148,7 @@ dependencies = [
|
||||
"raea-sys-engine-shaders",
|
||||
"raea-sys-post",
|
||||
"raea-sys-rt",
|
||||
"raea-sys-viewbox",
|
||||
"serde_json",
|
||||
"wgpu",
|
||||
]
|
||||
@@ -15117,7 +15307,6 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"junction",
|
||||
"libc",
|
||||
"raea-core-scene",
|
||||
"raea-io-home",
|
||||
"raea-io-media",
|
||||
@@ -15125,10 +15314,10 @@ dependencies = [
|
||||
"raea-native",
|
||||
"raea-runtime-bundle-lib",
|
||||
"raea-runtime-cssurls",
|
||||
"raea-runtime-pid",
|
||||
"raea-sys-layers",
|
||||
"regex",
|
||||
"serde_json",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -15146,7 +15335,6 @@ name = "raea-runtime-calls"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bevy",
|
||||
"image",
|
||||
"manifold-rust",
|
||||
"parley",
|
||||
@@ -15157,6 +15345,7 @@ dependencies = [
|
||||
"raea-io-net",
|
||||
"raea-io-trace",
|
||||
"raea-native",
|
||||
"raea-runtime-ecs",
|
||||
"raea-runtime-plugins",
|
||||
"raea-runtime-wear",
|
||||
"raea-sys-fonts",
|
||||
@@ -15222,6 +15411,14 @@ dependencies = [
|
||||
"vello",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-ecs"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-edit"
|
||||
version = "0.1.0"
|
||||
@@ -15261,7 +15458,9 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-core-facts",
|
||||
"raea-core-scene",
|
||||
"raea-runtime-lod-plan",
|
||||
"raea-sys-contact",
|
||||
"raea-sys-notice",
|
||||
"raea-sys-stage",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -15291,6 +15490,7 @@ dependencies = [
|
||||
"raea-runtime-page",
|
||||
"raea-runtime-pagestore",
|
||||
"raea-runtime-react",
|
||||
"raea-runtime-review",
|
||||
"raea-runtime-scene",
|
||||
"raea-runtime-scene3d",
|
||||
"raea-runtime-sound",
|
||||
@@ -15373,6 +15573,17 @@ dependencies = [
|
||||
"rquickjs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-kinds"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-core-scene",
|
||||
"raea-runtime-look",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-live"
|
||||
version = "0.1.0"
|
||||
@@ -15401,6 +15612,18 @@ dependencies = [
|
||||
"winit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-lod-plan"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"dunce",
|
||||
"raea-core-facts",
|
||||
"raea-core-scene",
|
||||
"raea-sys-stage",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-look"
|
||||
version = "0.1.0"
|
||||
@@ -15417,12 +15640,9 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bevy",
|
||||
"image",
|
||||
"raea-core-scene",
|
||||
"raea-core-wire",
|
||||
"raea-io-assets",
|
||||
"raea-io-home",
|
||||
"raea-io-media",
|
||||
"raea-io-net",
|
||||
"raea-page",
|
||||
"raea-render",
|
||||
@@ -15431,8 +15651,8 @@ dependencies = [
|
||||
"raea-runtime-react",
|
||||
"raea-runtime-twins",
|
||||
"raea-runtime-view",
|
||||
"raea-sys-facetrack",
|
||||
"raea-sys-fonts",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-image",
|
||||
"raea-sys-page",
|
||||
"raea-sys-screen",
|
||||
@@ -15449,6 +15669,14 @@ dependencies = [
|
||||
"twox-hash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-pid"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-plugins"
|
||||
version = "0.1.0"
|
||||
@@ -15476,6 +15704,7 @@ dependencies = [
|
||||
"raea-core-alloc",
|
||||
"raea-core-animate",
|
||||
"raea-core-scene",
|
||||
"raea-core-shape",
|
||||
"raea-core-wire",
|
||||
"raea-io-assets",
|
||||
"raea-io-media",
|
||||
@@ -15500,6 +15729,18 @@ dependencies = [
|
||||
"raea-sys-light-meter",
|
||||
"raea-sys-page",
|
||||
"serde_json",
|
||||
"xxhash-rust",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-review"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"raea-core-facts",
|
||||
"raea-core-review",
|
||||
"raea-sys-light-meter",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -15510,6 +15751,7 @@ dependencies = [
|
||||
"raea-core-program",
|
||||
"raea-core-review",
|
||||
"raea-core-scene",
|
||||
"raea-runtime-kinds",
|
||||
"raea-runtime-look",
|
||||
"raea-runtime-scene2d",
|
||||
"raea-sys-frame",
|
||||
@@ -15548,6 +15790,7 @@ dependencies = [
|
||||
"raea-sys-sampler",
|
||||
"raea-sys-shader",
|
||||
"raea-sys-share",
|
||||
"raea-sys-toon",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
@@ -15730,6 +15973,17 @@ dependencies = [
|
||||
"raea-core-animate",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-atlas"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"parry3d",
|
||||
"raea-core-meshcheck",
|
||||
"raea-sys-glb",
|
||||
"rayon",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-bake"
|
||||
version = "0.1.0"
|
||||
@@ -15819,8 +16073,10 @@ dependencies = [
|
||||
"bevy",
|
||||
"raea-core-facts",
|
||||
"raea-core-meshcheck",
|
||||
"raea-core-modelbox",
|
||||
"raea-core-scene",
|
||||
"raea-core-shape",
|
||||
"raea-core-zfight",
|
||||
"raea-io-trace",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -15873,6 +16129,17 @@ dependencies = [
|
||||
"parry3d",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-facetrack"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"raea-io-assets",
|
||||
"raea-io-media",
|
||||
"raea-sys-frame",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-filters"
|
||||
version = "0.1.0"
|
||||
@@ -15880,7 +16147,9 @@ dependencies = [
|
||||
"anyrender",
|
||||
"anyrender_vello",
|
||||
"blitz-paint",
|
||||
"png 0.18.1",
|
||||
"rustc-hash 2.1.3",
|
||||
"skrifa 0.44.0",
|
||||
"vello",
|
||||
"wgpu",
|
||||
]
|
||||
@@ -15924,6 +16193,14 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-fixes"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-io-home",
|
||||
"rusqlite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-fog"
|
||||
version = "0.1.0"
|
||||
@@ -15950,17 +16227,6 @@ dependencies = [
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-foliage"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"parry3d",
|
||||
"raea-core-ease",
|
||||
"raea-sys-glb",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-fonts"
|
||||
version = "0.1.0"
|
||||
@@ -16001,6 +16267,7 @@ dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-core-scene",
|
||||
"raea-core-tables",
|
||||
"raea-io-media",
|
||||
"raea-sys-layers",
|
||||
"raea-sys-shots",
|
||||
@@ -16013,6 +16280,7 @@ name = "raea-sys-framepass"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-sys-compose",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-material",
|
||||
"raea-sys-sampler",
|
||||
@@ -16170,6 +16438,20 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-lightbake"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"parry3d",
|
||||
"pollster 0.4.0",
|
||||
"raea-gpu-device",
|
||||
"raea-sys-atlas",
|
||||
"rayon",
|
||||
"serde_json",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-lod"
|
||||
version = "0.1.0"
|
||||
@@ -16207,9 +16489,11 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bevy",
|
||||
"blake3",
|
||||
"image",
|
||||
"intel_tex_2",
|
||||
"raea-core-program",
|
||||
"raea-core-shape",
|
||||
"raea-io-home",
|
||||
"raea-io-net",
|
||||
"raea-io-trace",
|
||||
"raea-sys-frame",
|
||||
@@ -16223,6 +16507,13 @@ dependencies = [
|
||||
name = "raea-sys-measure"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-memtally"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-mesh"
|
||||
version = "0.1.0"
|
||||
@@ -16253,11 +16544,22 @@ dependencies = [
|
||||
"raea-io-home",
|
||||
"raea-io-media",
|
||||
"raea-io-trace",
|
||||
"raea-sys-mix-device",
|
||||
"raea-sys-mix-level",
|
||||
"raea-sys-tone",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-mix-device"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"audioadapter-buffers",
|
||||
"cpal 0.15.3",
|
||||
"firewheel",
|
||||
"raea-io-trace",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-mix-level"
|
||||
version = "0.1.0"
|
||||
@@ -16285,6 +16587,27 @@ dependencies = [
|
||||
"mlx-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-motionfaults"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"glam 0.33.12",
|
||||
"raea-core-ease",
|
||||
"raea-sys-body",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-notice"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-ease",
|
||||
"raea-core-scene",
|
||||
"raea-io-home",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-page"
|
||||
version = "0.1.0"
|
||||
@@ -16505,6 +16828,7 @@ name = "raea-sys-splat"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-ease",
|
||||
"raea-core-program",
|
||||
"raea-sys-frame",
|
||||
"serde_json",
|
||||
@@ -16570,6 +16894,17 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-toon"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-core-shape",
|
||||
"raea-sys-frame",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-touch"
|
||||
version = "0.1.0"
|
||||
@@ -16590,6 +16925,7 @@ name = "raea-sys-viewbox"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-sys-compose",
|
||||
"raea-sys-frame",
|
||||
]
|
||||
|
||||
@@ -16629,7 +16965,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"parry3d",
|
||||
"raea-core-meshcheck",
|
||||
"raea-sys-atlas",
|
||||
"raea-sys-damage",
|
||||
"raea-sys-exposure",
|
||||
"raea-sys-glb",
|
||||
@@ -20232,8 +20568,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "taffy"
|
||||
version = "0.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3c8480887e8803986d96a7173729565520d4bbb721ad6b7ad6941a22897207aa"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"slotmap",
|
||||
|
||||
+35
-2
@@ -6,10 +6,13 @@ members = [
|
||||
"core/animate",
|
||||
"core/ask",
|
||||
"core/brief",
|
||||
"core/zfight",
|
||||
"core/modelbox",
|
||||
"core/facts",
|
||||
"core/ease",
|
||||
"core/fonts",
|
||||
"core/program",
|
||||
"core/tables",
|
||||
"core/scene",
|
||||
"core/shape",
|
||||
"core/meshcheck",
|
||||
@@ -28,6 +31,7 @@ members = [
|
||||
"systems/phase",
|
||||
"systems/shader/wgsl",
|
||||
"systems/sampler",
|
||||
"systems/memtally",
|
||||
"systems/parity",
|
||||
"systems/shader",
|
||||
"systems/three-shader",
|
||||
@@ -39,12 +43,15 @@ members = [
|
||||
"engine/bevy-world",
|
||||
"engine/bundle",
|
||||
"engine/cli",
|
||||
"engine/cli/goal",
|
||||
"engine/cli/refused",
|
||||
"engine/neural",
|
||||
"engine/light",
|
||||
"engine/modules",
|
||||
"engine/native",
|
||||
"io/npm",
|
||||
"engine/page",
|
||||
"engine/page/ax",
|
||||
"engine/page/host",
|
||||
"engine/rune",
|
||||
"engine/rune/page",
|
||||
@@ -83,6 +90,7 @@ members = [
|
||||
"systems/tone",
|
||||
"systems/mix",
|
||||
"systems/mix/level",
|
||||
"systems/mix/device",
|
||||
"systems/ml",
|
||||
"systems/mlx",
|
||||
"systems/kimodo",
|
||||
@@ -91,6 +99,7 @@ members = [
|
||||
"systems/vision",
|
||||
"systems/columns",
|
||||
"systems/index",
|
||||
"systems/fixes",
|
||||
"systems/fingerprint",
|
||||
"systems/fingerprint-use",
|
||||
"systems/fingerprint-things",
|
||||
@@ -100,6 +109,8 @@ members = [
|
||||
"systems/a11y",
|
||||
"systems/bake",
|
||||
"systems/contact",
|
||||
"systems/notice",
|
||||
"systems/motionfaults",
|
||||
"systems/light-meter",
|
||||
"systems/measure",
|
||||
"systems/canvas",
|
||||
@@ -116,6 +127,7 @@ members = [
|
||||
"systems/page-net",
|
||||
"systems/page-ops",
|
||||
"systems/frame",
|
||||
"systems/facetrack",
|
||||
"systems/engine-shaders",
|
||||
"systems/shots",
|
||||
"systems/hold",
|
||||
@@ -136,7 +148,6 @@ members = [
|
||||
"systems/matchmove",
|
||||
"systems/grid",
|
||||
"systems/lod",
|
||||
"systems/foliage",
|
||||
"systems/viewbox",
|
||||
"systems/rendermap",
|
||||
"systems/meshseq",
|
||||
@@ -144,6 +155,7 @@ members = [
|
||||
"systems/look",
|
||||
"systems/compose",
|
||||
"systems/material",
|
||||
"systems/toon",
|
||||
"systems/mesh",
|
||||
"systems/post",
|
||||
"systems/fog",
|
||||
@@ -165,12 +177,16 @@ members = [
|
||||
"tools/perceive",
|
||||
"engine/render",
|
||||
"engine/render/raytrace",
|
||||
"engine/render/plugins",
|
||||
"engine/render/denoise/bench",
|
||||
"engine/seedling",
|
||||
"engine/web",
|
||||
"runtime/react",
|
||||
"runtime/track",
|
||||
"runtime/pagestore",
|
||||
"runtime/review",
|
||||
"runtime/cssurls",
|
||||
"runtime/pid",
|
||||
"bench/bridge",
|
||||
"bench/bevy-parity",
|
||||
"bench/lightbench",
|
||||
@@ -182,25 +198,32 @@ members = [
|
||||
"runtime/bundle/lib",
|
||||
"engine/shape-web",
|
||||
"runtime/calls",
|
||||
"runtime/ecs",
|
||||
"runtime/shots",
|
||||
"runtime/wear",
|
||||
"runtime/canvas",
|
||||
"runtime/export",
|
||||
"runtime/endchecks",
|
||||
"runtime/lod-plan",
|
||||
"runtime/live",
|
||||
"runtime/page",
|
||||
"runtime/appscreen",
|
||||
"runtime/sound",
|
||||
"runtime/look",
|
||||
"runtime/scene",
|
||||
"runtime/kinds",
|
||||
"runtime/scene2d",
|
||||
"runtime/shared",
|
||||
"apps/ask",
|
||||
"apps/lightbake",
|
||||
"systems/lightbake",
|
||||
"systems/atlas",
|
||||
"apps/double",
|
||||
"apps/check",
|
||||
"apps/check/cause",
|
||||
"apps/check/flash",
|
||||
"apps/check/inbox",
|
||||
"apps/check/make",
|
||||
"apps/check/read",
|
||||
"apps/check/text",
|
||||
"apps/direction",
|
||||
@@ -214,15 +237,17 @@ members = [
|
||||
"apps/motion",
|
||||
"apps/engines",
|
||||
"apps/interchange",
|
||||
"apps/judge",
|
||||
"apps/make",
|
||||
"apps/solid",
|
||||
"apps/scene",
|
||||
"apps/voice",
|
||||
"apps/media",
|
||||
"apps/targets",
|
||||
"apps/game",
|
||||
"apps/capcut",
|
||||
"apps/layers",
|
||||
"apps/play",
|
||||
"apps/playable",
|
||||
"tools/sdk-props",
|
||||
"tools/hands-audit",
|
||||
]
|
||||
@@ -331,6 +356,10 @@ split-debuginfo = "packed"
|
||||
[patch.crates-io]
|
||||
# the MP4 muxer, vendored
|
||||
muxide = { path = "vendor/muxide" }
|
||||
# metis-sys 0.3.2 (bevy_pbr's meshlets) with GKlib's own stdint.h and inttypes.h stand-ins used only before Visual
|
||||
# Studio 2013: Visual Studio 18's stdint.h types int_fast16_t differently, and every C file failed (raea#82; the change
|
||||
# is marked "raea:" in vendor/GKlib/gk_arch.h). Its test graphs, manual and programs are left out
|
||||
metis-sys = { path = "vendor/metis-sys" }
|
||||
# usvg 0.48.1 spacing a chunk's last letter as Chrome does (changes marked "raea:", docs/layout-reads.feature LR10)
|
||||
usvg = { path = "vendor/usvg" }
|
||||
# bevy_seedling 0.8.0 without its cpal 0.18 paths, ported to Bevy 0.20 (changes marked "raea:")
|
||||
@@ -387,6 +416,10 @@ vello_encoding = { path = "vendor/vello_encoding" }
|
||||
# (changes marked "raea:"): raea-page blends a bevy_ui page as Bevy does (bevy_ui on Blitz). No upstream
|
||||
# equivalent yet (linebender/vello blends the encoded values).
|
||||
vello_shaders = { path = "vendor/vello_shaders" }
|
||||
# taffy 0.15.0 (Blitz's, Bevy UI's, rune-taffy's) with a flex line whose items overflow its container by less than
|
||||
# Chrome's layout unit, 1/64 px, kept on one line: f32 rounding wrapped items that add up to the container's width
|
||||
# (changes marked "raea:", raea #252). Back to upstream once Taffy breaks flex lines with a tolerance.
|
||||
taffy = { path = "vendor/taffy" }
|
||||
# Firewheel 0.12 on Bevy 0.20: bevy_reflect 0.20 and a glam-33 feature (BillyDM/Firewheel#144; changes marked "raea:")
|
||||
firewheel = { path = "vendor/firewheel" }
|
||||
firewheel-core = { path = "vendor/firewheel-core" }
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
<p align="center">
|
||||
Tell your AI what to make. Videos, motion graphics, 3D and games, written as React and TypeScript<br>
|
||||
(the code your AI already writes) and rendered on your own GPU, faster than they play.
|
||||
(the code your AI already writes) and rendered on your own GPU.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -32,10 +32,10 @@
|
||||
|
||||
---
|
||||
|
||||
> **0.1.6** (17 November 2026) is the latest release: the engine and the desktop app on macOS (Apple Silicon), Linux
|
||||
> (x86_64) and, newest and least tested, Windows 10 and 11 (x86_64). raea is young and moves fast, with a release most
|
||||
> days since 0.1.1 on 11 November: expect rough edges, and tell us what you hit in an
|
||||
> [issue](https://github.com/shinyobjectz/raea/issues), or from your agent with `raea bug`.
|
||||
> raea releases experimentally and often, so the newest release is always on
|
||||
> [Releases](https://github.com/shinyobjectz/raea/releases). The app is unstable for now, especially on Linux and
|
||||
> Windows: expect rough edges, and tell us what you hit in an [issue](https://github.com/shinyobjectz/raea/issues), or
|
||||
> from your agent with `raea bug`.
|
||||
|
||||
## The app
|
||||
|
||||
@@ -80,6 +80,13 @@ The installer puts the `raea` command under `~/.raea`, links it into `~/.local/b
|
||||
work. Run it again to update. The engine is free and needs no account. Tarballs and checksums are on the
|
||||
[releases page](https://github.com/shinyobjectz/raea/releases).
|
||||
|
||||
Linux release builds also package an x86_64 AppImage of the engine command and
|
||||
attach it and its SHA256 checksum beside the release archives.
|
||||
Make it executable with `chmod +x raea-*.AppImage`, then run
|
||||
`./raea-VERSION-linux-x86_64.AppImage --help` or pass the usual `raea` arguments.
|
||||
See [the AppImage release recipe](tools/release/README.md#linux-appimage) for build
|
||||
instructions, runtime requirements and running without FUSE.
|
||||
|
||||
On Windows 10 or 11, in PowerShell:
|
||||
|
||||
```powershell
|
||||
@@ -123,7 +130,7 @@ floor (`raea check hello.mp4`). `raea init` starts a project, and `raea --help`
|
||||
Gaussian splats, and Bevy plugins compiled into the engine. three.js work runs as it's written: a React Three Fiber
|
||||
scene inside `<R3F>`, or a three.js page's script inside `<Three program>`.
|
||||
- **Sound.** One mixer for live play and offline render, instruments and effects, and local models for foley and
|
||||
instrument notes (`raea sao`, `raea tokensynth`).
|
||||
instrument notes (`raea make sao`, `raea make tokensynth`).
|
||||
- **Built for agents.** Everything it draws stays queryable as data, so an agent can render a frame, look at it, and
|
||||
fix what's wrong without a person in the loop.
|
||||
|
||||
@@ -138,9 +145,10 @@ Apache-2.0, to read, render and take apart, and its models, textures and sound f
|
||||
- **Agent skills.** They live in [raea-skills](https://github.com/shinyobjectz/raea-skills), pinned here as
|
||||
[`skills/`](skills): `raea` teaches an agent to write, render and check raea compositions, 3D and games
|
||||
included. The installer adds it to `~/.claude/skills`, and `raea skills install --agent NAME` to other agents.
|
||||
- **Claude plugin.** The raea skill and two hooks (raea's quick check after a composition is saved, and media shown in
|
||||
the raea app). In Claude Code: `/plugin install raea --marketplace shinyobjectz/raea-skills`. It's the `skills/`
|
||||
folder of raea-skills, and `/plugin marketplace add shinyobjectz/raea` installs the same one.
|
||||
- **Claude plugin.** The raea skill and its hooks: media an agent opens goes to the raea app, and `raea check` holds
|
||||
the brief's goals as a turn ends. Nothing is checked after a save, since a render checks its own output. In Claude
|
||||
Code: `/plugin install raea --marketplace shinyobjectz/raea-skills`. It's the `skills/` folder of raea-skills, and
|
||||
`/plugin marketplace add shinyobjectz/raea` installs the same one.
|
||||
- **Craft guides.** `raea guide` prints the floor every edit is held to and the guides for pitches, explainers, stories,
|
||||
games, motion, music and layout. `raea context PROJECT` says what to read before working on a project.
|
||||
- **Bug reports.** When an agent finds a bug in raea itself, `raea bug TITLE --text TEXT` sends it to raea's server
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "raea ask: questions about a piece's picture and sound, prepared from what raea knows of it, asked of clef in parallel from the person's plan, and every answer kept"
|
||||
description = "Questions about a piece's picture and sound, prepared from what raea knows of it, asked of clef in parallel from the person's plan, and every answer kept"
|
||||
|
||||
[dependencies]
|
||||
# the question format and the standard sets; the one clef client, routed to the person's plan first (docs/ask.feature)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! threshold, the problem score that flags 10% of the clean labels. The gates are the fingerprint's (16 labels of each
|
||||
//! kind, from 3 projects, an AUC of 0.8). A question that passes is calibrated at its threshold: its answers are
|
||||
//! findings, and the person's calibration replaces raea's shipped one. One under 0.6 after 32 labels doesn't separate,
|
||||
//! and says which labels it missed, so its words can be fixed. `raea ask try` asks new words of the labelled clips and
|
||||
//! and says which labels it missed, so its words can be fixed. `try_words` asks new words of the labelled clips and
|
||||
//! sets both AUCs side by side.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
@@ -135,7 +135,7 @@ fn versions(only: Option<&str>, all: &[Label]) -> Vec<Question> {
|
||||
out
|
||||
}
|
||||
|
||||
/// `raea ask calibrate [ID]`: the feed's labels read again, then every labelled version held to them. The ones that
|
||||
/// `calibrate(ID)`: the feed's labels read again, then every labelled version held to them. The ones that
|
||||
/// pass are kept as the person's calibration; one that no longer passes loses it.
|
||||
pub fn calibrate(only: Option<&str>) -> Result<(Vec<Standing>, (usize, usize)), String> {
|
||||
let feed = labels::from_feed()?;
|
||||
@@ -159,7 +159,7 @@ fn today() -> String {
|
||||
raea_io_trace::utc(std::time::SystemTime::now()).0.chars().take(10).collect()
|
||||
}
|
||||
|
||||
/// The groups `raea ask try` sends: the new question on each labelled clip set, with the state it was asked with.
|
||||
/// The groups `try_words` sends: the new question on each labelled clip set, with the state it was asked with.
|
||||
pub fn try_groups(like: &str, words: &str) -> Result<(Question, Question, Vec<Group>), String> {
|
||||
let all = labels::all();
|
||||
let standing = labels::standing(&all);
|
||||
@@ -182,7 +182,7 @@ pub fn try_groups(like: &str, words: &str) -> Result<(Question, Question, Vec<Gr
|
||||
groups.push(Group { piece, from, to, sees: new.sees, hears: new.hears, with: vec![], questions: vec![new.clone()], kept: Some(Arc::new(kept)) });
|
||||
}
|
||||
if groups.is_empty() {
|
||||
return Err(format!("ask try: none of {like}'s labelled clips are still kept (raea ask calibrate lists its labels)"));
|
||||
return Err(format!("ask try: none of {like}'s labelled clips are still kept (calibrate() lists its labels)"));
|
||||
}
|
||||
Ok((old, new, groups))
|
||||
}
|
||||
@@ -201,7 +201,7 @@ fn media(names: &[&str]) -> Option<Media> {
|
||||
Some(m)
|
||||
}
|
||||
|
||||
/// `raea ask try "WORDS" --like ID`: the new words asked of the old question's labelled clips, and both versions held to
|
||||
/// `try_words(LIKE, WORDS)`: the new words asked of the old question's labelled clips, and both versions held to
|
||||
/// the same labels.
|
||||
pub fn try_words(like: &str, words: &str, o: &Opts, out: &mut dyn FnMut(Event)) -> Result<(Summary, Option<(Standing, Standing)>), String> {
|
||||
let (old, new, groups) = try_groups(like, words)?;
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
//! Labels (docs/ask.feature AK6): whether a question's problem was really there in what one call sent, so the question
|
||||
//! can be calibrated on the person's own eye (calibrate.rs). A label belongs to a question and to the clips a call sent
|
||||
//! (by their hashes), never to one answer: the same question reworded, asked again of the same clips, has the same
|
||||
//! labels, which is what lets `raea ask try` measure new words.
|
||||
//! labels, which is what lets `try_words` measure new words.
|
||||
//!
|
||||
//! Where labels come from:
|
||||
//! - `raea ask verdict ANSWER WORD`: the person answers the question themselves, in its own terms (yes or no, an option,
|
||||
//! - `verdict(ANSWER, WORD)`: the person answers the question themselves, in its own terms (yes or no, an option,
|
||||
//! a level). Theirs counts first.
|
||||
//! - The feed: a note of the person's on the render (its copy in the project's feed, known by `record::ident`), pinned
|
||||
//! inside the window or not pinned at all, holding one of the question's label words, is a yes; an approved post (done)
|
||||
//! with no such note is a no. Read again by every `raea ask calibrate`.
|
||||
//! with no such note is a no. Read again by every `calibrate()`.
|
||||
//! - Another eye (`verdict --eye agent`: an agent's own look) is kept as `eye:NAME` and never counted, as the
|
||||
//! fingerprint keeps another eye's readings (FP6d).
|
||||
|
||||
@@ -149,7 +149,7 @@ fn label(q: &str, call: &Value, bad: bool, source: &str, note: Option<String>) -
|
||||
}
|
||||
}
|
||||
|
||||
/// `raea ask verdict ANSWER WORD [--eye NAME]`: the person's answer to the question on that answer's clips (or another
|
||||
/// `verdict(ANSWER, WORD, EYE)`: the person's answer to the question on that answer's clips (or another
|
||||
/// eye's, kept and never counted). A verdict given again replaces the last from the same source.
|
||||
pub fn verdict(answer: &str, said: &str, eye: Option<&str>) -> Result<String, String> {
|
||||
let row = record::rows("answers.jsonl").into_iter().find(|a| a["id"] == answer).ok_or_else(|| format!("ask verdict: no answer {answer} in {}", record::dir().display()))?;
|
||||
|
||||
+4
-8
@@ -1,17 +1,13 @@
|
||||
//! `raea ask` (docs/ask.feature AK2-AK3): questions about a piece's picture and sound. `prepare` reads what raea knows
|
||||
//! of the piece and keeps the questions that apply; `runner` plans the calls, cuts each clip once and asks in parallel;
|
||||
//! `record` keeps every call and answer; `labels` reads the person's verdicts, notes and approvals into labels, and
|
||||
//! `calibrate` holds each question to them (AK6-AK7); `verbs` is the command. `raea check`, the app's critique and the
|
||||
//! fingerprint's double-check go through the same runner.
|
||||
//! Questions about a piece's picture and sound (docs/ask.feature AK2-AK3), asked for the fingerprint's double-check
|
||||
//! (`raea fingerprint score --ask`, apps/double). `prepare` reads what raea knows of the piece and keeps the questions
|
||||
//! that apply; `runner` plans the calls, cuts each clip once and asks in parallel; `record` keeps every call and answer;
|
||||
//! `labels` reads the person's notes and approvals into labels, and `calibrate` holds each question to them (AK6-AK7).
|
||||
|
||||
pub mod calibrate;
|
||||
pub mod labels;
|
||||
pub mod prepare;
|
||||
pub mod record;
|
||||
pub mod runner;
|
||||
pub mod verbs;
|
||||
|
||||
pub use verbs::{USAGE, cli};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
+3
-24
@@ -3,10 +3,9 @@
|
||||
//! answer in answers.jsonl (the call, the question and its version, the reading). The clips themselves are kept by hash
|
||||
//! in media/, at most 2 GB, the oldest out first, so new words can be asked of the same media. A call keeps what its
|
||||
//! file was (`ident`), so a note on the render's copy in the feed labels it (labels.rs), and an answer keeps its whole
|
||||
//! question, so a verdict reads in its terms and `raea ask try` can reword it.
|
||||
//! question, so a verdict reads in its terms and `try_words` can reword it.
|
||||
|
||||
use std::io::Write as _;
|
||||
use std::io::{Read as _, Seek as _, SeekFrom};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use raea_core_ask::{Question, Reading};
|
||||
@@ -50,28 +49,8 @@ fn hex(digest: &[u8]) -> String {
|
||||
digest.iter().take(16).map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
/// What a file is, cheaply: its size and a hash of its first and last MB. A render is known again by its copy in the
|
||||
/// feed, and a later render to the same path isn't taken for it.
|
||||
pub fn ident(path: &Path) -> Option<String> {
|
||||
const MB: u64 = 1 << 20;
|
||||
let mut f = std::fs::File::open(path).ok()?;
|
||||
let len = f.metadata().ok()?.len();
|
||||
let mut h = Sha256::new();
|
||||
let mut part = vec![0u8; len.min(MB) as usize];
|
||||
f.read_exact(&mut part).ok()?;
|
||||
h.update(&part);
|
||||
if len > 2 * MB {
|
||||
f.seek(SeekFrom::Start(len - MB)).ok()?;
|
||||
f.read_exact(&mut part).ok()?;
|
||||
h.update(&part);
|
||||
}
|
||||
Some(format!("{len}-{}", hex(&h.finalize())))
|
||||
}
|
||||
|
||||
/// The size an ident names, to pass over files that can't be it without reading them.
|
||||
pub fn ident_len(ident: &str) -> Option<u64> {
|
||||
ident.split_once('-')?.0.parse().ok()
|
||||
}
|
||||
/// What a file is, cheaply, and the size an ident names (raea-core-ask's).
|
||||
pub use raea_core_ask::ident::{ident, ident_len};
|
||||
|
||||
/// One of the record's files written whole, through a temporary file, so a reader never sees half of it.
|
||||
pub fn write_whole(file: &str, text: &str) -> Result<(), String> {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! call whose questions depend on whether anyone speaks when that isn't known), each clip cut once, the calls
|
||||
//! made in parallel, the answers streamed back as they come and kept. A pool that's spent partway keeps what came and
|
||||
//! reports the rest as waiting for it. `dry` cuts the media and says what would be sent, and spends nothing. A group can
|
||||
//! carry clips kept from an earlier call instead of a file to cut (`raea ask try`), and every question goes out with the
|
||||
//! carry clips kept from an earlier call instead of a file to cut (`try_words`), and every question goes out with the
|
||||
//! person's own calibration when it has earned one (calibrate.rs).
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
@@ -50,10 +50,10 @@ pub struct Kept {
|
||||
pub sound_seconds: f64,
|
||||
}
|
||||
|
||||
/// One answer, or why a question wasn't asked or still waits: the line `raea ask --json` prints for each.
|
||||
/// One answer, or why a question wasn't asked or still waits: one line of JSON each.
|
||||
#[derive(Debug, Clone, Default, Serialize)]
|
||||
pub struct Answer {
|
||||
/// its id in the record (`raea ask verdict` takes it)
|
||||
/// its id in the record (`labels::verdict` takes it)
|
||||
pub answer: Option<String>,
|
||||
pub file: String,
|
||||
pub id: String,
|
||||
@@ -285,7 +285,7 @@ pub fn run_groups(groups: Vec<Group>, unasked: Vec<Answer>, o: &Opts, out: &mut
|
||||
sum
|
||||
}
|
||||
|
||||
/// The clips a call sent, kept by hash for `raea ask try`.
|
||||
/// The clips a call sent, kept by hash for `try_words`.
|
||||
fn kept(m: &Media) -> Vec<String> {
|
||||
let each = |v: &[Vec<u8>], ext: &str| v.iter().map(|b| record::keep_media(b, ext)).collect::<Vec<_>>();
|
||||
[each(&m.videos, "mp4"), each(&m.stills, "jpg"), each(&m.sounds, "mp3")].concat()
|
||||
|
||||
@@ -11,7 +11,7 @@ use crate::prepare::{self, Piece, VOICE};
|
||||
use crate::runner::{self, Answer, Entry, Event, Opts};
|
||||
|
||||
fn rubric() -> String {
|
||||
std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/guides/craft/rubric.md")).expect("the craft rubric")
|
||||
std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/guides/craft/verbs/critique.md")).expect("the critique guide")
|
||||
}
|
||||
|
||||
pub(crate) fn setup() {
|
||||
@@ -166,9 +166,3 @@ fn a_pool_spent_partway_keeps_what_came_and_the_rest_waits() {
|
||||
assert_eq!(got.iter().filter(|a| a.waits.as_deref().is_some_and(|w| w.contains("used up"))).count(), 2);
|
||||
assert_eq!(CALLS.load(Ordering::SeqCst), 3, "nothing is sent after the pool is spent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn own_words_keep_their_id() {
|
||||
assert_eq!(crate::verbs::own_id("Does the music fight the voice?"), "own-does-the-music-fight-the-voice");
|
||||
assert_eq!(crate::verbs::own_id("Does the music fight the voice?"), crate::verbs::own_id("does the MUSIC fight the voice"));
|
||||
}
|
||||
@@ -1,385 +0,0 @@
|
||||
//! `raea ask` (docs/ask.feature AK3): questions about a piece's picture and sound, from the command line or a batch,
|
||||
//! prepared (prepare.rs), asked in parallel (runner.rs) and kept (record.rs). It prints as answers come: words and a
|
||||
//! probability a line, or with `--json` one JSON object a line (an answer, a call `--dry` would make, then the summary).
|
||||
//! `--gate` exits 1 when a calibrated question flags (`--gate any`: when any does), for a pipeline. `verdict`,
|
||||
//! `calibrate` and `try` label the answers, calibrate the questions on them and measure new words (labels.rs,
|
||||
//! calibrate.rs; AK6-AK7).
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::io::Read as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use raea_core_ask::{Kind, Question, Window, library};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::labels::{self, span};
|
||||
use crate::prepare::{self, Piece};
|
||||
use crate::runner::{self, Entry, Event, Opts};
|
||||
use crate::{calibrate, record};
|
||||
|
||||
pub const USAGE: &str = "raea ask FILE [QUESTION...] [--choose A,B,C] [--grade] [--rate N] [--flag ANSWERS] [--set NAME] [--std ID] [--from S] [--to S] [--at S] [--with FILE2] [--brief brief.ts|none] [--words words.json] [--voice yes|no] [--state TEXT] [--dry] [--json] [--gate [any]] [--jobs N] | ask --batch FILE [--dry] [--json] [--gate [any]] [--jobs N] | ask list [SET] [--json] | ask verdict ANSWER WORD [--eye NAME] | ask calibrate [ID] [--json] | ask try WORDS --like ID [--dry] [--json] [--jobs N] (questions about a piece's picture and sound, answered by clef-omni and paid from your raea plan's pool when the app is signed in, else RAEA_AGENT_KEY's, else your own Cloudflare keys: your own words, or the standard sets (rubric, av, defects, platform, decide); every question about one clip goes in one call, --batch (a JSON list or JSON lines, - for stdin) asks many clips in parallel; --dry says what would be sent and spends nothing; answers are advice until a question is calibrated: verdict labels an answer, calibrate holds each question to your verdicts, notes and approvals, try asks new words of its labelled clips)";
|
||||
|
||||
const VALUED: [&str; 17] = ["--choose", "--rate", "--flag", "--set", "--std", "--from", "--to", "--at", "--with", "--brief", "--words", "--voice", "--state", "--jobs", "--batch", "--eye", "--like"];
|
||||
const BARE: [&str; 4] = ["--grade", "--dry", "--json", "--gate"];
|
||||
|
||||
/// The arguments: the words that aren't flags, each flag's values, and whether `--gate` is `--gate any`.
|
||||
#[derive(Default)]
|
||||
struct Args {
|
||||
words: Vec<String>,
|
||||
flags: BTreeMap<String, Vec<String>>,
|
||||
gate_any: bool,
|
||||
}
|
||||
|
||||
impl Args {
|
||||
fn parse(args: &[String]) -> Result<Args, String> {
|
||||
let mut a = Args::default();
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
let s = args[i].as_str();
|
||||
if VALUED.contains(&s) {
|
||||
let v = args.get(i + 1).ok_or_else(|| format!("ask: {s} takes a value\nusage: {USAGE}"))?;
|
||||
a.flags.entry(s.into()).or_default().push(v.clone());
|
||||
i += 1;
|
||||
} else if BARE.contains(&s) {
|
||||
a.flags.entry(s.into()).or_default();
|
||||
if s == "--gate" && args.get(i + 1).is_some_and(|v| v == "any") {
|
||||
a.gate_any = true;
|
||||
i += 1;
|
||||
}
|
||||
} else if s.starts_with("--") {
|
||||
return Err(format!("ask doesn't take {s}\nusage: {USAGE}"));
|
||||
} else {
|
||||
a.words.push(s.into());
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
Ok(a)
|
||||
}
|
||||
fn has(&self, f: &str) -> bool {
|
||||
self.flags.contains_key(f)
|
||||
}
|
||||
fn one(&self, f: &str) -> Option<&str> {
|
||||
self.flags.get(f).and_then(|v| v.last()).map(String::as_str)
|
||||
}
|
||||
fn num(&self, f: &str) -> Result<Option<f64>, String> {
|
||||
self.one(f).map(|v| v.parse::<f64>().map_err(|_| format!("ask: {f} takes seconds, got {v:?}"))).transpose()
|
||||
}
|
||||
fn list(&self, f: &str) -> Vec<String> {
|
||||
self.flags.get(f).into_iter().flatten().flat_map(|v| v.split(',')).map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The craft rubric's text, where the guides are installed, for the `rubric` set.
|
||||
pub fn rubric_md() -> Option<String> {
|
||||
std::fs::read_to_string(raea_io_home::home().join("sdk/guides/craft/rubric.md")).ok()
|
||||
}
|
||||
|
||||
/// A question's id from its words: `own-` and its first words, so the same words keep their id.
|
||||
pub fn own_id(words: &str) -> String {
|
||||
let slug: Vec<String> = words.split(|c: char| !c.is_ascii_alphanumeric()).filter(|w| !w.is_empty()).take(6).map(str::to_lowercase).collect();
|
||||
let mut id = format!("own-{}", slug.join("-"));
|
||||
id.truncate(raea_core_ask::limits::ID_LEN);
|
||||
id
|
||||
}
|
||||
|
||||
/// The questions an entry names: its own words (shaped by the kind flags), its sets and its standard ids.
|
||||
fn named(own: &[Question], sets: &[String], std: &[String], rubric: Option<&str>) -> Result<Vec<Question>, String> {
|
||||
let mut qs = own.to_vec();
|
||||
for s in sets {
|
||||
qs.extend(library::set(s, rubric)?);
|
||||
}
|
||||
for id in std {
|
||||
qs.push(library::find(id, rubric).ok_or_else(|| format!("ask: no standard question {id} (raea ask list)"))?);
|
||||
}
|
||||
Ok(qs)
|
||||
}
|
||||
|
||||
fn shaped(words: &str, a: &Args) -> Result<Question, String> {
|
||||
let mut q = Question::plain(&own_id(words), words);
|
||||
if let Some(c) = a.one("--choose") {
|
||||
q.kind = Kind::Choose;
|
||||
q.options = c.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect();
|
||||
} else if let Some(n) = a.one("--rate") {
|
||||
let n: usize = n.parse().map_err(|_| format!("ask: --rate takes how many levels, got {n:?}"))?;
|
||||
q.kind = Kind::Rate;
|
||||
q.options = (1..=n).map(|i| i.to_string()).collect();
|
||||
} else if a.has("--grade") {
|
||||
q.kind = Kind::Grade;
|
||||
}
|
||||
q.flags = a.list("--flag");
|
||||
if let Some(why) = raea_core_ask::limits::check(&q) {
|
||||
return Err(format!("ask: {why}"));
|
||||
}
|
||||
Ok(q)
|
||||
}
|
||||
|
||||
/// The window from --from, --to and --at (three seconds around it).
|
||||
fn window(a: &Args) -> Result<Option<Window>, String> {
|
||||
if let Some(at) = a.num("--at")? {
|
||||
return Ok(Some(Window { from: Some((at - 1.5).max(0.0)), to: Some(at + 1.5) }));
|
||||
}
|
||||
let (from, to) = (a.num("--from")?, a.num("--to")?);
|
||||
Ok((from.is_some() || to.is_some()).then_some(Window { from, to }))
|
||||
}
|
||||
|
||||
fn voice(v: Option<&str>) -> Result<Option<bool>, String> {
|
||||
match v {
|
||||
None => Ok(None),
|
||||
Some("yes" | "true") => Ok(Some(true)),
|
||||
Some("no" | "false") => Ok(Some(false)),
|
||||
Some(v) => Err(format!("ask: --voice takes yes or no, got {v:?}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Pieces read once a run, by what they were read with.
|
||||
type Pieces = HashMap<String, Arc<Piece>>;
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn piece(pieces: &mut Pieces, file: &str, brief: Option<&str>, words: Option<&str>, voice: Option<bool>, state: Option<String>) -> Result<Arc<Piece>, String> {
|
||||
let key = format!("{file}\u{1f}{brief:?}\u{1f}{words:?}\u{1f}{voice:?}\u{1f}{state:?}");
|
||||
if let Some(p) = pieces.get(&key) {
|
||||
return Ok(p.clone());
|
||||
}
|
||||
let p = Arc::new(Piece::read(Path::new(file), brief.map(Path::new), words.map(Path::new), voice, state).map_err(|e| format!("ask: {e}"))?);
|
||||
pieces.insert(key, p.clone());
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
fn entry(p: Arc<Piece>, window: Option<Window>, qs: Vec<Question>, with: Vec<PathBuf>, rubric: Option<&str>) -> Entry {
|
||||
let (questions, dropped) = prepare::keep(qs, &p.facts(), rubric);
|
||||
Entry { piece: p, window, questions, dropped, with }
|
||||
}
|
||||
|
||||
/// The command line's one entry.
|
||||
fn from_args(a: &Args, rubric: Option<&str>, pieces: &mut Pieces) -> Result<Vec<Entry>, String> {
|
||||
let Some((file, words)) = a.words.split_first() else { return Err(USAGE.into()) };
|
||||
let own = words.iter().map(|w| shaped(w, a)).collect::<Result<Vec<_>, _>>()?;
|
||||
let qs = named(&own, &a.list("--set"), &a.list("--std"), rubric)?;
|
||||
if qs.is_empty() {
|
||||
return Err(format!("ask: nothing to ask: give a question in words, --set or --std (raea ask list)\nusage: {USAGE}"));
|
||||
}
|
||||
let p = piece(pieces, file, a.one("--brief"), a.one("--words"), voice(a.one("--voice"))?, a.one("--state").map(str::to_string))?;
|
||||
let with = a.flags.get("--with").into_iter().flatten().map(PathBuf::from).collect();
|
||||
Ok(vec![entry(p, window(a)?, qs, with, rubric)])
|
||||
}
|
||||
|
||||
/// A batch: a JSON list of entries or JSON lines, from a file or stdin (`-`). Each entry is {file, window?, questions?
|
||||
/// (words or questions), set?, std?, with?, brief?, words?, voice?, state?}.
|
||||
fn from_batch(path: &str, rubric: Option<&str>, pieces: &mut Pieces) -> Result<Vec<Entry>, String> {
|
||||
let text = match path {
|
||||
"-" => {
|
||||
let mut s = String::new();
|
||||
std::io::stdin().read_to_string(&mut s).map_err(|e| format!("ask: stdin: {e}"))?;
|
||||
s
|
||||
}
|
||||
p => std::fs::read_to_string(p).map_err(|e| format!("ask: {p}: {e}"))?,
|
||||
};
|
||||
let rows: Vec<Value> = match serde_json::from_str::<Value>(text.trim()) {
|
||||
Ok(Value::Array(a)) => a,
|
||||
Ok(v @ Value::Object(_)) => vec![v],
|
||||
_ => text.lines().filter(|l| !l.trim().is_empty()).enumerate().map(|(i, l)| serde_json::from_str(l).map_err(|e| format!("ask: {path} line {}: {e}", i + 1))).collect::<Result<_, _>>()?,
|
||||
};
|
||||
let strs = |v: &Value| -> Vec<String> {
|
||||
match v {
|
||||
Value::String(s) => s.split(',').map(|s| s.trim().to_string()).collect(),
|
||||
Value::Array(a) => a.iter().filter_map(Value::as_str).map(str::to_string).collect(),
|
||||
_ => vec![],
|
||||
}
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for (n, r) in rows.iter().enumerate() {
|
||||
let at = |e: String| format!("ask: {path} entry {}: {e}", n + 1);
|
||||
let file = r["file"].as_str().ok_or_else(|| at("it has no file".into()))?;
|
||||
let own = r["questions"].as_array().into_iter().flatten().map(|q| match q {
|
||||
Value::String(w) => Ok(Question::plain(&own_id(w), w)),
|
||||
q => serde_json::from_value::<Question>(q.clone()).map_err(|e| e.to_string()),
|
||||
});
|
||||
let own = own.collect::<Result<Vec<_>, _>>().map_err(at)?;
|
||||
let qs = named(&own, &strs(&r["set"]), &strs(&r["std"]), rubric).map_err(at)?;
|
||||
let window: Option<Window> = serde_json::from_value(r["window"].clone()).ok();
|
||||
let v = voice(r["voice"].as_str()).map_err(at)?.or(r["voice"].as_bool());
|
||||
let p = piece(pieces, file, r["brief"].as_str(), r["words"].as_str(), v, r["state"].as_str().map(str::to_string)).map_err(at)?;
|
||||
out.push(entry(p, window, qs, strs(&r["with"]).into_iter().map(PathBuf::from).collect(), rubric));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `raea ask list [SET]`: the standard questions.
|
||||
fn list(a: &Args, rubric: Option<&str>) -> Result<String, String> {
|
||||
let sets: Vec<String> = match a.words.get(1) {
|
||||
Some(s) => vec![s.clone()],
|
||||
None => library::SETS.iter().map(|s| s.to_string()).collect(),
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
let mine = calibrate::local();
|
||||
for s in &sets {
|
||||
let mut qs = library::set(s, rubric)?;
|
||||
qs.iter_mut().for_each(|q| calibrate::apply(q, &mine));
|
||||
if a.has("--json") {
|
||||
out.push(json!({"set": s, "questions": qs}).to_string());
|
||||
continue;
|
||||
}
|
||||
out.push(format!("{s}:"));
|
||||
for q in qs {
|
||||
let how = if q.calibrated() { "calibrated" } else { "advice" };
|
||||
out.push(format!(" {:<28} {:<6} {:<10} {}", q.id, format!("{:?}", q.kind).to_lowercase(), how, q.ask));
|
||||
}
|
||||
}
|
||||
Ok(out.join("\n"))
|
||||
}
|
||||
|
||||
/// An event as a line of text.
|
||||
fn line(e: &Event, files: usize) -> String {
|
||||
match e {
|
||||
Event::Would(v) => {
|
||||
let qs: Vec<&str> = v["questions"].as_array().into_iter().flatten().filter_map(|q| q["id"].as_str()).collect();
|
||||
let m = &v["media"];
|
||||
let kb = |k: &str| m[k].as_array().map(|a| a.iter().filter_map(Value::as_u64).map(|b| format!("{} KB", b / 1024)).collect::<Vec<_>>().join(", ")).unwrap_or_default();
|
||||
format!(
|
||||
"would ask {} ({}) about {}:\n {}\n videos [{}], stills [{}], sounds [{}], about ${:.4}\n state: {}",
|
||||
qs.len(),
|
||||
span(v["from"].as_f64().unwrap_or(0.0), v["to"].as_f64()),
|
||||
v["file"].as_str().unwrap_or(""),
|
||||
qs.join(", "),
|
||||
kb("videos"),
|
||||
kb("stills"),
|
||||
kb("sounds"),
|
||||
v["estimate_usd"].as_f64().unwrap_or(0.0),
|
||||
v["state"].as_str().unwrap_or("")
|
||||
)
|
||||
}
|
||||
Event::Answer(a) => {
|
||||
let who = if files > 1 { format!("{}: ", a.file) } else { String::new() };
|
||||
let what = match (&a.says, &a.not_asked, &a.waits) {
|
||||
(Some(s), ..) => format!("{s} [{}]{}", span(a.from, a.to), if a.flagged && a.calibrated { " <- finding" } else if a.flagged { " <- flagged" } else { "" }),
|
||||
(_, Some(n), _) => format!("not asked: {n}"),
|
||||
(.., Some(w)) => w.clone(),
|
||||
_ => "no answer".into(),
|
||||
};
|
||||
format!("{who}{:<34} {what}", a.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `raea ask ...` with its exit code: 0, or 1 when it couldn't ask or a gate failed.
|
||||
pub fn cli(args: &[String]) -> i32 {
|
||||
match run(args) {
|
||||
Ok(code) => code,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run(args: &[String]) -> Result<i32, String> {
|
||||
let a = Args::parse(args)?;
|
||||
let rubric = rubric_md();
|
||||
let jobs = a.one("--jobs").map(|j| j.parse::<usize>().map_err(|_| format!("ask: --jobs takes a number, got {j:?}"))).transpose()?.unwrap_or(4);
|
||||
let sub = a.words.first().map(String::as_str).filter(|w| !Path::new(w).exists());
|
||||
match sub {
|
||||
Some("list") => {
|
||||
println!("{}", list(&a, rubric.as_deref())?);
|
||||
return Ok(0);
|
||||
}
|
||||
Some("verdict") => {
|
||||
let [_, answer, said] = a.words.as_slice() else { return Err(format!("ask verdict ANSWER WORD: the answer's id (from --json or {}) and your answer to its question", record::dir().join("answers.jsonl").display())) };
|
||||
println!("{}", labels::verdict(answer, said, a.one("--eye"))?);
|
||||
return Ok(0);
|
||||
}
|
||||
Some("calibrate") => return calibrated(&a),
|
||||
Some("try") => return tried(&a, jobs),
|
||||
_ => {}
|
||||
}
|
||||
let mut pieces = Pieces::new();
|
||||
let entries = match a.one("--batch") {
|
||||
Some(b) => from_batch(b, rubric.as_deref(), &mut pieces)?,
|
||||
None => from_args(&a, rubric.as_deref(), &mut pieces)?,
|
||||
};
|
||||
let (json_out, dry) = (a.has("--json"), a.has("--dry"));
|
||||
let files = pieces.len();
|
||||
let sum = runner::run(entries, &Opts::new(jobs, dry), &mut |e| {
|
||||
match (&e, json_out) {
|
||||
(Event::Answer(r), true) => println!("{}", serde_json::to_string(r).unwrap_or_default()),
|
||||
(Event::Would(v), true) => println!("{}", json!({"would": v})),
|
||||
(e, false) => println!("{}", line(e, files)),
|
||||
}
|
||||
});
|
||||
if json_out {
|
||||
println!("{}", json!({"summary": sum}));
|
||||
} else if dry {
|
||||
println!("{} call{}, about ${:.4}; nothing was sent", sum.calls, if sum.calls == 1 { "" } else { "s" }, sum.estimate);
|
||||
} else if sum.calls > 0 {
|
||||
let routes: Vec<&str> = sum.routes.iter().map(String::as_str).collect();
|
||||
let left = sum.pool_left.map(|l| format!(", ${l:.2} left this month")).unwrap_or_default();
|
||||
let waiting = if sum.waiting > 0 { format!("; {} wait for the pool", sum.waiting) } else { String::new() };
|
||||
println!(
|
||||
"asked {} question{} in {} call{} through {}: ${:.4}{left}{waiting}. Answers are advice until a question is calibrated (docs/ask.feature AK7).",
|
||||
sum.asked,
|
||||
if sum.asked == 1 { "" } else { "s" },
|
||||
sum.calls,
|
||||
if sum.calls == 1 { "" } else { "s" },
|
||||
routes.join(" and "),
|
||||
sum.cost
|
||||
);
|
||||
}
|
||||
if !dry && sum.calls == 0 {
|
||||
return Err("ask: nothing was asked (each question's line says why)".into());
|
||||
}
|
||||
// a gate fails on a flag (a calibrated one, or with `any` any), and on questions still waiting for the pool
|
||||
let flagged = if a.gate_any { sum.flagged } else { sum.flagged_calibrated };
|
||||
Ok(i32::from(a.has("--gate") && (flagged > 0 || sum.waiting > 0)))
|
||||
}
|
||||
|
||||
/// A version's standing as a line, with its misses below when it doesn't separate.
|
||||
fn standing_line(s: &calibrate::Standing) -> String {
|
||||
let auc = s.auc.map_or_else(|| "no AUC".to_string(), |a| format!("AUC {a:.2}"));
|
||||
let mut out = format!("{} ({}) \"{}\": {}, {auc} on {} labels; {}", s.id, &s.version[..8.min(s.version.len())], s.ask, s.state, s.problems + s.clean, s.why);
|
||||
if s.others > 0 {
|
||||
out += &format!(" ({} from other eyes, not counted)", s.others);
|
||||
}
|
||||
for m in &s.misses {
|
||||
let what = if m.bad { "a problem it scored" } else { "clean work it scored" };
|
||||
out += &format!("\n {what} {:.2}: {} ({}){}", m.problem, m.file, m.span, m.note.as_ref().map(|n| format!(" \"{n}\"")).unwrap_or_default());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `raea ask calibrate [ID]`: the feed's labels read again and each labelled question held to its labels.
|
||||
fn calibrated(a: &Args) -> Result<i32, String> {
|
||||
let (all, (yes, no)) = calibrate::calibrate(a.words.get(1).map(String::as_str))?;
|
||||
if a.has("--json") {
|
||||
println!("{}", json!({"feed": {"problems": yes, "clean": no}}));
|
||||
all.iter().for_each(|s| println!("{}", serde_json::to_string(s).unwrap_or_default()));
|
||||
return Ok(0);
|
||||
}
|
||||
println!("from the feed: {yes} note{} that saw a problem, {no} approval{} without one", if yes == 1 { "" } else { "s" }, if no == 1 { "" } else { "s" });
|
||||
if all.is_empty() {
|
||||
println!("no labelled questions yet: raea ask verdict ANSWER WORD labels one, and your notes on a posted render do too");
|
||||
}
|
||||
all.iter().for_each(|s| println!("{}", standing_line(s)));
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
/// `raea ask try WORDS --like ID`: new words asked of a question's labelled clips, both held to the same labels.
|
||||
fn tried(a: &Args, jobs: usize) -> Result<i32, String> {
|
||||
let words = a.words[1..].join(" ");
|
||||
let like = a.one("--like").ok_or("ask try WORDS --like ID: the question whose labelled clips the new words are asked of")?;
|
||||
if words.trim().is_empty() {
|
||||
return Err("ask try WORDS --like ID: the new words".into());
|
||||
}
|
||||
let json_out = a.has("--json");
|
||||
let (sum, both) = calibrate::try_words(like, &words, &Opts::new(jobs, a.has("--dry")), &mut |e| match (&e, json_out) {
|
||||
(Event::Would(v), true) => println!("{}", json!({"would": v})),
|
||||
(Event::Answer(r), true) => println!("{}", serde_json::to_string(r).unwrap_or_default()),
|
||||
(e, false) => println!("{}", line(e, 2)),
|
||||
})?;
|
||||
match (both, json_out) {
|
||||
(None, true) => println!("{}", json!({"summary": sum})),
|
||||
(None, false) => println!("{} call{}, about ${:.4}; nothing was sent", sum.calls, if sum.calls == 1 { "" } else { "s" }, sum.estimate),
|
||||
(Some((old, new)), true) => println!("{}", json!({"summary": sum, "old": old, "new": new})),
|
||||
(Some((old, new)), false) => println!("${:.4} for {} calls\nold words: {}\nnew words: {}", sum.cost, sum.calls, standing_line(&old), standing_line(&new)),
|
||||
}
|
||||
Ok(i32::from(!a.has("--dry") && sum.calls == 0))
|
||||
}
|
||||
@@ -20,12 +20,14 @@ raea-io-ffmpeg = { path = "../../io/ffmpeg" }
|
||||
raea-sys-measure = { path = "../../systems/measure" }
|
||||
# what it reads of a video, through FFmpeg or raea's own decoders where it isn't installed
|
||||
raea-app-check-read = { path = "read" }
|
||||
# who can fix what it finds: the encode's or the picture's own, carried, a source (split out to keep this crate small)
|
||||
# who can fix what it finds: the encode's or the picture's own, carried, a source
|
||||
raea-app-check-cause = { path = "cause" }
|
||||
# the text rules on a render's manifest (split out: raea render holds its own text to them)
|
||||
raea-app-check-text = { path = "text" }
|
||||
# the flashing screen (WCAG 2.3.1), split out to keep this crate small
|
||||
# the flashing screen (WCAG 2.3.1)
|
||||
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)
|
||||
# what the person sent from the raea app, handed to the agent
|
||||
raea-app-check-inbox = { path = "inbox" }
|
||||
# the Stop gate for a `make` job (docs/goal.feature MK2)
|
||||
raea-app-check-make = { path = "make" }
|
||||
serde_json = "1"
|
||||
@@ -53,7 +53,7 @@ pub fn luma(rgba: &[u8], width: usize, w: usize, h: usize) -> Vec<u8> {
|
||||
}
|
||||
|
||||
/// `frames` as `comp` draws them, never encoded, as luma `w` x `h` (top-left): `raea render COMP --at F,... -o DIR/`
|
||||
/// (PNG) run by `raea` from the project, kept out of its record as the quick check's stills are
|
||||
/// (PNG) run by `raea` from the project, kept out of its record (RAEA_RECORD=off)
|
||||
pub fn unencoded(raea: &Path, project: &Path, comp: &Path, frames: &[i64], w: usize, h: usize) -> R<Vec<Vec<u8>>> {
|
||||
let mut wanted: Vec<i64> = frames.to_vec();
|
||||
wanted.sort_unstable();
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//! The flashing screen behind `raea check` (apps/check flash.rs feeds it the decoded frames): a pure measure of pixels,
|
||||
//! in a crate of its own so the check stays small (tools/size.sh).
|
||||
//! The flashing screen behind `raea check` (apps/check flash.rs feeds it the decoded frames): a pure measure of pixels.
|
||||
|
||||
/// Flashing past WCAG 2.3.1: more than three flashes in any one second, over enough of the frame to matter. A flash is a
|
||||
/// pair of opposing changes in the same pixels, so a shape sliding past isn't one. Each window, a third of the frame wide
|
||||
|
||||
@@ -55,6 +55,11 @@ fn said(l: &Value) -> String {
|
||||
"result" => format!("a result{on}: {text}"),
|
||||
"correction" => format!("a correction{on}: {text}"),
|
||||
"sign" => format!("a sign-off{on} (ask {})", l["ask"]),
|
||||
// a show only to be looked at (raea show --fyi), looked at: Got it, with a word or none
|
||||
"seen" => {
|
||||
let word = text.strip_prefix("Seen").unwrap_or(&text).trim_start_matches(':').trim();
|
||||
if word.is_empty() { format!("seen{on}") } else { format!("seen{on}: {word}") }
|
||||
}
|
||||
k => format!("{}{on}: {text}", if k.is_empty() { "something" } else { k }),
|
||||
};
|
||||
format!("- {what}")
|
||||
@@ -68,6 +73,17 @@ pub fn told(agent: &str, v: &Value) -> Option<String> {
|
||||
return None;
|
||||
}
|
||||
let list = lines.iter().map(said).collect::<Vec<_>>().join("\n");
|
||||
// only Got it on what was shown to look at: nothing to take up
|
||||
if !lines.iter().any(|l| l["kind"] != "seen") {
|
||||
return Some(format!("raea: the person has looked at what you showed them (your inbox, ~/.raea/inbox/{inbox}.jsonl):\n{list}\nNothing to do about it; carry on."));
|
||||
}
|
||||
// a session started again (resumed) after the person wrote to it while it was closed (Shane 11-28: "notes reach
|
||||
// closed sessions"): what waited is handed over before anything else
|
||||
if v["hook_event_name"].as_str() == Some("SessionStart") {
|
||||
return Some(format!(
|
||||
"raea: while this session was closed, the person sent this from the raea app (your inbox, ~/.raea/inbox/{inbox}.jsonl; marked read, so the app shows it as read):\n{list}\nTake it up first, before anything else. Answer an item with raea show --on ITEM --note LINE, or post the next version with raea show FILE --replaces ITEM."
|
||||
));
|
||||
}
|
||||
Some(format!(
|
||||
"raea: the person just sent this from the raea app (your inbox, ~/.raea/inbox/{inbox}.jsonl; marked read, so the app shows it as read):\n{list}\nTake it up now, before going on: it may change what you're doing. What you say next shows under your session in their feed; answer an item with raea show --on ITEM --note LINE, or post the next version with raea show FILE --replaces ITEM."
|
||||
))
|
||||
@@ -78,11 +94,17 @@ mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn each_line_is_handed_over_once_and_a_half_written_one_waits() {
|
||||
let d = std::env::temp_dir().join(format!("raea-inbox-{}", std::process::id()));
|
||||
/// an empty inbox folder of the test's own
|
||||
fn scratch(tag: &str) -> std::path::PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("raea-inbox-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_line_is_handed_over_once_and_a_half_written_one_waits() {
|
||||
let d = scratch("once");
|
||||
let f = d.join("claude-code-abcd1234.jsonl");
|
||||
std::fs::write(&f, "{\"kind\":\"message\",\"text\":\"more epic\"}\n{\"kind\":\"no").unwrap();
|
||||
let first = unread(&d, "claude-code-abcd1234");
|
||||
@@ -97,6 +119,25 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seen_is_said_as_seen_and_asks_nothing() {
|
||||
assert_eq!(said(&json!({"kind": "seen", "item": "i-2", "title": "Lobby", "text": "Seen"})), "- seen on item i-2 \"Lobby\"");
|
||||
assert_eq!(said(&json!({"kind": "seen", "item": "i-2", "title": "Lobby", "text": "Seen: lovely"})), "- seen on item i-2 \"Lobby\": lovely");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_waited_while_it_was_closed_is_handed_over_as_it_starts_again() {
|
||||
let d = scratch("start");
|
||||
std::fs::write(d.join("claude-code-5e55a0ff.jsonl"), "{\"kind\":\"edits\",\"item\":\"i-9\",\"title\":\"Cut\",\"text\":\"tighter open\"}\n").unwrap();
|
||||
// SAFETY: tests in this crate don't read RAEA_INBOX_DIR concurrently
|
||||
unsafe { std::env::set_var("RAEA_INBOX_DIR", &d) };
|
||||
let start = told("claude", &json!({"hook_event_name": "SessionStart", "source": "resume", "session_id": "5e55a0ff-1"})).unwrap();
|
||||
assert!(start.starts_with("raea: while this session was closed") && start.contains("- edits on item i-9 \"Cut\":\ntighter open"), "{start}");
|
||||
assert_eq!(told("claude", &json!({"hook_event_name": "UserPromptSubmit", "session_id": "5e55a0ff-1"})), None, "handed over once");
|
||||
unsafe { std::env::remove_var("RAEA_INBOX_DIR") };
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_inbox_is_named_as_raea_show_names_it() {
|
||||
assert_eq!(name("claude", &json!({"session_id": "15cd6bb0-8829-466f-a28a-bbca3d35be92"})).as_deref(), Some("claude-code-15cd6bb0"));
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "raea-app-check-make"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "`raea hook`'s Stop gate for a `make` job (docs/goal.feature MK36): an agent can't end its turn until `raea goal check --at done` passes"
|
||||
|
||||
[dependencies]
|
||||
serde_json = "1"
|
||||
# brief.ts found as raea finds a project (plain paths on Windows)
|
||||
dunce = "1"
|
||||
# the project's folder (record.rs `up`)
|
||||
raea-core-facts = { path = "../../../core/facts" }
|
||||
# the guard's counts, under the home folder
|
||||
raea-io-home = { path = "../../../io/home" }
|
||||
@@ -0,0 +1,125 @@
|
||||
//! raea-app-check-make: the Stop hook's moment of the loop (docs/goal.feature MK36): an agent working in a project with a
|
||||
//! brief.ts can't end its turn until `raea goal check --at done` passes: every goal the brief holds (or, with none, the
|
||||
//! floor) and every raea file reached from the brief (`registered`). Run by `raea goal check`, a child process, so this
|
||||
//! crate carries none of the rules. A session blocked three times with the same open items goes through: it's going in
|
||||
//! circles, and the person is better told than the agent looped.
|
||||
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// How many times the same open items may block one session before the stop goes through.
|
||||
pub const SAME_BLOCKS: u32 = 3;
|
||||
|
||||
/// The project's brief.ts, at or above `cwd` inside its raea project: every brief is held, none is an outlier.
|
||||
pub fn brief_with_job(cwd: &Path) -> Option<PathBuf> {
|
||||
let project = raea_core_facts::record::up(cwd, ".raea/project");
|
||||
for d in dunce::canonicalize(cwd).ok()?.ancestors() {
|
||||
let p = d.join("brief.ts");
|
||||
if p.is_file() {
|
||||
return Some(p);
|
||||
}
|
||||
if project.as_deref() == Some(d) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn hash(parts: &[&str]) -> u64 {
|
||||
let mut h = DefaultHasher::new();
|
||||
parts.hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// Counts this session's blocks on the same open items in `guard` ("<items hash> <count>"); true while it may block.
|
||||
pub fn may_block(guard: &Path, items: &str) -> bool {
|
||||
let key = hash(&[items]).to_string();
|
||||
let count = std::fs::read_to_string(guard).ok().and_then(|t| {
|
||||
let (k, n) = t.trim().split_once(' ')?;
|
||||
(k == key).then(|| n.parse::<u32>().ok()).flatten()
|
||||
});
|
||||
let next = count.unwrap_or(0) + 1;
|
||||
let _ = std::fs::create_dir_all(guard.parent().unwrap_or(Path::new(".")));
|
||||
let _ = std::fs::write(guard, format!("{key} {next}"));
|
||||
next <= SAME_BLOCKS
|
||||
}
|
||||
|
||||
/// What the agent is told when its turn may not end, or None to let it end: no job here, the job passes, the runner
|
||||
/// didn't run (never block on raea's own failure), or the same items have blocked it three times already.
|
||||
pub fn stop(v: &Value) -> Option<String> {
|
||||
let cwd = PathBuf::from(v["cwd"].as_str()?);
|
||||
let brief = brief_with_job(&cwd)?;
|
||||
let exe = std::env::current_exe().ok()?;
|
||||
let out = std::process::Command::new(exe).args(["check", "--at", "done", "--json"]).current_dir(brief.parent()?).env("RAEA_RECORD", "off").output().ok()?;
|
||||
let r: Value = serde_json::from_slice(&out.stdout).ok()?;
|
||||
let home = raea_io_home::user_home()?;
|
||||
let session = v["session_id"].as_str().unwrap_or("");
|
||||
let guard = home.join(".raea/hooks/goal").join(format!("{:x}", hash(&[session, &brief.display().to_string()])));
|
||||
if r["passed"] == true {
|
||||
let _ = std::fs::remove_file(&guard);
|
||||
return None;
|
||||
}
|
||||
let items = open_items(&r);
|
||||
if !may_block(&guard, &items) {
|
||||
return None;
|
||||
}
|
||||
let goals: Vec<String> = r["goals"].as_array().into_iter().flatten().filter(|g| g["passed"] != true).filter_map(|g| g["name"].as_str().map(String::from)).collect();
|
||||
let open = if goals.is_empty() { String::new() } else { format!("goal {}, ", goals.join(", ")) };
|
||||
Some(format!("Not done ({open}{}): {items}. Fix each in its composition and render it again (its check runs at the render's end): `raea check --at done` lists them with their fixes, and review/goal.json holds them all.", brief.display()))
|
||||
}
|
||||
|
||||
/// The open items, one line each: each error-level finding (its check and file), then each check that broke.
|
||||
pub fn open_items(r: &Value) -> String {
|
||||
let mut items: Vec<String> = r["findings"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|x| x["level"] == "error")
|
||||
.map(|x| format!("{}{}: {}", x["check"].as_str().unwrap_or(""), x["file"].as_str().map(|f| format!(" {f}")).unwrap_or_default(), x["says"].as_str().unwrap_or("")))
|
||||
.collect();
|
||||
for b in r["broke"].as_array().into_iter().flatten() {
|
||||
items.push(format!("{} broke: {}", b["check"].as_str().unwrap_or(""), b["says"].as_str().unwrap_or("")));
|
||||
}
|
||||
items.join("; ")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn tmp(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("raea-goal-gate-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(d.join("compositions")).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_brief_is_held_with_or_without_a_goal() {
|
||||
let d = tmp("job");
|
||||
assert_eq!(brief_with_job(&d.join("compositions")), None, "no brief, nothing held");
|
||||
std::fs::write(d.join("brief.ts"), "export default brief({ title: \"x\" })").unwrap();
|
||||
assert_eq!(brief_with_job(&d.join("compositions")).map(|p| p.file_name().unwrap().to_owned()), Some("brief.ts".into()), "a brief without a goal is held to the floor and registered");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_open_items_block_three_times_then_go_through() {
|
||||
let g = tmp("guard").join("g");
|
||||
assert!(may_block(&g, "a") && may_block(&g, "a") && may_block(&g, "a"));
|
||||
assert!(!may_block(&g, "a"), "a fourth stop on the same items goes through");
|
||||
assert!(may_block(&g, "a; b"), "new items start the count again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_items_list_each_error_then_each_broken_check() {
|
||||
let r = json!({"findings": [
|
||||
{"check": "deliverables", "level": "error", "file": null, "says": "missing: out/kit/lineup.png"},
|
||||
{"check": "cta", "level": "error", "file": "out/cuts/a_9x16.mp4", "says": "no CTA in its last 8 s"},
|
||||
{"check": "place", "level": "warn", "file": "out/cuts/a_9x16.mp4", "says": "a warning holds nothing"}],
|
||||
"broke": [{"check": "mine", "says": "x is undefined"}]});
|
||||
assert_eq!(open_items(&r), "deliverables: missing: out/kit/lineup.png; cta out/cuts/a_9x16.mp4: no CTA in its last 8 s; mine broke: x is undefined");
|
||||
}
|
||||
}
|
||||
+16
-26
@@ -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: nothing (docs/check.feature: a render checks its own output at its end). As a turn ends: `raea check
|
||||
//! --at done` on the brief's goals (apps/check/make), which reads each deliverable's kept check. 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; what was sent goes back in the shape each one reads.
|
||||
use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -113,17 +114,6 @@ pub fn steer(files: &[String]) -> String {
|
||||
format!("raea: the raea app is installed here, so show this in it, not the Mac's viewer: `raea show {list}` (several stills make a storyboard; add --ask \"what you want from the person\"; inside the raea app, feed_post does the same). It brings the app's window up on it as an item the person can answer, and their answer comes to the inbox file it prints. If the Mac's viewer really is what's wanted (the person asked for it, or raea show can't), run the same command again and it goes through.")
|
||||
}
|
||||
|
||||
/// The files a tool call saved: `file_path` or `path` (Claude Code, Kimi Code, Gemini CLI), or the files an apply_patch
|
||||
/// adds or updates (Codex).
|
||||
fn saved(v: &Value) -> Vec<String> {
|
||||
let i = &v["tool_input"];
|
||||
if let Some(p) = i["file_path"].as_str().or(i["path"].as_str()).or(i["absolute_path"].as_str()) {
|
||||
return vec![p.to_string()];
|
||||
}
|
||||
let patch = i["command"].as_str().or(i["input"].as_str()).unwrap_or("");
|
||||
patch.lines().filter_map(|l| ["*** Add File: ", "*** Update File: "].iter().find_map(|head| l.strip_prefix(head))).map(str::trim).map(String::from).collect()
|
||||
}
|
||||
|
||||
/// Findings for the agent in the shape its harness reads after a tool: Gemini CLI's AfterTool context, Kimi Code's
|
||||
/// plain stdout, Claude Code's and Codex's PostToolUse context.
|
||||
fn after(agent: &str, text: &str) -> String {
|
||||
@@ -148,9 +138,17 @@ pub fn hook(args: &[String]) -> R<String> {
|
||||
let event = v["hook_event_name"].as_str().unwrap_or("");
|
||||
// what the person sent from the raea app since the last look (inbox.rs): handed over after any tool, and a turn about
|
||||
// to end goes on to take it up
|
||||
let sent = if matches!(event, "PostToolUse" | "AfterTool" | "Stop") { crate::inbox::told(agent, &v) } else { None };
|
||||
let sent = if matches!(event, "PostToolUse" | "AfterTool" | "Stop" | "SessionStart" | "UserPromptSubmit") { crate::inbox::told(agent, &v) } else { None };
|
||||
// a session starting again, or the person writing to it in its terminal: what they sent from raea while it was
|
||||
// closed or idle goes in as context first (Claude Code's and Codex's SessionStart and UserPromptSubmit read
|
||||
// hookSpecificOutput.additionalContext)
|
||||
if matches!(event, "SessionStart" | "UserPromptSubmit") {
|
||||
return Ok(sent.map(|t| json!({"hookSpecificOutput": {"hookEventName": event, "additionalContext": t}}).to_string()).unwrap_or_default());
|
||||
}
|
||||
if event == "Stop" {
|
||||
return Ok(sent.map(|s| json!({"decision": "block", "reason": s}).to_string()).unwrap_or_default());
|
||||
// what the person sent, and a brief whose goals don't pass at done (docs/goal.feature MK36): either keeps the turn going
|
||||
let reasons: Vec<String> = [sent, raea_app_check_make::stop(&v)].into_iter().flatten().collect();
|
||||
return Ok(if reasons.is_empty() { String::new() } else { json!({"decision": "block", "reason": reasons.join("\n\n")}).to_string() });
|
||||
}
|
||||
let after_tool = matches!(event, "PostToolUse" | "AfterTool");
|
||||
if let Some(cmd) = shell_command(&v).filter(|_| !after_tool) {
|
||||
@@ -163,14 +161,8 @@ pub fn hook(args: &[String]) -> R<String> {
|
||||
}
|
||||
return Ok(String::new());
|
||||
}
|
||||
let mut found = Vec::new();
|
||||
for path in saved(&v).iter().filter(|p| p.ends_with(".tsx") && std::fs::read_to_string(p).is_ok_and(|t| t.contains("registerRoot"))) {
|
||||
let (report, _) = crate::quick::quick(std::slice::from_ref(path), Vec::new())?;
|
||||
found.extend(report.lines().skip(1).filter(|l| !l.starts_with("ok ")).map(String::from));
|
||||
}
|
||||
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");
|
||||
Ok(if text.is_empty() { String::new() } else { after(agent, &text) })
|
||||
// no check after a save (docs/check.feature CK1): a render checks its own output at its end, once
|
||||
Ok(sent.map(|t| after(agent, &t)).unwrap_or_default())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -196,8 +188,6 @@ mod tests {
|
||||
assert_eq!(agent_of(&json!({"hook_event_name": "PreToolUse", "tool_name": "Bash"})), "claude");
|
||||
assert_eq!(shell_command(&json!({"tool_name": "shell_command", "tool_input": {"command": "open a.png"}})), Some("open a.png"));
|
||||
assert_eq!(shell_command(&json!({"tool_name": "apply_patch", "tool_input": {"command": "*** Begin Patch\n"}})), None);
|
||||
assert_eq!(saved(&json!({"tool_input": {"command": "*** Begin Patch\n*** Update File: a/E.tsx\n@@\n*** Add File: b.ts\n"}})), ["a/E.tsx", "b.ts"]);
|
||||
assert_eq!(saved(&json!({"tool_input": {"path": "E.tsx"}})), ["E.tsx"]);
|
||||
assert_eq!(after("kimi", "x"), "x");
|
||||
assert!(after("gemini", "x").contains("AfterTool") && after("codex", "x").contains("PostToolUse"));
|
||||
assert!(steer(&["a b.png".into()]).contains("`raea show \"a b.png\"`"));
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! `raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--things T.json] [--shape 9:16]
|
||||
//! `raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 9:16]
|
||||
//! [--platform tiktok|reels|shorts] [-o check.json]`: the floor's measurable lines on an export (docs/craft-system.md, I; sdk/guides/craft/floor.md).
|
||||
//! Each issue is ranked P0 (breaks the piece) to P3 (polish), with where it is and what to do. Rules on the file alone:
|
||||
//! loudness and true peak, a steady sound that stops dead (a source run out, a cut with no fade), stretches where nothing
|
||||
@@ -28,7 +28,6 @@ use raea_app_check_text::*;
|
||||
use raea_app_check_cause as cause;
|
||||
/// a video read through FFmpeg, or raea's own decoders where it isn't installed
|
||||
use raea_app_check_read::{self as read, Probe};
|
||||
pub mod quick;
|
||||
pub mod hook;
|
||||
pub use raea_app_check_inbox as inbox;
|
||||
#[cfg(test)]
|
||||
@@ -66,7 +65,7 @@ fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
|
||||
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
|
||||
}
|
||||
|
||||
pub const USAGE: &str = "raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--things T.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit, and with --things what `raea fingerprint things --json` found: a thing floating or passing through another, the camera lurching mid-move, an empty frame; its findings errors, warns and notes)";
|
||||
pub const USAGE: &str = "raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit; its findings errors, warns and notes)";
|
||||
|
||||
/// A rule from the person's taste: a form raea can measure, its value, and the taste line it stands for.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -116,7 +115,7 @@ fn taste_text(rules: &[Taste], runs: &[Run], w: f64, h: f64, issues: &mut Vec<Is
|
||||
}
|
||||
|
||||
/// the flags `raea check` takes, each with a value
|
||||
const TAKES: [&str; 8] = ["--manifest", "--words", "--perception", "--things", "--shape", "--platform", "--taste", "-o"];
|
||||
const TAKES: [&str; 6] = ["--manifest", "--words", "--perception", "--shape", "--platform", "-o"];
|
||||
|
||||
fn run(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {
|
||||
let (video, issues, passed, fps) = measured(args, taste_rules(&tastes))?;
|
||||
@@ -218,7 +217,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) {
|
||||
|
||||
@@ -15,6 +15,16 @@ pub(crate) const MOST: f32 = 4.0;
|
||||
pub(crate) const RUN: usize = 4;
|
||||
pub(crate) const BACK: usize = 4;
|
||||
pub(crate) const BLOTCHY: f64 = 0.009;
|
||||
/// The least blotching an encoder's patches have been measured at (the VideoToolbox exports' 0.012): a score between
|
||||
/// BLOTCHY and this, whose cause can't be told, is a warning, never an error (12-05: a 3D shot rendered at master
|
||||
/// quality read 0.010, from its shadows' own dithered edge, and was an error whose fix, master quality, it already had)
|
||||
pub(crate) const BLOTCHED: f64 = 0.012;
|
||||
|
||||
/// How a finding whose cause can't be told stands: an error when more than a fifth of the samples blotch and the worst
|
||||
/// is past BLOTCHED, else a warning
|
||||
pub(crate) fn untold_level(share: f64, worst: f64) -> u8 {
|
||||
if share > 0.2 && worst >= BLOTCHED { 1 } else { 2 }
|
||||
}
|
||||
|
||||
pub(crate) fn blotch_score(y: &[u8], w: usize, h: usize) -> Option<f64> {
|
||||
let (bw, bh) = (w / 8, h / 8);
|
||||
@@ -190,8 +200,8 @@ pub(crate) fn blotching_from(video: &str, probe: &Probe, scores: &[Option<f64>],
|
||||
let own = if a.0.before > 0 { format!("; {} of the samples show the footage's own too, which stays", a.0.before) } else { String::new() };
|
||||
(if a.0.worse as f64 / a.0.of.max(1) as f64 > 0.2 { 1 } else { 2 }, first.or(Some(at)), format!("the encode added blocky patches in dark areas: {} of {} samples are blotchier than the composition draws them unencoded; render with --quality master, which gives the darks the bits they need{own}", a.0.worse, a.0.of))
|
||||
}
|
||||
Some(Err(why)) => (if share > 0.2 { 1 } else { 2 }, Some(at), format!("{found}; whether the encode made them or the picture holds them couldn't be told ({why}): render with --quality master if the encode starved the darks")),
|
||||
None => (if share > 0.2 { 1 } else { 2 }, Some(at), format!("{found}: the encode starved the near-blacks, or the footage holds them; render with --quality master, and check a render made in a raea project to tell which")),
|
||||
Some(Err(why)) => (untold_level(share, worst), Some(at), format!("{found}; whether the encode made them or the picture holds them couldn't be told ({why}): render with --quality master if the encode starved the darks")),
|
||||
None => (untold_level(share, worst), Some(at), format!("{found}: the encode starved the near-blacks, or the footage holds them; render with --quality master, and check a render made in a raea project to tell which")),
|
||||
};
|
||||
issues.push(Issue { rule: "blotching", p, at, says });
|
||||
} else if seen > 0 {
|
||||
@@ -199,26 +209,29 @@ pub(crate) fn blotching_from(video: &str, probe: &Probe, scores: &[Option<f64>],
|
||||
}
|
||||
}
|
||||
|
||||
/// Caption contrast: at each text's middle frame, the pixels behind it against its colour, at least 3:1. The pixels
|
||||
/// Caption contrast: at each text's middle frame, the pixels behind it where it is on that frame against its colour, at
|
||||
/// least 3:1. The pixels
|
||||
/// behind are the half of the box least like the text.
|
||||
pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe, issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
|
||||
let (sx, sy) = (probe.w / w, probe.h / h);
|
||||
let mut low = 0;
|
||||
let mut measured = 0;
|
||||
for r in runs.iter().filter(|r| r.size >= 20.0).take(80) {
|
||||
let [x, y, bw, bh] = r.box_;
|
||||
let (t, [x, y, bw, bh]) = r.middle(probe.fps);
|
||||
let crop = [(x * sx).max(0.0) as u32, (y * sy).max(0.0) as u32, (bw * sx) as u32, (bh * sy) as u32];
|
||||
if crop[0] + crop[2] > probe.w as u32 || crop[1] + crop[3] > probe.h as u32 {
|
||||
continue;
|
||||
}
|
||||
let t = (r.from + r.to) / 2.0;
|
||||
// the same measure `raea world` joins to a text from its render (raea-sys-measure, DR2)
|
||||
let ratio = if crate::read::native() { crate::read::contrast(video, t, crop, &r.color) } else { raea_sys_measure::contrast(std::path::Path::new(video), t, crop, &r.color) };
|
||||
let Some(ratio) = ratio else { continue };
|
||||
// each colour its words are drawn in (an accent word's beside the line's), held to the lowest
|
||||
let measure = |color: &str| 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 worst = r.middle_inks().into_iter().filter_map(|c| measure(c).map(|v| (v, c))).min_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let Some((ratio, color)) = worst else { continue };
|
||||
let word = if color == r.middle_color() { String::new() } else { format!(" (its words in {color})") };
|
||||
measured += 1;
|
||||
if ratio < 3.0 {
|
||||
low += 1;
|
||||
issues.push(Issue { rule: "contrast", p: 1, at: Some(t), says: format!("{} is {ratio:.1}:1 against what's behind it; make it at least 3:1 (a band, a shadow for separation, or another colour)", quote(&r.text)) });
|
||||
issues.push(Issue { rule: "contrast", p: 1, at: Some(t), says: format!("{}{word} is {:.2}:1 against what's behind it; make it at least 3:1 (a band, a shadow for separation, or another colour)", quote(&r.text), (ratio * 100.0).floor() / 100.0) });
|
||||
}
|
||||
}
|
||||
if measured > 0 && low == 0 {
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
//! `raea check EDIT.tsx --quick` (docs/skills.feature SK10). The quick check renders three stills of a composition (a
|
||||
//! quarter in, the middle, the last frame, of the length frame 0's render reports) with their manifest, and runs the text rules
|
||||
//! and the person's text taste on it: clipped and cramped text, safe areas, sizes. Every agent's after-save hook runs
|
||||
//! it (hook.rs): after a .tsx that registers a root is saved, its findings go back to the agent; a clean check says
|
||||
//! nothing.
|
||||
use super::*;
|
||||
use std::path::Path;
|
||||
|
||||
/// The stills' frames: a quarter in, the middle and the last of the length a render reports (render.json's `length`,
|
||||
/// the composition's own however it's written; #86 read its source's `durationInFrames={N}` and took 90 for a name).
|
||||
fn samples(m: &Value) -> Option<[u64; 3]> {
|
||||
let n = m["length"].as_u64()?.max(1);
|
||||
Some([n / 4, n / 2, n - 1])
|
||||
}
|
||||
|
||||
/// `raea check EDIT.tsx --quick [--shape S] [--platform P] [-o check.json]`: (report, P0 or P1 found). `tastes` are the
|
||||
/// person's, evaluated by the raea CLI when --taste names them.
|
||||
pub fn quick(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {
|
||||
let file = args.iter().find(|a| a.ends_with(".tsx")).ok_or("raea check --quick takes a composition: EDIT.tsx")?;
|
||||
let tmp = std::env::temp_dir().join(format!("raea-quick-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?;
|
||||
let manifest = tmp.join("render.json");
|
||||
let me = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
// the stills are part of this check, which keeps the one entry in the project's record (DR3)
|
||||
let render = |at: &str| std::process::Command::new(&me).arg("render").arg(file).args(["--at", at, "-o"]).arg(format!("{}/", tmp.display())).arg("--manifest").arg(&manifest).env("RAEA_RECORD", "off").output().map_err(|e| e.to_string());
|
||||
// frame 0 first, for the length (its manifest's), then the three stills
|
||||
let mut out = render("0")?;
|
||||
let at = std::fs::read_to_string(&manifest).ok().and_then(|t| samples(&serde_json::from_str(&t).ok()?));
|
||||
if let Some(at) = at {
|
||||
let _ = std::fs::remove_file(&manifest);
|
||||
out = render(&at.map(|f| f.to_string()).join(","))?;
|
||||
}
|
||||
// rendered when its manifest was written: a render whose stills clip exits 1 (DR3), and those findings are read here
|
||||
let result = if let (Some(at), true) = (at, manifest.is_file()) {
|
||||
on_manifest(file, &manifest, args, tastes, at)
|
||||
} else {
|
||||
// a render that fails is the finding: the agent sees why
|
||||
let (err, out) = (String::from_utf8_lossy(&out.stderr), String::from_utf8_lossy(&out.stdout));
|
||||
let why: Vec<&str> = err.lines().chain(out.lines()).filter(|l| l.contains("REFUSED") || l.contains("rror")).collect();
|
||||
let f = raea_core_facts::Finding::new("render", raea_core_facts::Level::Error, why.join("\n"), "raea check --quick");
|
||||
Ok((format!("raea check {file}: it doesn't render\n{}\nraea check: {}", f.line(), raea_core_facts::finding::count(&[f])), true))
|
||||
};
|
||||
let _ = std::fs::remove_dir_all(&tmp);
|
||||
result
|
||||
}
|
||||
|
||||
/// `raea check --quick`'s half (docs/skills.feature SK10): the text rules and the person's text taste on the manifest
|
||||
/// of a few stills (`raea render EDIT.tsx --at ... --manifest`), no video. What it can't see (contrast, freezes,
|
||||
/// sound, blotching) waits for the full check on the export.
|
||||
fn on_manifest(file: &str, manifest: &Path, args: &[String], tastes: Vec<raea_core_brief::Taste>, [a, b, c]: [u64; 3]) -> R<(String, bool)> {
|
||||
let at = manifest.display();
|
||||
let m: Value = serde_json::from_str(&std::fs::read_to_string(manifest).map_err(|e| format!("{at}: {e}"))?).map_err(|e| format!("{at}: {e}"))?;
|
||||
let (mut issues, mut passed) = (Vec::new(), vec![format!("looked at frames {a}, {b} and {c} of {}", c + 1)]);
|
||||
let runs = text_runs(&m);
|
||||
let (w, h) = (m["width"].as_f64().unwrap_or(1080.0), m["height"].as_f64().unwrap_or(1920.0));
|
||||
text_rules(&runs, None, w, h, flag(args, "--shape"), flag(args, "--platform"), &mut issues, &mut passed);
|
||||
taste_text(&taste_rules(&tastes), &runs, w, h, &mut issues, &mut passed);
|
||||
// and what the render of the stills found (the 3D's clipping, DR3)
|
||||
let more = serde_json::from_value(m["findings"].clone()).unwrap_or_default();
|
||||
report(file, issues, more, passed, flag(args, "-o"), m["fps"].as_f64().unwrap_or(30.0))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
/// the length is the render's, so a `durationInFrames={DUR}` (#86: 300 frames, read as 90) is sampled to its end
|
||||
#[test]
|
||||
fn frames_come_from_the_render() {
|
||||
assert_eq!(super::samples(&json!({"length": 240})), Some([60, 120, 239]));
|
||||
assert_eq!(super::samples(&json!({"length": 300})), Some([75, 150, 299]));
|
||||
assert_eq!(super::samples(&json!({"length": 1})), Some([0, 0, 0]));
|
||||
// a render that reported no length: no stills to look at, so the frame-0 render's failure is the finding
|
||||
assert_eq!(super::samples(&json!({"width": 640})), None);
|
||||
}
|
||||
}
|
||||
+26
-12
@@ -22,7 +22,7 @@ fn a_placeholder_brand_kit_is_flagged() {
|
||||
brand_kit(&["", video.to_str().unwrap()], &mut issues, &mut passed);
|
||||
(issues.iter().map(|i| i.p).collect::<Vec<_>>(), passed.len())
|
||||
};
|
||||
assert_eq!(rules(Some(r#"{"domain":"acme.test","source":{"thin":["no font-family in its CSS"]}}"#)), (vec![1], 0));
|
||||
assert_eq!(rules(Some(r#"{"domain":"acme.test","source":{"thin":["no font-family in its CSS"]}}"#)), (vec![2], 0));
|
||||
assert_eq!(rules(Some(r#"{"domain":"acme.test","source":{"thin":["x"],"by_hand":{"palette.accent":"hero button"}}}"#)), (vec![], 1));
|
||||
assert_eq!(rules(Some(r#"{"domain":"acme.test","source":{"thin":[]}}"#)), (vec![], 1));
|
||||
assert_eq!(rules(None), (vec![2], 0));
|
||||
@@ -51,6 +51,10 @@ fn flat_dark_is_clean_and_stepped_dark_is_blotchy() {
|
||||
(20.0 - (x * x + y * y).sqrt() / 24.0).max(6.0) as u8
|
||||
}).collect();
|
||||
assert!(blotch_score(&rings, w, h).unwrap() < BLOTCHY / 2.0);
|
||||
// a cause that can't be told: an error only past an encoder's measured blotching, on more than a fifth of samples
|
||||
assert_eq!(untold_level(1.0, 0.010), 2);
|
||||
assert_eq!(untold_level(1.0, 0.09), 1);
|
||||
assert_eq!(untold_level(0.1, 0.09), 2);
|
||||
assert_eq!(x264_crf(b"..\x05x264 - core 165 r3222 - H.264/MPEG-4 AVC codec - options: cabac=1 rc=crf mbtree=1 crf=12.0 qcomp=0.60"), Some(12.0));
|
||||
assert_eq!(x264_crf(b"Lavf61 VideoToolbox"), None);
|
||||
}
|
||||
@@ -67,8 +71,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![], inks: 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![], inks: 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();
|
||||
@@ -185,15 +189,14 @@ fn a_bed_close_under_the_voice_and_a_loud_stretch_without_it_are_found() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_floor_and_placement_state_the_zones_check_measures() {
|
||||
// zones() is where the numbers live; floor.md and placement.md say them in words, held to it here
|
||||
fn placement_states_the_zones_check_measures() {
|
||||
// zones() is where the numbers live; placement.md says them in words, held to it here
|
||||
let words = |t: &str| t.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
let floor = words(include_str!("../../../sdk/guides/craft/floor.md"));
|
||||
let placement = words(include_str!("../../../sdk/guides/craft/motion/placement.md"));
|
||||
let n = |v: f64| format!("{v:.0}");
|
||||
let [t, r, b, l] = zones(1080.0, 1920.0, Some("9:16"), None);
|
||||
let said = [
|
||||
format!("keep the top {} px, the bottom {}, the right {} and the left {} clear", n(t), n(b), n(r), n(l)),
|
||||
format!("that is top {}, bottom {}, right {} and left {} px at 1080 wide", n(t), n(b), n(r), n(l)),
|
||||
["tiktok", "reels", "shorts"].map(|p| {
|
||||
let [t, r, b, _] = zones(1080.0, 1920.0, Some("9:16"), Some(p));
|
||||
let name = match p { "tiktok" => "TikTok", "reels" => "Reels", _ => "Shorts" };
|
||||
@@ -204,10 +207,8 @@ fn the_floor_and_placement_state_the_zones_check_measures() {
|
||||
{ let [t, r, b, l] = zones(1920.0, 1080.0, Some("16:9"), None); assert!(t == b && r == l); format!("16:9 top and bottom {}, sides {}", n(t), n(r)) },
|
||||
];
|
||||
for s in &said {
|
||||
assert!(floor.contains(s.as_str()), "floor.md doesn't say {s:?}");
|
||||
assert!(placement.contains(s.as_str()), "placement.md doesn't say {s:?}");
|
||||
}
|
||||
let s = format!("that is top {}, bottom {}, right {} and left {} px at 1080 wide", n(t), n(b), n(r), n(l));
|
||||
assert!(placement.contains(&s), "placement.md doesn't say {s:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -267,7 +268,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![], inks: 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 +336,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![], inks: 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![]);
|
||||
@@ -420,3 +421,16 @@ fn things_found_are_findings_and_an_unknown_rule_is_not() {
|
||||
let _ = std::fs::remove_file(&p);
|
||||
assert_eq!(passed.len(), 1, "nothing found is a pass");
|
||||
}
|
||||
|
||||
/// #236: a text that moves is read where it is on its middle frame, not where it ends.
|
||||
#[test]
|
||||
fn a_moving_text_is_read_where_it_is() {
|
||||
let ink = |f: usize| [56.7 + 4.0 * f as f64, 1000.0, 26.7, 40.0];
|
||||
let run = Run { text: "E".into(), from: 0.0, to: 8.0, box_: [996.0, 1000.0, 60.0, 40.0], boxes: (0..240).map(ink).collect(), colors: vec![], inks: 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]));
|
||||
}
|
||||
|
||||
+107
-7
@@ -43,13 +43,57 @@ 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>,
|
||||
/// the colours its words are drawn in on each of those frames, beside `colors`, when any differs from the line's (the
|
||||
/// manifest's `inks`: a caption's accent word); empty when every word is in the line's colour
|
||||
pub inks: Vec<Vec<String>>,
|
||||
/// its colour on its last frame
|
||||
pub color: String,
|
||||
pub size: f64,
|
||||
}
|
||||
|
||||
impl Run {
|
||||
/// The frame midway through those that show its whole text, and its box on that frame: `box_` (the last frame's)
|
||||
/// moved back by how far its letters travel from there to where they end. A text that moves was read at its last
|
||||
/// place on its middle frame (#236).
|
||||
pub fn middle(&self, fps: f64) -> (f64, [f64; 4]) {
|
||||
let n = self.boxes.len();
|
||||
let (Some(last), true) = (self.boxes.last(), fps > 0.0 && n > 1) else { return ((self.from + self.to) / 2.0, self.box_) };
|
||||
let (at, [x, y, w, h]) = (self.boxes[n / 2], self.box_);
|
||||
(self.to - (n - n / 2) as f64 / fps, [x + at[0] - last[0], y + at[1] - last[1], w, h])
|
||||
}
|
||||
|
||||
/// 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,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every colour its words are drawn in on that frame: the line's, and an accent span's beside it (12-06: a line
|
||||
/// recorded only by its own colour hid a dark word on a dark plate)
|
||||
pub fn middle_inks(&self) -> Vec<&str> {
|
||||
let n = self.boxes.len();
|
||||
let mut all = vec![self.middle_color()];
|
||||
let at = if n > 1 && self.inks.len() == n { self.inks.get(n / 2) } else { self.inks.last() };
|
||||
for i in at.into_iter().flatten() {
|
||||
if !all.contains(&i.as_str()) {
|
||||
all.push(i);
|
||||
}
|
||||
}
|
||||
all
|
||||
}
|
||||
}
|
||||
|
||||
/// The brand kit the cut was styled from (brand/ at or above the manifest's or the video's folder, as render finds
|
||||
/// brand.css): a kit `raea brand` read from a thin fetch that nobody corrected by hand is a placeholder, P1; a brand.css
|
||||
/// with no brand.json beside it wasn't read from the brand at all, P2
|
||||
/// brand.css): a kit `raea brand` read from a thin fetch that nobody corrected by hand is a placeholder, and a brand.css
|
||||
/// with no brand.json beside it wasn't read from the brand at all, both P2: where a kit came from is a note for the person
|
||||
/// at sign-off, not a fault in the cut (12-05, run 39: all four of Body Shop's cuts held an error for a fetch of the
|
||||
/// brand's site that read 40 of its 95 colour and face variables)
|
||||
pub fn brand_kit(near: &[&str], issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for start in near.iter().filter(|p| !p.is_empty()) {
|
||||
@@ -70,7 +114,7 @@ pub fn brand_kit(near: &[&str], issues: &mut Vec<Issue>, passed: &mut Vec<String
|
||||
let thin: Vec<&str> = kit["source"]["thin"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
|
||||
let by_hand = kit["source"]["by_hand"].as_object().is_some_and(|o| !o.is_empty());
|
||||
if !thin.is_empty() && !by_hand {
|
||||
issues.push(Issue { rule: "brand", p: 1, at: None, says: format!("styled from a placeholder kit: raea brand's fetch of {} was thin ({}) and nothing in brand.json's source.by_hand says it was checked; read the live site in a browser and fix the kit (raea guide brand, \"When the fetch was thin\")", kit["domain"].as_str().unwrap_or("the site"), thin.join("; ")) });
|
||||
issues.push(Issue { rule: "brand", p: 2, at: None, says: format!("styled from a placeholder kit: raea brand's fetch of {} was thin ({}) and nothing in brand.json's source.by_hand says it was checked; read the live site in a browser and fix the kit (raea guide brand, \"When the fetch was thin\")", kit["domain"].as_str().unwrap_or("the site"), thin.join("; ")) });
|
||||
} else {
|
||||
passed.push(format!("brand: the cut is styled from {}'s kit{}", kit["domain"].as_str().unwrap_or("the brand"), if by_hand { ", checked by hand" } else { "" }));
|
||||
}
|
||||
@@ -102,18 +146,24 @@ 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(), inks: Vec::new(), color: String::new(), size: 0.0 },
|
||||
};
|
||||
let color = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string();
|
||||
let inks: Vec<String> = x["inks"].as_array().map(|a| a.iter().filter_map(Value::as_str).map(String::from).collect()).unwrap_or_default();
|
||||
if text.len() > r.text.len() {
|
||||
r.boxes.clear();
|
||||
r.colors.clear();
|
||||
r.inks.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.inks.push(inks);
|
||||
}
|
||||
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);
|
||||
}
|
||||
@@ -164,7 +214,11 @@ pub fn face_cover(runs: &[Run], faces: &[(f64, f64, [f64; 4])], issues: &mut Vec
|
||||
}
|
||||
}
|
||||
|
||||
/// the zones where text can't go, as [top, right, bottom, left] at 1080 wide (sdk/guides/craft/floor.md)
|
||||
/// The app's right-hand buttons start this far down the frame (sdk/video/src/zones.ts RAIL): the right zone is under it.
|
||||
/// 12-05: a centred end card at 35% down was an error for the right zone, where no app draws anything.
|
||||
pub const RAIL: f64 = 0.45;
|
||||
|
||||
/// the zones where text can't go, as [top, right, bottom, left] at 1080 wide (sdk/guides/craft/motion/placement.md)
|
||||
pub fn zones(w: f64, h: f64, shape: Option<&str>, platform: Option<&str>) -> [f64; 4] {
|
||||
let r = w / h;
|
||||
let shape = shape.unwrap_or(if r < 0.7 { "9:16" } else if r < 0.9 { "4:5" } else if r < 1.2 { "1:1" } else { "16:9" });
|
||||
@@ -196,7 +250,8 @@ pub fn text_rules(runs: &[Run], heard: Option<&[Word]>, w: f64, h: f64, shape: O
|
||||
let [x, y, bw, bh] = r.box_;
|
||||
let q = quote(&r.text);
|
||||
let off = |&[x, y, bw, bh]: &[f64; 4]| x < -1.0 || y < -1.0 || x + bw > w + 1.0 || y + bh > h + 1.0;
|
||||
let zoned = |&[x, y, bw, bh]: &[f64; 4]| y < zt || x + bw > w - zr || y + bh > h - zb || x < zl;
|
||||
// the right zone is the app's buttons, which start RAIL down the frame: above them the right edge is clear
|
||||
let zoned = |&[x, y, bw, bh]: &[f64; 4]| y < zt || (x + bw > w - zr && y + bh > RAIL * h) || y + bh > h - zb || x < zl;
|
||||
if r.boxes.iter().all(off) {
|
||||
clipped += 1;
|
||||
issues.push(Issue { rule: "clipped", p: 0, at: Some(r.from), says: format!("{q} runs off the frame (box {x:.0},{y:.0} {bw:.0}x{bh:.0} in {w:.0}x{h:.0}); fit it or break the line") });
|
||||
@@ -282,3 +337,48 @@ 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 {
|
||||
/// The right zone is the app's buttons, from RAIL down: a centred end card above them is clear (12-05, an end card 35%
|
||||
/// down was an error); the same card over the buttons isn't.
|
||||
#[test]
|
||||
fn the_right_zone_starts_where_the_apps_buttons_do() {
|
||||
let right = |y: f64| {
|
||||
let m = serde_json::json!({"fps": 1.0, "frames": [{"frame": 0, "text": [{"text": "THE BODY SHOP", "box": [134.0, y, 812.0, 112.0]}]}]});
|
||||
let (mut issues, mut passed) = (vec![], vec![]);
|
||||
text_rules(&text_runs(&m), None, 1080.0, 1920.0, None, None, &mut issues, &mut passed);
|
||||
issues.into_iter().filter(|i| i.rule == "safe-area").map(|i| i.says).collect::<String>()
|
||||
};
|
||||
assert_eq!(right(682.0), "");
|
||||
assert!(right(1290.0).contains("at the right (keep 140 px clear)"), "{}", right(1290.0));
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_with_an_accent_word_is_measured_in_both_colours() {
|
||||
// a white caption with one word in dark red: the manifest's line colour alone hid the red word
|
||||
let m = json!({"fps": 10.0, "frames": (0..4).map(|f| json!({"frame": f, "text": [
|
||||
{"text": "Stay out longer.", "box": [100, 1400, 880, 90], "size": 84, "color": "rgb(255, 255, 255)", "inks": ["rgb(255, 255, 255)", "rgb(120, 0, 0)"]}
|
||||
]})).collect::<Vec<_>>()});
|
||||
let runs = text_runs(&m);
|
||||
assert_eq!(runs[0].middle_inks(), vec!["rgb(255, 255, 255)", "rgb(120, 0, 0)"]);
|
||||
// a line drawn in its own colour only has no inks, and is measured in that colour alone
|
||||
let plain = json!({"fps": 10.0, "frames": [{"frame": 0, "text": [{"text": "raea", "box": [0, 0, 10, 10], "size": 40, "color": "rgb(1, 2, 3)"}]}]});
|
||||
assert_eq!(text_runs(&plain)[0].middle_inks(), vec!["rgb(1, 2, 3)"]);
|
||||
}
|
||||
}
|
||||
+100
-7
@@ -18,10 +18,10 @@ use crate::ts;
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
pub const USAGE: &str = "raea check [PROJECT|EDIT.tsx] [--composition ID] [--only ID] [--taste T] [--render OUT | --no-render] [--json] (every check that applies to each composition, over its frames: raea's floor on its newest render, the person's, the workspace's and the project's taste.ts (each line's check: one of raea's forms or checks by name, or a project's .ts check); what needs a render and has none waits, and says so)";
|
||||
pub const USAGE: &str = "raea check [PROJECT|EDIT.tsx] [--composition ID] [--only ID] [--render OUT | --no-render] [--json] (every check that applies to each composition, over its frames: raea's floor on its newest render, the person's, the workspace's and the project's taste.ts (each line's check: one of raea's forms or checks by name, or a project's .ts check); what needs a render and has none waits, and says so)";
|
||||
|
||||
/// The flags raea check takes with a value (its own, and the floor's on a video).
|
||||
const TAKES: [&str; 10] = ["--composition", "--only", "--taste", "--render", "--manifest", "--words", "--perception", "--shape", "--platform", "-o"];
|
||||
const TAKES: [&str; 9] = ["--composition", "--only", "--render", "--manifest", "--words", "--perception", "--shape", "--platform", "-o"];
|
||||
|
||||
/// What the CLI lends `raea check`: its TS evaluator and headless run, and the taste kinds a mode needs (as `raea
|
||||
/// context` reads the person's taste).
|
||||
@@ -240,6 +240,16 @@ fn check_one(tsx: &Path, id: Option<String>, rules: &[Rule], args: &[String], wh
|
||||
None => hows.iter().filter(|(_, h)| matches!(h, How::Named(n) if n.render && n.name != "text-read")).for_each(|(r, _)| needs(&mut waits, r)),
|
||||
}
|
||||
}
|
||||
// traced light held still (raea light steady): with the floor, a composition lit by Solari carries what its newest
|
||||
// hold of each frame found, kept in the project's record; with none yet, it waits for one
|
||||
if floor && traced(tsx) {
|
||||
let held = light_held(tsx, id.as_deref());
|
||||
if held.is_empty() {
|
||||
let c = id.as_ref().map(|i| format!(" --composition {i}")).unwrap_or_default();
|
||||
waits.push(("light-steady".into(), format!("a held frame of its traced light (raea light steady {}{c} --frame N -o DIR)", tsx.display())));
|
||||
}
|
||||
found.extend(held.into_iter().filter(|f| f.level != Level::Note));
|
||||
}
|
||||
// the project's own checks, in one run
|
||||
let mut files: Vec<PathBuf> = Vec::new();
|
||||
let mut plan = Vec::new();
|
||||
@@ -249,10 +259,7 @@ fn check_one(tsx: &Path, id: Option<String>, rules: &[Rule], args: &[String], wh
|
||||
needs(&mut waits, r);
|
||||
continue;
|
||||
}
|
||||
let k = files.iter().position(|f| *f == m.file).unwrap_or_else(|| {
|
||||
files.push(m.file.clone());
|
||||
files.len() - 1
|
||||
});
|
||||
let k = file_index(&mut files, &m.file);
|
||||
let mut on = m.frames.pick(&worlds);
|
||||
if let (true, Some(j)) = (m.render, &join_on_of(&worlds)) {
|
||||
on.retain(|f| j.contains(f));
|
||||
@@ -272,6 +279,55 @@ fn check_one(tsx: &Path, id: Option<String>, rules: &[Rule], args: &[String], wh
|
||||
Ok(Checked { file: tsx.to_path_buf(), id, found: finding::ranked(found), waits, render, shots, fps })
|
||||
}
|
||||
|
||||
/// Whether a composition is lit by traced light: its file, or a .tsx beside it or a folder down, names SolariLighting.
|
||||
fn traced(tsx: &Path) -> bool {
|
||||
let mut files = vec![tsx.to_path_buf()];
|
||||
let tsxs = |d: &Path| -> Vec<PathBuf> { std::fs::read_dir(d).into_iter().flatten().flatten().map(|e| e.path()).collect() };
|
||||
if let Some(dir) = tsx.parent() {
|
||||
files.extend(tsxs(dir).into_iter().flat_map(|p| if p.is_dir() { tsxs(&p) } else { vec![p] }).filter(|p| p.extension().is_some_and(|x| x == "tsx")));
|
||||
}
|
||||
for f in files {
|
||||
if let Ok(text) = std::fs::read_to_string(&f) {
|
||||
if text.contains("SolariLighting") {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The findings of the newest hold of each frame of a composition (`raea light steady`), from its project's record.
|
||||
fn light_held(tsx: &Path, id: Option<&str>) -> Vec<Finding> {
|
||||
let Some(project) = dunce::canonicalize(tsx).ok().and_then(|t| record::up(t.parent()?, ".raea/project")) else { return Vec::new() };
|
||||
let of = record::rel(&project, tsx);
|
||||
let mut newest: std::collections::BTreeMap<i64, Vec<Finding>> = std::collections::BTreeMap::new();
|
||||
for e in record::read(&project) {
|
||||
if e.by != "raea light steady" || e.of != of {
|
||||
continue;
|
||||
}
|
||||
let mut mine = Vec::new();
|
||||
for f in e.findings {
|
||||
let mut about = f.about.iter().map(|a| a.name.as_str());
|
||||
if id.is_none_or(|id| about.any(|n| n == id)) {
|
||||
mine.push(f);
|
||||
}
|
||||
}
|
||||
if let Some(frame) = mine.first().and_then(|f| f.frames) {
|
||||
newest.insert(frame[0], mine);
|
||||
}
|
||||
}
|
||||
newest.into_values().flatten().collect()
|
||||
}
|
||||
|
||||
/// Where `f` is in `files`, added at the end when it isn't yet: the one run's checks, each file once.
|
||||
fn file_index(files: &mut Vec<PathBuf>, f: &Path) -> usize {
|
||||
if let Some(at) = files.iter().position(|x| x == f) {
|
||||
return at;
|
||||
}
|
||||
files.push(f.to_path_buf());
|
||||
files.len() - 1
|
||||
}
|
||||
|
||||
/// Whether `r` runs on the composition `tsx` (`id` where its file registers several) of `project`: a rule a note's ask
|
||||
/// scopes to one (`of`) runs there alone.
|
||||
fn applies(r: &Rule, project: &Path, tsx: &Path, id: Option<&str>) -> bool {
|
||||
@@ -325,6 +381,9 @@ pub fn check(args: &[String], host: &Host) -> R<(String, bool)> {
|
||||
return Err(format!("--only {only}: no rule here has that id"));
|
||||
}
|
||||
}
|
||||
if target.is_file() && target.to_string_lossy().ends_with(".story.ts") {
|
||||
return check_story(&target, &rules, unread, args, host);
|
||||
}
|
||||
let mut all = Vec::new();
|
||||
for (tsx, id) in compositions(&target, args)? {
|
||||
let mine: Vec<Rule> = rules.iter().filter(|r| applies(r, &project, &tsx, id.as_deref())).cloned().collect();
|
||||
@@ -351,7 +410,7 @@ pub fn check(args: &[String], host: &Host) -> R<(String, bool)> {
|
||||
// a note's ask's finding says which ask, as two asks can run one check
|
||||
out.extend(c.found.iter().map(|f| if f.by.starts_with("note ") { format!("{} [{}]", f.line(), f.by) } else { f.line() }));
|
||||
out.extend(c.waits.iter().map(|(r, w)| format!("waits {r}: needs {w}")));
|
||||
// kept in its project's record (DR3), what raea findings and raea next read
|
||||
// kept in its project's record (DR3), what raea findings and raea goal next read
|
||||
if let Some(e) = record::keep("raea check", &c.file, None, &c.found, vec![], &stamp) {
|
||||
out.push(format!("raea check: kept in the project's record as {} (raea findings reads it)", e.id));
|
||||
}
|
||||
@@ -363,6 +422,40 @@ pub fn check(args: &[String], host: &Host) -> R<(String, bool)> {
|
||||
Ok((out.join("\n"), bad))
|
||||
}
|
||||
|
||||
/// `raea check NAME.story.ts` (docs/story.feature ST5a): a story checked before anything is drawn. Every rule whose .ts
|
||||
/// check reads stories (`over: "story"` or `"both"`) runs once with no frames, so only its `after` speaks; the check
|
||||
/// imports the story it holds (raea/story's storyCheck), and the file named says which project and that no composition
|
||||
/// is wanted.
|
||||
fn check_story(file: &Path, rules: &[Rule], unread: Vec<Finding>, args: &[String], host: &Host) -> R<(String, bool)> {
|
||||
let (mut found, mut files, mut plan) = (Vec::new(), Vec::<PathBuf>::new(), Vec::new());
|
||||
for r in rules {
|
||||
let Some(f) = r.file() else { continue };
|
||||
match ts::meta(f, &host.ts) {
|
||||
Ok(m) if m.story => {
|
||||
let k = file_index(&mut files, &m.file);
|
||||
plan.push(ts::Planned { check: k, frames: Vec::new(), values: r.values.clone(), level: r.level, by: r.by.clone() });
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(e) => found.push(Finding::new(&r.id, Level::Error, e, &r.by)),
|
||||
}
|
||||
}
|
||||
if plan.is_empty() {
|
||||
found.push(Finding::new("story", Level::Note, "no check here reads a story: a .ts check over \"story\" or \"both\" (raea/story's storyCheck is one) named in taste.ts", "raea check"));
|
||||
}
|
||||
found.extend(ts::run(&files, &plan, &[], &host.ts)?);
|
||||
let found = finding::ranked(found);
|
||||
let bad = unread.iter().chain(&found).any(|f| f.level == Level::Error);
|
||||
if args.iter().any(|a| a == "--json") {
|
||||
return Ok((serde_json::to_string_pretty(&json!({"unread": unread, "story": file, "findings": found})).unwrap_or_default(), bad));
|
||||
}
|
||||
let mut out: Vec<String> = unread.iter().map(Finding::line).collect();
|
||||
out.push(format!("raea check {} (a story: no frames)", file.display()));
|
||||
out.extend(found.iter().map(Finding::line));
|
||||
let every: Vec<Finding> = unread.into_iter().chain(found).collect();
|
||||
out.push(format!("raea check: {}", finding::count(&every)));
|
||||
Ok((out.join("\n"), bad))
|
||||
}
|
||||
|
||||
/// `raea check ...`: its exit code (1 on an error found, 2 when it couldn't check).
|
||||
pub fn cli(args: &[String], host: &Host) -> i32 {
|
||||
raea_app_check::said(check(args, host), "raea check: ")
|
||||
|
||||
@@ -28,7 +28,7 @@ const LEVELS: f32 = 96.0;
|
||||
const SHARE: f64 = 1e-4;
|
||||
const LEAST: usize = 64;
|
||||
/// The flags of the render the stills repeat (each takes a value, then the bare ones): what it draws and at what size
|
||||
const KEEP: [&str; 9] = ["--composition", "--w", "--h", "--fps", "--frames", "--words", "--perception", "--input", "--stage"];
|
||||
const KEEP: [&str; 12] = ["--composition", "--w", "--h", "--fps", "--frames", "--words", "--perception", "--input", "--stage", "--props", "--scale", "--hold"];
|
||||
const KEEP_BARE: [&str; 2] = ["--clay", "--lite"];
|
||||
const BY: &str = "raea render (frame-pure)";
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ pub fn rendered(args: &[String]) -> i32 {
|
||||
let _ = std::fs::write(&m, v.to_string());
|
||||
}
|
||||
}
|
||||
// a render that is part of another (a review's tiles, a quick check's stills) leaves the entry to that one
|
||||
// a render that is part of another (a review's tiles) leaves the entry to that one
|
||||
let file = args.get(1).filter(|a| !a.starts_with('-') && std::env::var("RAEA_RECORD").as_deref() != Ok("off")).map(PathBuf::from);
|
||||
if let Some(e) = file.and_then(|f| record::keep("raea render", &f, out.as_deref(), &found, excused, &raea_io_trace::utc(SystemTime::now()).1)) {
|
||||
println!("raea render: kept in the project's record as {} (raea findings reads it)", e.id);
|
||||
|
||||
@@ -27,6 +27,8 @@ pub struct Meta {
|
||||
pub render: bool,
|
||||
pub level: Level,
|
||||
pub frames: Frames,
|
||||
/// it runs on a story with no frames (`over: "story" | "both"`): what `raea check NAME.story.ts` runs
|
||||
pub story: bool,
|
||||
}
|
||||
|
||||
/// The declaration of the check `file`'s default export is.
|
||||
@@ -46,7 +48,12 @@ pub fn meta(file: &Path, host: &Host) -> R<Meta> {
|
||||
Some(o) => return Err(format!("{name}: a check's level is error, warn or note, not \"{o}\"")),
|
||||
};
|
||||
let frames = Frames::of(&v["frames"]).map_err(|e| format!("{name}: {e}"))?;
|
||||
Ok(Meta { file: file.to_path_buf(), id, text: s("text").unwrap_or_default(), render, level, frames })
|
||||
let story = match s("over").as_deref() {
|
||||
None | Some("frames") => false,
|
||||
Some("story" | "both") => true,
|
||||
Some(o) => return Err(format!("{name}: a check is over \"frames\", \"story\" or \"both\", not \"{o}\"")),
|
||||
};
|
||||
Ok(Meta { file: file.to_path_buf(), id, text: s("text").unwrap_or_default(), render, level, frames, story })
|
||||
}
|
||||
|
||||
/// One planned run: the check (its index in `files`), its frames, and its rule's values, level (None: the check's
|
||||
|
||||
@@ -35,7 +35,7 @@ pub struct Double {
|
||||
pub problem: Option<f64>,
|
||||
/// clef agrees: past even odds, or past the question's threshold once the person's labels calibrated it
|
||||
pub agrees: Option<bool>,
|
||||
/// its answer's id in raea ask's record, for `raea ask verdict`
|
||||
/// its answer's id in the ask record (~/.raea/ask/answers.jsonl)
|
||||
pub answer: Option<String>,
|
||||
/// why it wasn't asked or still waits
|
||||
pub not_asked: Option<String>,
|
||||
|
||||
@@ -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" }
|
||||
|
||||
@@ -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, for a person to look at; --json prints it as 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),
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -99,13 +99,18 @@ fn shape(expr: &str, out: &Path, meshes: &mut BTreeMap<String, String>) -> R<Val
|
||||
Some(f) => f.clone(),
|
||||
None => {
|
||||
let f = format!("meshes/mesh{k}.glb");
|
||||
// export() empties meshes/ before the parts are walked, so the folder is made here, where a file first needs it
|
||||
let dir = out.join("meshes");
|
||||
if let Err(e) = std::fs::create_dir_all(&dir) {
|
||||
return Err(format!("{}: {e}", dir.display()));
|
||||
}
|
||||
// and as an .obj, which Godot imports as a mesh of its own (a .glb comes in as a scene)
|
||||
let (glb, obj) = (out.join(&f).to_string_lossy().into_owned(), out.join(f.replace(".glb", ".obj")).to_string_lossy().into_owned());
|
||||
match expr.strip_prefix("buffer:") {
|
||||
// a mesh given by its own vertices (a <BufferMesh>, a three.js geometry through raea/r3f): written as it
|
||||
// is, with its normals and texture coordinates, since it needn't be a closed solid
|
||||
Some(b) => {
|
||||
let (t, uv) = raea_core_shape::buffer_tris(b)?;
|
||||
let (t, uv) = raea_core_shape::buffer_tris(&raea_core_shape::buffer_json(b)?)?;
|
||||
raea_core_shape::export_tris(&t, uv.as_deref(), &glb, "glb")?;
|
||||
raea_core_shape::export_tris(&t, uv.as_deref(), &obj, "obj")?;
|
||||
}
|
||||
@@ -312,7 +317,8 @@ mod tests {
|
||||
#[test]
|
||||
fn primitives_cross_as_themselves_and_the_rest_as_a_mesh() {
|
||||
let out = std::env::temp_dir().join(format!("raea-interchange-shape-{}", std::process::id()));
|
||||
std::fs::create_dir_all(out.join("meshes")).unwrap();
|
||||
// no meshes/ beforehand, as export() leaves it: shape() makes it (it once failed every solid in a fresh export)
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
let mut m = BTreeMap::new();
|
||||
assert_eq!(shape("box(1, 2, 3)", &out, &mut m).unwrap(), json!({ "type": "cuboid", "size": [1.0, 2.0, 3.0] }));
|
||||
assert_eq!(shape("sphere(0.5)", &out, &mut m).unwrap()["type"], "sphere");
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
[package]
|
||||
name = "raea-app-judge"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "raea judge: a review's sheets judged by clef-omni on a frozen rubric, the pass decided in code, calibrated against the person's eye before it gates"
|
||||
|
||||
[dependencies]
|
||||
dunce = "1"
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
# what a judge saw, as raea's one Finding (docs/direction.feature DR3)
|
||||
raea-core-facts = { path = "../../core/facts" }
|
||||
serde_json = "1"
|
||||
raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
# the one clef client: the question format and the call, routed to the person's plan first (docs/ask.feature AK1b)
|
||||
raea-core-ask = { path = "../../core/ask" }
|
||||
raea-io-clef = { path = "../../io/clef" }
|
||||
@@ -1,149 +0,0 @@
|
||||
//! 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
|
||||
//! its reading as the eye clef is calibrated against.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::rubric::SCORES;
|
||||
|
||||
pub const BY: [&str; 2] = ["kimi", "claude"];
|
||||
|
||||
/// The judge prompt: the sheets by name, the brief's words, and the JSON to answer.
|
||||
pub fn prompt(dir: &Path, brief: &Value, target: Option<&Path>) -> String {
|
||||
let words = ["look", "logline", "notDoing"].iter().filter_map(|k| brief.get(*k).map(|v| format!("{k}: {}", v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())))).collect::<Vec<_>>().join("; ");
|
||||
let target = target.map(|t| format!(" The target picture, what it must read as, is {}.", t.display())).unwrap_or_default();
|
||||
format!(
|
||||
"You review a 3D scene from images only, as the person who will use it would. You have never seen how it was built and you never will. \
|
||||
Judge what is in the pixels; do not guess at intentions. Only look at images; change no file.\n\n\
|
||||
PART 1, BLIND: open {d}/hero-colour.png first, one frame. In one sentence: what place is this, what time, what era? List five objects you can name. \
|
||||
Is it a photograph or a render, and which three tells decided it?\n\n\
|
||||
PART 2, SCORED. The brief: \"{words}\".{target} This round's sheets: {d}/colour.png and {d}/clay.png, each six tiles, left to right, top to bottom: \
|
||||
hero, front, right, top, iso, low (0.3 m off the floor). Clay is every surface light grey and matte. Open both.\n\n\
|
||||
Score each 0-10 (5 = a believable draft; 7 = a production base an artist would accept; 9 = indistinguishable from real). Halves are allowed.\n\
|
||||
- composition: camera, framing, layout, the position and scale of every major object.\n\
|
||||
- form, judged on CLAY: silhouettes read at a glance; parts have real thickness; nothing blobby, melted or a primitive standing in for a thing; repeated things vary.\n\
|
||||
- assembly, judged on CLAY first: nothing floats, sinks, pokes through or rests on the wrong thing; joints touch; the low tile shows the feet.\n\
|
||||
- materials: every surface reads as its real material, with wear where use puts it; nothing a flat default colour.\n\
|
||||
- light: motivated by the place's own sources; exposure and contrast believable.\n\
|
||||
- detail: close views hold real geometry or texture, not a smooth stand-in; printed matter reads.\n\
|
||||
- world: one coherent real place; nothing off-era or invented beyond the brief.\n\n\
|
||||
Then list the defects, most damaging first: at most 8, each field one short sentence. \"blocking\" means someone using this scene would notice it in the views it will be seen in. \
|
||||
Name exactly what gives it away (not \"the dryer looks fake\" but \"the dryer door is a flat disc with no rim or glass depth\").\n\n\
|
||||
End your answer with only this JSON, nothing after it:\n\
|
||||
{{\"blind\": {{\"place\": \"\", \"objects\": [], \"photo\": \"yes|no\", \"tells\": []}}, \
|
||||
\"scores\": {{\"composition\": 0, \"form\": 0, \"assembly\": 0, \"materials\": 0, \"light\": 0, \"detail\": 0, \"world\": 0}}, \
|
||||
\"defects\": [{{\"tile\": \"\", \"where\": \"\", \"wrong\": \"\", \"real\": \"\", \"fix\": \"\", \"level\": \"blocking|detail\"}}], \
|
||||
\"show_as_is\": \"\"}}",
|
||||
d = dir.display()
|
||||
)
|
||||
}
|
||||
|
||||
/// The last JSON object in the text that has scores (an agent may think aloud, or draft the JSON twice).
|
||||
pub fn last_verdict(text: &str) -> Option<Value> {
|
||||
let starts: Vec<usize> = text.match_indices('{').map(|(i, _)| i).collect();
|
||||
for &s in starts.iter().rev() {
|
||||
let mut de = serde_json::Deserializer::from_str(&text[s..]).into_iter::<Value>();
|
||||
if let Some(Ok(v)) = de.next()
|
||||
&& v.get("scores").is_some_and(Value::is_object)
|
||||
{
|
||||
return Some(v);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The verdict read into the judge's own shape: scores (0-10, the seven categories), defects (present, level, named
|
||||
/// by what is wrong), the blind read's photo (1 a photo, 0 a render) and the agent's own words.
|
||||
pub fn read(v: &Value) -> (Map<String, Value>, Vec<Value>, Value) {
|
||||
let mut scores = Map::new();
|
||||
for (k, _, _) in SCORES {
|
||||
if let Some(x) = v["scores"][k].as_f64().filter(|x| (0.0..=10.0).contains(x)) {
|
||||
scores.insert(k.into(), json!(x));
|
||||
}
|
||||
}
|
||||
let defects = v["defects"].as_array().into_iter().flatten().filter(|d| d["wrong"].as_str().is_some_and(|w| !w.trim().is_empty())).map(|d| {
|
||||
let level = if d["level"].as_str().unwrap_or("").starts_with("block") { "blocking" } else { "detail" };
|
||||
let wrong = d["wrong"].as_str().unwrap_or("");
|
||||
json!({"defect": wrong.chars().take(80).collect::<String>(), "present": true, "level": level, "sheet": d["tile"], "asked": wrong,
|
||||
"where": d["where"], "real": d["real"], "fix": d["fix"]})
|
||||
}).collect();
|
||||
let photo = match v["blind"]["photo"].as_str() {
|
||||
Some(p) if p.starts_with('y') => json!(1.0),
|
||||
Some(p) if p.starts_with('n') => json!(0.0),
|
||||
_ => Value::Null,
|
||||
};
|
||||
(scores, defects, photo)
|
||||
}
|
||||
|
||||
/// One fresh judging session by `by` over DIR's sheets: its verdict JSON. Its steps stream (kimi's stream-json), each
|
||||
/// said on stderr as it comes, so a watcher sees it working through a judgement that can take minutes.
|
||||
pub fn ask(by: &str, dir: &Path, brief: &Value, target: Option<&Path>) -> Result<Value, String> {
|
||||
use std::io::BufRead as _;
|
||||
let dir = dunce::canonicalize(&dir).map_err(|e| format!("judge: {}: {e}", dir.display()))?;
|
||||
let p = prompt(&dir, brief, target);
|
||||
let 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
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
//! Shane's eye, the judge's calibration. `raea judge eye DIR form=5 light=7 ... [--pass yes|no]` records his scores for a
|
||||
//! round the judge has already judged (DIR/judge.json), with the judge's raw scores beside them, in
|
||||
//! ~/.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
|
||||
//! fresh agent session's reading instead (Shane, 11-06), each row saying whose eye it is.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::rubric::{SCORES, pass};
|
||||
|
||||
fn home() -> PathBuf {
|
||||
raea_io_home::env_path("RAEA_JUDGE_DIR", ".raea/judge")
|
||||
}
|
||||
|
||||
/// The calibration in force, if one was made.
|
||||
pub fn calibration() -> Option<Value> {
|
||||
serde_json::from_str(&std::fs::read_to_string(home().join("calibration.json")).ok()?).ok()
|
||||
}
|
||||
|
||||
/// The judge's scores mapped through the calibration's lines, kept to 0-10.
|
||||
pub fn apply(c: &Value, scores: &mut Map<String, Value>) {
|
||||
for (k, v) in scores.iter_mut() {
|
||||
if let (Some(x), Some(a), Some(b)) = (v.as_f64(), c["maps"][k]["a"].as_f64(), c["maps"][k]["b"].as_f64()) {
|
||||
*v = json!(((a * x + b).clamp(0.0, 10.0) * 100.0).round() / 100.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn record(args: &[String]) -> Result<String, String> {
|
||||
let dir = args.get(2).map(PathBuf::from).ok_or("raea judge eye DIR CATEGORY=SCORE... [--pass yes|no]")?;
|
||||
let verdict: Value = serde_json::from_str(&std::fs::read_to_string(dir.join("judge.json")).map_err(|_| format!("judge eye: no {}: judge the round first (raea judge {})", dir.join("judge.json").display(), dir.display()))?).map_err(|e| e.to_string())?;
|
||||
// an agent's reading as the eye (`--by kimi`): a fresh session's scores, and its pass by the same rule in code
|
||||
if let Some(by) = args.iter().position(|a| a == "--by").and_then(|i| args.get(i + 1)) {
|
||||
let v = crate::agent::ask(by, &dir, &json!({}), None)?;
|
||||
let (eye, defects, _) = crate::agent::read(&v);
|
||||
if eye.len() < SCORES.len() {
|
||||
return Err(format!("judge eye: {by} scored only {} of {} categories", eye.len(), SCORES.len()));
|
||||
}
|
||||
let eye_pass = pass(&eye, &defects).0;
|
||||
let row = json!({"dir": verdict["dir"], "by": by, "judge": verdict["raw"], "judge_pass": verdict["pass"], "defects": verdict["defects"], "eye": eye, "eye_pass": eye_pass, "eye_defects": defects});
|
||||
append(&row)?;
|
||||
let shown: Vec<String> = eye.iter().map(|(k, v)| format!("{k} {v}")).collect();
|
||||
return Ok(format!("APPLIED {by}'s eye on {} recorded ({}): {}; raea judge calibrate fits clef to it", dir.display(), if eye_pass { "a pass" } else { "not yet" }, shown.join(", ")));
|
||||
}
|
||||
let mut eye = Map::new();
|
||||
let mut said_pass = None;
|
||||
let mut i = 3;
|
||||
while i < args.len() {
|
||||
if args[i] == "--pass" {
|
||||
said_pass = Some(matches!(args.get(i + 1).map(String::as_str), Some("yes" | "true" | "y")));
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
let (k, v) = args[i].split_once('=').ok_or_else(|| format!("judge eye: {:?} isn't CATEGORY=SCORE", args[i]))?;
|
||||
if !SCORES.iter().any(|s| s.0 == k) {
|
||||
return Err(format!("judge eye: no category {k}: {}", SCORES.iter().map(|s| s.0).collect::<Vec<_>>().join(", ")));
|
||||
}
|
||||
let x: f64 = v.parse().ok().filter(|x| (0.0..=10.0).contains(x)).ok_or_else(|| format!("judge eye: {k} is a score 0-10, got {v:?}"))?;
|
||||
eye.insert(k.into(), json!(x));
|
||||
i += 1;
|
||||
}
|
||||
if eye.is_empty() {
|
||||
return Err("judge eye: give your scores, e.g. composition=6 form=5 assembly=7 materials=4 light=6 detail=5 world=6".into());
|
||||
}
|
||||
// his pass: as he says it, else the same rule on his scores with the judge's defects
|
||||
let eye_pass = said_pass.unwrap_or_else(|| pass(&eye, verdict["defects"].as_array().map(Vec::as_slice).unwrap_or(&[])).0);
|
||||
let row = json!({"dir": verdict["dir"], "by": "shane", "judge": verdict["raw"], "judge_pass": verdict["pass"], "defects": verdict["defects"], "eye": eye, "eye_pass": eye_pass});
|
||||
append(&row)?;
|
||||
Ok(format!("APPLIED your eye on {} recorded ({}): raea judge calibrate fits the judge to it", dir.display(), if eye_pass { "a pass" } else { "not yet" }))
|
||||
}
|
||||
|
||||
/// One eye row onto ~/.raea/judge/eye.jsonl; a newer reading of the same round by the same eye replaces the older.
|
||||
fn append(row: &Value) -> Result<(), String> {
|
||||
std::fs::create_dir_all(home()).map_err(|e| e.to_string())?;
|
||||
let path = home().join("eye.jsonl");
|
||||
let mut rows: Vec<Value> = std::fs::read_to_string(&path).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).filter(|r: &Value| !(r["dir"] == row["dir"] && whose(r) == whose(&row))).collect();
|
||||
rows.push(row.clone());
|
||||
std::fs::write(&path, rows.iter().map(Value::to_string).collect::<Vec<_>>().join("\n") + "\n").map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Least squares y = a x + b; flat x (one value) maps by the mean offset.
|
||||
fn fit(xy: &[(f64, f64)]) -> (f64, f64) {
|
||||
let n = xy.len() as f64;
|
||||
let (mx, my) = (xy.iter().map(|p| p.0).sum::<f64>() / n, xy.iter().map(|p| p.1).sum::<f64>() / n);
|
||||
let sxx: f64 = xy.iter().map(|p| (p.0 - mx).powi(2)).sum();
|
||||
if sxx < 1e-9 {
|
||||
return (1.0, my - mx);
|
||||
}
|
||||
let a = xy.iter().map(|p| (p.0 - mx) * (p.1 - my)).sum::<f64>() / sxx;
|
||||
(a, my - a * mx)
|
||||
}
|
||||
|
||||
/// The fit over rows of {judge, eye, defects, eye_pass}: per-category maps and errors, and the pass agreement.
|
||||
pub fn fit_rows(rows: &[Value]) -> Value {
|
||||
let mut maps = Map::new();
|
||||
for (k, _, _) in SCORES {
|
||||
let xy: Vec<(f64, f64)> = rows.iter().filter_map(|r| Some((r["judge"][k].as_f64()?, r["eye"][k].as_f64()?))).collect();
|
||||
if xy.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let (a, b) = fit(&xy);
|
||||
let mae = |f: &dyn Fn(f64) -> f64| xy.iter().map(|(x, y)| (f(*x) - y).abs()).sum::<f64>() / xy.len() as f64;
|
||||
let r2 = |x: f64| (x * 1000.0).round() / 1000.0;
|
||||
maps.insert(k.into(), json!({"a": r2(a), "b": r2(b), "n": xy.len(), "maeRaw": r2(mae(&|x| x)), "maeMapped": r2(mae(&|x| (a * x + b).clamp(0.0, 10.0)))}));
|
||||
}
|
||||
let cal = json!({"maps": maps});
|
||||
let mut agree = 0;
|
||||
for r in rows {
|
||||
let mut s = r["judge"].as_object().cloned().unwrap_or_default();
|
||||
apply(&cal, &mut s);
|
||||
let p = pass(&s, r["defects"].as_array().map(Vec::as_slice).unwrap_or(&[])).0;
|
||||
if Value::Bool(p) == r["eye_pass"] {
|
||||
agree += 1;
|
||||
}
|
||||
}
|
||||
let n = rows.len();
|
||||
let agreement = if n == 0 { 0.0 } else { agree as f64 / n as f64 };
|
||||
// agreement means something only when the eye passed some rounds and failed others: all fails agree trivially
|
||||
let passes = rows.iter().filter(|r| r["eye_pass"] == true).count();
|
||||
let both = passes > 0 && passes < n;
|
||||
json!({"maps": maps, "rounds": n, "eyePasses": passes, "agreement": (agreement * 1000.0).round() / 1000.0, "gate": n >= 10 && agreement >= 0.8 && both})
|
||||
}
|
||||
|
||||
pub fn calibrate(args: &[String]) -> Result<String, String> {
|
||||
let rows: Vec<Value> = std::fs::read_to_string(home().join("eye.jsonl")).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect();
|
||||
if rows.is_empty() {
|
||||
return Err("judge calibrate: no rounds with your eye yet (raea judge eye DIR form=5 ...)".into());
|
||||
}
|
||||
let mut cal = fit_rows(&rows);
|
||||
let mut eyes: Vec<String> = rows.iter().map(whose).map(str::to_string).collect();
|
||||
eyes.sort();
|
||||
eyes.dedup();
|
||||
cal["eyes"] = json!(eyes);
|
||||
std::fs::write(home().join("calibration.json"), serde_json::to_string_pretty(&cal).unwrap_or_default()).map_err(|e| e.to_string())?;
|
||||
if args.iter().any(|a| a == "--json") {
|
||||
return Ok(serde_json::to_string_pretty(&cal).unwrap_or_default());
|
||||
}
|
||||
let mut t: Vec<String> = cal["maps"].as_object().into_iter().flatten().map(|(k, m)| format!("{k:<12} eye = {} x judge {:+} (off by {} raw, {} mapped, {} rounds)", m["a"], m["b"], m["maeRaw"], m["maeMapped"], m["n"])).collect();
|
||||
t.push(format!("agreement on the pass: {} over {} rounds (eyes: {}); {}", cal["agreement"], cal["rounds"], eyes.join(", "), if cal["gate"] == true { "the judge gates now".to_string() } else if cal["rounds"].as_u64() >= Some(10) && cal["agreement"].as_f64() >= Some(0.8) { format!("advice only: the eye passed {} of {} rounds, and agreement means something only with passes and fails both (judge a scene that is good)", cal["eyePasses"], cal["rounds"]) } else { "advice only until 10 rounds agree 8 in 10, with passes and fails both".to_string() }));
|
||||
Ok(t.join("\n"))
|
||||
}
|
||||
|
||||
/// Whose eye a row records: Shane's when it doesn't say.
|
||||
fn whose(r: &Value) -> &str {
|
||||
r["by"].as_str().unwrap_or("shane")
|
||||
}
|
||||
@@ -1,206 +0,0 @@
|
||||
//! `raea judge`: a review's sheets (`raea render --review DIR`) judged by clef-omni on the frozen rubric (rubric.rs),
|
||||
//! fresh every round and blind to the code, with the pass decided here in code. Until it is calibrated against Shane's
|
||||
//! eye (`raea judge eye`, `raea judge calibrate`, eye.rs) its verdict is advice: `gating` says which.
|
||||
//!
|
||||
//! raea judge DIR [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry]
|
||||
//! raea judge eye DIR composition=6 form=5 ... [--pass yes|no] (or --by kimi: an agent's reading as the eye)
|
||||
//! raea judge calibrate [--json]
|
||||
//!
|
||||
//! DIR/judge.json is the verdict; DIR's parent's judge.log.jsonl holds every round's, so "done" (two passes in a row,
|
||||
//! each a fresh call) and the stall (the mean up by less than a point over two rounds) are read from it.
|
||||
|
||||
mod agent;
|
||||
mod eye;
|
||||
pub mod rubric;
|
||||
|
||||
pub use agent::BY;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use raea_core_facts::{Finding, Level, finding};
|
||||
use raea_runtime_bundle::flag;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub const USAGE: &str = "raea judge DIR [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR (CATEGORY=SCORE ... [--pass yes|no] | --by kimi|claude) | judge calibrate [--json] (a --review folder's sheets judged blind: clef-omni on the frozen rubric, or a fresh kimi or claude session on the judge prompt; the pass decided in code; clef advises until calibrated against your eye or an agent's)";
|
||||
|
||||
/// One call through raea's one clef client (raea-io-clef: the person's plan first, then their own Cloudflare keys),
|
||||
/// with the rubric's questions as written and each sheet as a JPEG still.
|
||||
fn ask(state: &str, questions: &Value, images: &[PathBuf]) -> Result<(Value, f64), String> {
|
||||
let qs = questions.as_object().ok_or("judge: the questions aren't a map")?;
|
||||
let questions = qs.iter().map(|(id, w)| raea_core_ask::Question::from_wire(id, w).ok_or(format!("judge: {id} isn't one of clef's question types"))).collect::<Result<_, _>>()?;
|
||||
let stills = images.iter().map(|p| raea_io_clef::media::still(p, None)).collect::<Result<_, _>>()?;
|
||||
let call = raea_io_clef::Call { state: state.into(), questions, media: raea_io_clef::Media { stills, ..Default::default() } };
|
||||
let a = raea_io_clef::ask(&call).map_err(|f| f.to_string())?;
|
||||
Ok((Value::Object(a.answers), a.cost))
|
||||
}
|
||||
|
||||
/// The brief's words, from `raea spec brief.ts --as brief` (look, logline, notDoing), or nothing.
|
||||
fn brief_of(path: Option<&str>) -> Result<Value, String> {
|
||||
let Some(p) = path else { return Ok(json!({})) };
|
||||
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
let out = std::process::Command::new(exe).args(["spec", p, "--as", "brief"]).output().map_err(|e| e.to_string())?;
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
let start = text.find('{').ok_or_else(|| format!("judge: {p} didn't read as a brief: {}", String::from_utf8_lossy(&out.stderr).lines().last().unwrap_or("")))?;
|
||||
let v: Value = serde_json::from_str(&text[start..]).map_err(|e| format!("judge: {p}: {e}"))?;
|
||||
Ok(v.get("brief").cloned().unwrap_or(v))
|
||||
}
|
||||
|
||||
/// The rounds judged so far beside this one (DIR's parent's judge.log.jsonl).
|
||||
fn log_of(dir: &Path) -> PathBuf {
|
||||
dir.parent().unwrap_or(dir).join("judge.log.jsonl")
|
||||
}
|
||||
|
||||
/// Done and stall, from the log's rounds (oldest first), in code.
|
||||
pub fn progress(rounds: &[Value]) -> Value {
|
||||
let passes = rounds.iter().rev().take_while(|r| r["pass"] == true).count();
|
||||
let means: Vec<f64> = rounds.iter().filter_map(|r| r["mean"].as_f64()).collect();
|
||||
let stall = means.len() >= 3 && {
|
||||
let best_before = means[..means.len() - 2].iter().cloned().fold(f64::MIN, f64::max);
|
||||
let best_now = means[means.len() - 2..].iter().cloned().fold(f64::MIN, f64::max);
|
||||
best_now - best_before < 1.0
|
||||
};
|
||||
// the same blocking defect present in the last two rounds
|
||||
let named = |r: &Value| -> Vec<String> { rubric::blocking(r["defects"].as_array().map(Vec::as_slice).unwrap_or_default()).into_iter().map(str::to_string).collect() };
|
||||
let again: Vec<String> = match rounds {
|
||||
[.., a, b] => named(a).into_iter().filter(|d| named(b).contains(d)).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
json!({"rounds": rounds.len(), "passesInARow": passes, "done": passes >= 2, "stall": stall || !again.is_empty(), "again": again})
|
||||
}
|
||||
|
||||
pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
match args.get(1).map(String::as_str) {
|
||||
Some("eye") => return eye::record(args),
|
||||
Some("calibrate") => return eye::calibrate(args),
|
||||
Some(_) => {}
|
||||
None => return Err(USAGE.into()),
|
||||
}
|
||||
let dir = PathBuf::from(&args[1]);
|
||||
let (colour, clay, hero) = (dir.join("colour.png"), dir.join("clay.png"), dir.join("hero-colour.png"));
|
||||
for f in [&colour, &clay] {
|
||||
if !f.is_file() {
|
||||
return Err(format!("judge: no {} (make the sheets with raea render EDIT.tsx --review {})", f.display(), dir.display()));
|
||||
}
|
||||
}
|
||||
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());
|
||||
if by != "clef" {
|
||||
if dry {
|
||||
return Ok(agent::prompt(&dir, &brief, target.as_deref()));
|
||||
}
|
||||
let v = agent::ask(&by, &dir, &brief, target.as_deref())?;
|
||||
let (scores, defects, photo) = agent::read(&v);
|
||||
return finish(args, &dir, scores.clone(), scores, defects, photo, 0.0, &by, false, json!({"blind": v["blind"], "show_as_is": v["show_as_is"]}));
|
||||
}
|
||||
let mut calls = Vec::new();
|
||||
for (sheet, img) in [("colour", &colour), ("clay", &clay)] {
|
||||
let mut images = vec![img.clone()];
|
||||
if sheet == "colour" {
|
||||
images.extend(target.clone());
|
||||
}
|
||||
calls.push((sheet, rubric::state(sheet, &brief), rubric::questions(sheet), images));
|
||||
}
|
||||
if hero.is_file() {
|
||||
calls.push(("blind", "One frame. Judge only what is in the pixels.".into(), rubric::blind(), vec![hero.clone()]));
|
||||
}
|
||||
if dry {
|
||||
let shown: Vec<Value> = calls.iter().map(|(s, st, q, im)| json!({"sheet": s, "state": st, "questions": q, "images": im.iter().map(|p| p.display().to_string()).collect::<Vec<_>>()})).collect();
|
||||
return Ok(serde_json::to_string_pretty(&json!({"would_ask": shown})).unwrap_or_default());
|
||||
}
|
||||
let mut scores = serde_json::Map::new();
|
||||
let mut defects = Vec::new();
|
||||
let mut photo = Value::Null;
|
||||
let mut cost = 0.0;
|
||||
for (sheet, st, q, images) in &calls {
|
||||
let (answers, c) = ask(st, q, images)?;
|
||||
cost += c;
|
||||
if *sheet == "blind" {
|
||||
photo = json!(answers["photo"]["noul"].as_f64().map(|p| (p * 1000.0).round() / 1000.0));
|
||||
continue;
|
||||
}
|
||||
let (s, d) = rubric::read(&answers);
|
||||
scores.extend(s);
|
||||
defects.extend(d.into_iter().map(|mut x| {
|
||||
x["sheet"] = json!(sheet);
|
||||
x
|
||||
}));
|
||||
}
|
||||
let raw = scores.clone();
|
||||
let cal = eye::calibration();
|
||||
if let Some(c) = &cal {
|
||||
eye::apply(c, &mut scores);
|
||||
}
|
||||
let gating = cal.as_ref().is_some_and(|c| c["gate"] == true);
|
||||
finish(args, &dir, scores, raw, defects, photo, cost, "clef", !gating, json!({"calibrated": cal.is_some()}))
|
||||
}
|
||||
|
||||
/// The defects a judge saw, as raea's one Finding (docs/direction.feature DR3): a blocking one an error and a detail a
|
||||
/// warn, each a level lower from a judge that only advises. A judge sees pictures, not parts: a finding names its
|
||||
/// sheet in its words and is about no entity.
|
||||
pub fn findings(defects: &[Value], by: &str, advice: bool) -> Vec<Finding> {
|
||||
let found = defects.iter().filter(|d| d["present"] == true).map(|d| {
|
||||
let blocking = d["level"] == "blocking";
|
||||
let level = match (blocking, advice) {
|
||||
(true, false) => Level::Error,
|
||||
(true, true) | (false, false) => Level::Warn,
|
||||
(false, true) => Level::Note,
|
||||
};
|
||||
let sheet = d["sheet"].as_str().unwrap_or("");
|
||||
let check = format!("judge.{}", if by == "clef" { d["defect"].as_str().unwrap_or("defect") } else { sheet });
|
||||
let mut f = Finding::new(&check, level, format!("{sheet} sheet: {}", d["asked"].as_str().unwrap_or("")), &format!("raea judge ({by})"));
|
||||
if let Some(p) = d["p"].as_f64() {
|
||||
f = f.measure("p", p, "", Some(0.5));
|
||||
}
|
||||
match d["fix"].as_str() {
|
||||
Some(x) if !x.is_empty() => f.fix(x),
|
||||
_ => f,
|
||||
}
|
||||
});
|
||||
finding::ranked(found.collect())
|
||||
}
|
||||
|
||||
/// The verdict decided in code, written (DIR/judge.json for clef, DIR/judge.BY.json for an agent; every round in the
|
||||
/// log), and said. `advice` marks a judge not yet trusted to gate (clef before calibration).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn finish(args: &[String], dir: &Path, scores: serde_json::Map<String, Value>, raw: serde_json::Map<String, Value>, defects: Vec<Value>, photo: Value, cost: f64, by: &str, advice: bool, extra: Value) -> Result<String, String> {
|
||||
let (pass, why) = rubric::pass(&scores, &defects);
|
||||
let vals: Vec<f64> = scores.values().filter_map(Value::as_f64).collect();
|
||||
let mean = if vals.is_empty() { 0.0 } else { (vals.iter().sum::<f64>() / vals.len() as f64 * 100.0).round() / 100.0 };
|
||||
let model = if by == "clef" { "@cf/cloudflare/clef-omni".to_string() } else { format!("{by} cli") };
|
||||
let found = findings(&defects, by, advice);
|
||||
let mut verdict = json!({"dir": dir.display().to_string(), "by": by, "scores": scores, "raw": raw, "mean": mean, "defects": defects, "photo": photo,
|
||||
"pass": pass, "why": why, "gating": !advice, "cost": cost, "model": model, "findings": found, "count": finding::count(&found)});
|
||||
if let (Some(v), Some(e)) = (verdict.as_object_mut(), extra.as_object()) {
|
||||
v.extend(e.clone());
|
||||
}
|
||||
let log = log_of(dir);
|
||||
let mut rounds: Vec<Value> = std::fs::read_to_string(&log).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).filter(|r: &Value| r["dir"] != verdict["dir"]).collect();
|
||||
rounds.push(verdict.clone());
|
||||
verdict["progress"] = progress(&rounds);
|
||||
let file = if by == "clef" { "judge.json".to_string() } else { format!("judge.{by}.json") };
|
||||
std::fs::write(dir.join(file), serde_json::to_string_pretty(&verdict).unwrap_or_default()).map_err(|e| e.to_string())?;
|
||||
let lines: Vec<String> = rounds.iter().map(|r| serde_json::to_string(&json!({"dir": r["dir"], "pass": r["pass"], "mean": r["mean"], "defects": r["defects"]})).unwrap_or_default()).collect();
|
||||
std::fs::write(&log, lines.join("\n") + "\n").map_err(|e| e.to_string())?;
|
||||
if cost > 0.0 {
|
||||
let _ = std::process::Command::new("antsy").args(["spend", &format!("{cost:.6}"), "raea judge (clef-omni)"]).output();
|
||||
}
|
||||
if args.iter().any(|a| a == "--json") {
|
||||
return Ok(serde_json::to_string_pretty(&verdict).unwrap_or_default());
|
||||
}
|
||||
let who = if by == "clef" { String::new() } else { format!("({by}) ") };
|
||||
let mut t = vec![format!("{} {who}{}{}", if pass { "PASS" } else { "NOT YET" }, if advice { "(advice: the judge isn't calibrated against your eye yet) " } else { "" }, why.join("; "))];
|
||||
t.push(format!("scores: {}", scores.iter().map(|(k, v)| format!("{k} {v}")).collect::<Vec<_>>().join(", ")));
|
||||
for f in &found {
|
||||
let p = f.measure.as_ref().map(|m| format!(" (p {})", m.value)).unwrap_or_default();
|
||||
t.push(format!(" {}{p}", f.line()));
|
||||
}
|
||||
let p = &verdict["progress"];
|
||||
t.push(format!("round {}: {} passes in a row{}{}; ${cost:.4}", p["rounds"], p["passesInARow"], if p["done"] == true { ", done" } else { "" }, if p["stall"] == true { ", stalled: change the approach for the part, not the dose" } else { "" }));
|
||||
t.push(format!("raea judge: {}", finding::count(&found)));
|
||||
Ok(t.join("\n"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,133 +0,0 @@
|
||||
//! The frozen rubric (the 11-06 prompt pack, section 3, in clef-omni's native question types): a 0-10 score per category
|
||||
//! as an ordered six-level rubric, and every named defect as a yes/no question, so a defect is a probability rather
|
||||
//! than prose. clef-omni answers questions, not essays; the defects it can name are the ones asked. Nothing here says
|
||||
//! where the pass line is (the loop decides, in code: `pass`).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The six levels each category is scored on, lowest first (clef's `score`: the probability-weighted level), read as
|
||||
/// 0, 2, 4, 6, 8, 10.
|
||||
fn levels(what: &str) -> Value {
|
||||
json!([
|
||||
format!("0: no {what} to speak of; broken or missing"),
|
||||
format!("2: {what} is crude: primitives and placeholders"),
|
||||
format!("4: {what} is a rough draft, plainly unfinished"),
|
||||
format!("6: {what} is a believable draft"),
|
||||
format!("8: {what} is a production base an artist would accept"),
|
||||
format!("10: {what} is indistinguishable from the real thing"),
|
||||
])
|
||||
}
|
||||
|
||||
/// (id, the sheet it is judged on, the question)
|
||||
pub const SCORES: [(&str, &str, &str); 7] = [
|
||||
("composition", "colour", "Composition: the camera, framing and layout; every major object's position and scale against the brief's space."),
|
||||
("form", "clay", "Form, judged on these grey clay tiles: silhouettes read at a glance, parts have real thickness, nothing blobby or melted, no primitive standing in for a thing, repeated things vary."),
|
||||
("assembly", "clay", "Assembly, judged on these grey clay tiles: nothing floats, sinks, pokes through or rests on the wrong thing; joints touch; the low tile shows the feet resting."),
|
||||
("materials", "colour", "Materials: every surface reads as its real material with wear where use puts it; nothing a flat default colour; glass is glass."),
|
||||
("light", "colour", "Light: motivated by the place's own sources; exposure and contrast believable; no surface implausibly dark or bright."),
|
||||
("detail", "colour", "Detail: close surfaces hold real geometry or texture at that distance, not smooth stand-ins; printed matter reads."),
|
||||
("world", "colour", "World: one coherent real place matching the brief; nothing off-era, no real brands, nothing invented beyond the brief."),
|
||||
];
|
||||
|
||||
/// (id, sheet, the yes/no question, blocking when yes)
|
||||
pub const DEFECTS: [(&str, &str, &str, bool); 12] = [
|
||||
("floating", "clay", "Does any object float above the surface it should rest on, with a visible gap under it?", true),
|
||||
("intersecting", "clay", "Does any object pass through another object, a wall or the floor?", true),
|
||||
("blobby", "clay", "Is any object a blobby, melted or lumpy shape where the real thing has crisp form?", true),
|
||||
("stand_in", "clay", "Is any object just a plain box, ball or cylinder standing in for a more detailed real thing?", true),
|
||||
("clones", "clay", "Are several copies of one thing identical and evenly spaced in an obviously artificial way?", false),
|
||||
("flat_colour", "colour", "Is any large surface a flat, uniform default colour with no texture, variation or wear?", true),
|
||||
("plastic", "colour", "Do the surfaces look like shiny uniform plastic or CG rather than their real materials?", true),
|
||||
("garbled_text", "colour", "Is any visible text garbled, tiled or unreadable where it should read?", false),
|
||||
("too_dark", "colour", "Is the scene so dark that important objects are hard to see?", true),
|
||||
("too_bright", "colour", "Is the scene washed out, with large areas blown to white?", true),
|
||||
("brands", "colour", "Is a real brand name or logo visible?", true),
|
||||
("not_doing", "colour", "Does the scene show anything the brief says it must not contain?", true),
|
||||
];
|
||||
|
||||
/// The paragraph clef reads before the sheet: what it is looking at, and the brief's words (no code, no log, no line).
|
||||
pub fn state(sheet: &str, brief: &Value) -> String {
|
||||
let look = brief["look"].as_str().unwrap_or("");
|
||||
let logline = brief["logline"].as_str().unwrap_or("");
|
||||
let not: Vec<&str> = brief["notDoing"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
|
||||
let tiles = "six tiles of one 3D scene, left to right and top to bottom: hero (the shot's own camera), front, right, top, iso, and low (a camera 0.3 m off the floor)";
|
||||
let what = if sheet == "clay" { format!("The image is {tiles}, rendered in clay: every surface plain grey, so only form and assembly show.") } else { format!("The image is {tiles}, in full colour.") };
|
||||
let target = if sheet == "colour" { " A second image, when given, is the target picture the scene should read as." } else { "" };
|
||||
let mut s = format!("{what}{target} Judge only what is in the pixels, as the person who will use the scene would.");
|
||||
if !logline.is_empty() || !look.is_empty() {
|
||||
s.push_str(&format!(" The brief: {logline} Look: {look}."));
|
||||
}
|
||||
if !not.is_empty() {
|
||||
s.push_str(&format!(" The scene must not contain: {}.", not.join("; ")));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// The questions for one sheet, by id.
|
||||
pub fn questions(sheet: &str) -> Value {
|
||||
let mut q = serde_json::Map::new();
|
||||
for (id, on, ask) in SCORES {
|
||||
if on == sheet {
|
||||
q.insert(format!("score_{id}"), json!({"type": "score", "instructions": ask, "criteria": levels(id)}));
|
||||
}
|
||||
}
|
||||
for (id, on, ask, _) in DEFECTS {
|
||||
if on == sheet {
|
||||
q.insert(format!("defect_{id}"), json!({"type": "noul", "instructions": ask}));
|
||||
}
|
||||
}
|
||||
Value::Object(q)
|
||||
}
|
||||
|
||||
/// The blind read on the hero tile alone: is this a photograph (reported, never gated, until calibrated).
|
||||
pub fn blind() -> Value {
|
||||
json!({"photo": {"type": "noul", "instructions": "Is this a photograph of a real place, rather than a computer render?"}})
|
||||
}
|
||||
|
||||
/// clef's answers read into scores (0-10) and defects (probability of yes, blocking ones flagged).
|
||||
pub fn read(answers: &Value) -> (serde_json::Map<String, Value>, Vec<Value>) {
|
||||
let mut scores = serde_json::Map::new();
|
||||
let mut defects = Vec::new();
|
||||
for (id, _, _) in SCORES {
|
||||
if let Some(a) = answers.get(format!("score_{id}")) {
|
||||
let level = a["score"].as_f64().unwrap_or(0.0);
|
||||
scores.insert(id.into(), json!((level * 2.0 * 100.0).round() / 100.0));
|
||||
}
|
||||
}
|
||||
for (id, _, ask, blocking) in DEFECTS {
|
||||
if let Some(a) = answers.get(format!("defect_{id}")) {
|
||||
let p = a["noul"].as_f64().unwrap_or(0.0);
|
||||
defects.push(json!({"defect": id, "p": (p * 1000.0).round() / 1000.0, "present": p >= 0.5, "level": if blocking { "blocking" } else { "detail" }, "asked": ask}));
|
||||
}
|
||||
}
|
||||
(scores, defects)
|
||||
}
|
||||
|
||||
/// The loop's pass, in code: no blocking defect present, the lowest score 6 or more and the mean 7 or more (raea's
|
||||
/// 0-10 scale; the prompt pack's line). Scores mapped by a calibration first, when there is one.
|
||||
pub fn pass(scores: &serde_json::Map<String, Value>, defects: &[Value]) -> (bool, Vec<String>) {
|
||||
let vals: Vec<f64> = scores.values().filter_map(Value::as_f64).collect();
|
||||
let mut why = Vec::new();
|
||||
let blocking = blocking(defects);
|
||||
if !blocking.is_empty() {
|
||||
why.push(format!("blocking: {}", blocking.join(", ")));
|
||||
}
|
||||
let min = vals.iter().cloned().fold(f64::INFINITY, f64::min);
|
||||
let mean = if vals.is_empty() { 0.0 } else { vals.iter().sum::<f64>() / vals.len() as f64 };
|
||||
if vals.len() < SCORES.len() {
|
||||
why.push(format!("only {} of {} categories scored", vals.len(), SCORES.len()));
|
||||
}
|
||||
if min < 6.0 {
|
||||
let low: Vec<String> = scores.iter().filter(|(_, v)| v.as_f64().is_some_and(|x| x < 6.0)).map(|(k, _)| k.clone()).collect();
|
||||
why.push(format!("below a draft: {}", low.join(", ")));
|
||||
}
|
||||
if mean < 7.0 {
|
||||
why.push("the whole is under a production base".into());
|
||||
}
|
||||
(why.is_empty(), why)
|
||||
}
|
||||
|
||||
/// The blocking defects present, by name.
|
||||
pub fn blocking(defects: &[Value]) -> Vec<&str> {
|
||||
defects.iter().filter(|d| d["present"] == true && d["level"] == "blocking").filter_map(|d| d["defect"].as_str()).collect()
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn scores(v: f64) -> serde_json::Map<String, Value> {
|
||||
rubric::SCORES.iter().map(|s| (s.0.to_string(), json!(v))).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pass_is_code_and_a_blocking_defect_holds_it() {
|
||||
assert!(rubric::pass(&scores(7.5), &[]).0);
|
||||
assert!(!rubric::pass(&scores(6.5), &[]).0, "mean under 7");
|
||||
let mut s = scores(8.0);
|
||||
s.insert("form".into(), json!(5.0));
|
||||
let (ok, why) = rubric::pass(&s, &[]);
|
||||
assert!(!ok && why.iter().any(|w| w.contains("form")));
|
||||
let d = vec![json!({"defect": "floating", "present": true, "level": "blocking"})];
|
||||
assert!(!rubric::pass(&scores(9.0), &d).0);
|
||||
// the questions hold no pass line
|
||||
let q = format!("{}{}", rubric::questions("colour"), rubric::questions("clay"));
|
||||
assert!(!q.contains("mean") && !q.contains(">= 6"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn answers_are_read_and_rounds_say_done_and_stall() {
|
||||
let a = json!({"score_form": {"score": 3.5}, "defect_floating": {"noul": 0.8}});
|
||||
let (s, d) = rubric::read(&a);
|
||||
assert_eq!(s["form"], 7.0);
|
||||
assert_eq!(d[0]["present"], true);
|
||||
let r = |p: bool, m: f64| json!({"pass": p, "mean": m, "defects": []});
|
||||
assert_eq!(progress(&[r(false, 5.0), r(true, 7.2), r(true, 7.4)])["done"], true);
|
||||
assert_eq!(progress(&[r(false, 5.0), r(false, 5.3), r(false, 5.6)])["stall"], true);
|
||||
assert_eq!(progress(&[r(false, 4.0), r(false, 5.3), r(false, 6.1)])["stall"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calibration_maps_a_lenient_judge_onto_the_eye() {
|
||||
// the judge says 8 to everything the eye gives 5, and 9 to what the eye gives 8
|
||||
let row = |j: f64, e: f64, p: bool| json!({"judge": scores(j), "eye": scores(e), "eye_pass": p, "defects": []});
|
||||
let rows: Vec<Value> = (0..12).map(|i| if i % 2 == 0 { row(8.0, 5.0, false) } else { row(9.0, 8.0, true) }).collect();
|
||||
let cal = eye::fit_rows(&rows);
|
||||
assert_eq!(cal["agreement"], 1.0);
|
||||
assert_eq!(cal["gate"], true);
|
||||
assert!((cal["maps"]["form"]["a"].as_f64().unwrap() - 3.0).abs() < 1e-6);
|
||||
let few = eye::fit_rows(&rows[..4]);
|
||||
assert_eq!(few["gate"], false, "too few rounds to gate");
|
||||
// an eye that failed everything agrees with a judge that fails everything, which proves nothing
|
||||
let fails: Vec<Value> = (0..12).map(|_| row(3.0, 2.0, false)).collect();
|
||||
let all_fail = eye::fit_rows(&fails);
|
||||
assert_eq!(all_fail["agreement"], 1.0);
|
||||
assert_eq!(all_fail["gate"], false, "no pass among the eye's rounds");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_agent_verdict_is_read_from_the_end_of_its_thinking() {
|
||||
// an agent thinks aloud, may draft the JSON twice, and ends with the one it means
|
||||
let text = r#"• Looking at the sheets... draft: {"scores": {"form": 1}} then the answer:
|
||||
{"blind": {"place": "office", "objects": [], "photo": "no", "tells": []},
|
||||
"scores": {"composition": 6, "form": 5.5, "assembly": 7, "materials": 4, "light": 6, "detail": 5, "world": 6, "vibes": 9},
|
||||
"defects": [{"tile": "iso", "where": "left", "wrong": "the desks are plain boxes", "real": "a desk has legs", "fix": "model legs", "level": "blocking"},
|
||||
{"tile": "low", "wrong": "", "level": "detail"}],
|
||||
"show_as_is": "no"}"#;
|
||||
let v = crate::agent::last_verdict(text).unwrap();
|
||||
let (scores, defects, photo) = crate::agent::read(&v);
|
||||
assert_eq!(scores.len(), 7, "only the seven categories, each 0-10");
|
||||
assert_eq!(scores["form"], serde_json::json!(5.5));
|
||||
assert_eq!(defects.len(), 1, "a defect with nothing wrong named is dropped");
|
||||
assert_eq!(defects[0]["level"], "blocking");
|
||||
assert_eq!(photo, serde_json::json!(0.0));
|
||||
let (pass, why) = crate::rubric::pass(&scores, &defects);
|
||||
assert!(!pass && why[0].starts_with("blocking"));
|
||||
assert!(crate::agent::last_verdict("no json here").is_none());
|
||||
// what it saw, as Findings (DR3): a gating judge's blocking defect is an error, an advising one's a warn
|
||||
let f = &crate::findings(&defects, "kimi", false)[0];
|
||||
assert_eq!((f.check.as_str(), f.level, f.fix.as_deref(), f.by.as_str()), ("judge.iso", raea_core_facts::Level::Error, Some("model legs"), "raea judge (kimi)"));
|
||||
assert!(f.says.starts_with("iso sheet: "), "{}", f.says);
|
||||
assert_eq!(crate::findings(&defects, "kimi", true)[0].level, raea_core_facts::Level::Warn);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "raea-app-lightbake"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "raea make bake light: bounce light baked into lightmaps on raea's own ray tracer, and the bar it is held to against Cycles (docs/bake.feature)"
|
||||
|
||||
[dependencies]
|
||||
# the frames' distance in stops, as raea light check measures it (LT1)
|
||||
raea-light = { path = "../../engine/light" }
|
||||
# the CLI's flag reader and result type
|
||||
raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
# raea's own files (the test set, the Blender library scripts) and the home folder
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
||||
serde_json = "1"
|
||||
sha2 = "0.10"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
# wait4: a step's peak memory
|
||||
libc = "0.2"
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"about": "the bake's test set (docs/bake.feature BK0), for `raea make bake light --compare DIR`: each set's Cycles still (blender/look.py, given the composition's own sky, tone and lens) and Cycles bake (blender/lightbake.py), and raea's frames beside them",
|
||||
"sets": [
|
||||
{ "name": "table", "dir": "bench/bake", "file": "table.tsx", "composition": "table", "cycles": ["table-cycles.tsx", "table-cycles"], "bar": true, "texels": 128,
|
||||
"look": ["--hdri", "media/kloofendal_48d_partly_cloudy_puresky_1k.hdr", "--strength", "0.25", "--rotation", "0.6", "--tone", "agx", "--exposure", "-0.8", "--focus", "2.5", "--fstop", "2.8", "--size", "1280x720"] },
|
||||
{ "name": "cornell", "dir": "bench/bake", "file": "cornell.tsx", "composition": "cornell", "cycles": ["cornell-cycles.tsx", "cornell-cycles"], "texels": 128,
|
||||
"look": ["--tone", "agx", "--exposure", "0", "--size", "1280x720"] },
|
||||
{ "name": "window", "dir": "bench/bake", "file": "window.tsx", "composition": "window", "cycles": ["window-cycles.tsx", "window-cycles"], "texels": 64,
|
||||
"look": ["--hdri", "media/kloofendal_48d_partly_cloudy_puresky_1k.hdr", "--strength", "0.25", "--rotation", "0.6", "--tone", "agx", "--exposure", "1.5", "--size", "1280x720"] },
|
||||
{ "name": "atelier", "dir": "~/Studio/raea/projects/atelier", "file": "compositions/atelier.tsx", "composition": "set", "texels": 64, "reference": false,
|
||||
"why": "a test agent's project, still being built; its Manifold solids stop `raea blender open` (filed with raea bug), so its Blender bake runs through its own tools/bake.sh. It joins at BK5, with that bake as the comparison" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
//! One set against Cycles (docs/bake.feature BK0): its Cycles still (blender/look.py) and Cycles bake
|
||||
//! (blender/lightbake.py), kept in DIR/NAME until the set or the samples change, then raea's frames beside them: the set
|
||||
//! unbaked, the set with Cycles' maps, and the set with raea's own bake. A frame is measured against the Cycles still by
|
||||
//! its RMSE (sRGB 0..1 over every pixel and channel, as docs/blender-research.md's table) and in stops (raea light
|
||||
//! check's distance); a lightmap against Cycles' in stops, texel by texel on the same UVs (map_stops).
|
||||
|
||||
use crate::{key, library, run, Ran, Set};
|
||||
use raea_runtime_bundle::R;
|
||||
use serde_json::{json, Value};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The bar (BK0): the frame with raea's bake within this RMSE of the Cycles still on the table set (lightbake.py's gives
|
||||
/// 0.040), no mesh's map off by more than a third of a stop on average, in under a quarter of lightbake.py's time.
|
||||
pub const BAR_RMSE: f64 = 0.045;
|
||||
pub const BAR_STOPS: f64 = 1.0 / 3.0;
|
||||
pub const BAR_TIME: f64 = 0.25;
|
||||
|
||||
/// The set's Cycles references, made: the export, look.py's still at `samples` (OUT/cycles.png), lightbake.py's bake at
|
||||
/// `samples` into the set's media/baked/NAME/, which the set's `cycles` composition reads.
|
||||
fn reference(set: &Set, samples: u32, out: &Path, baked: &Path) -> R<Value> {
|
||||
let bl = out.join("bl");
|
||||
let _ = std::fs::remove_dir_all(&bl);
|
||||
let _ = std::fs::remove_dir_all(baked);
|
||||
let stem = Path::new(&set.file).file_stem().map(|x| x.to_string_lossy().to_string()).unwrap_or_default();
|
||||
let open = run(&set.dir, &["blender".into(), "open".into(), set.file.clone(), "--no-window".into(), "-o".into(), format!("{}", bl.display())], &out.join("open.log"))?;
|
||||
let (blend, look) = (bl.join(format!("{stem}.blend")), bl.join("look.blend"));
|
||||
let mut a = vec!["blender".into(), "run".into(), format!("{}", library("look.py")?.display()), format!("{}", blend.display()), format!("{}", look.display())];
|
||||
a.extend(set.look.iter().cloned());
|
||||
a.extend(["--engine".into(), "cycles".into(), "--samples".into(), samples.to_string(), "--still".into(), format!("{}", out.join("cycles.png").display())]);
|
||||
let still = run(&set.dir, &a, &out.join("look.log"))?;
|
||||
let a = vec!["blender".into(), "run".into(), format!("{}", library("lightbake.py")?.display()), format!("{}", look.display()), format!("{}", baked.join("set.glb").display()), "--samples".into(), samples.to_string(), "--texels".into(), set.texels.to_string()];
|
||||
let bake = run(&set.dir, &a, &out.join("lightbake.log"))?;
|
||||
Ok(json!({ "export": open.json(), "still": still.json(), "lightbake": bake.json() }))
|
||||
}
|
||||
|
||||
/// Frame 0 of `composition` in `file`, drawn by raea into OUT/LABEL/: the picture and what it cost.
|
||||
fn frame(set: &Set, file: &str, composition: &str, out: &Path, label: &str) -> R<(PathBuf, Ran)> {
|
||||
let dir = out.join(label);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
|
||||
let a = ["render", file, "--composition", composition, "--at", "0", "-o", &format!("{}/", dir.display())].map(String::from);
|
||||
let ran = run(&set.dir, &a, &out.join(format!("{label}.log")))?;
|
||||
Ok((dir.join("frame-00000.png"), ran))
|
||||
}
|
||||
|
||||
fn round(x: f64) -> f64 {
|
||||
(x * 10000.0).round() / 10000.0
|
||||
}
|
||||
|
||||
/// RMSE of two pictures the same size, sRGB 0..1 over every pixel and channel.
|
||||
pub fn rmse(a: &Path, b: &Path) -> R<f64> {
|
||||
let load = |p: &Path| image::open(p).map(|i| i.to_rgb8()).map_err(|e| format!("{}: {e}", p.display()));
|
||||
let (a, b) = (load(a)?, load(b)?);
|
||||
if a.dimensions() != b.dimensions() {
|
||||
return Err(format!("sizes differ: {:?} against {:?}", a.dimensions(), b.dimensions()));
|
||||
}
|
||||
let sum: f64 = a.as_raw().iter().zip(b.as_raw()).map(|(x, y)| ((*x as f64 - *y as f64) / 255.0).powi(2)).sum();
|
||||
Ok((sum / a.as_raw().len().max(1) as f64).sqrt())
|
||||
}
|
||||
|
||||
/// A raea frame against the Cycles still: RMSE, and the mean and worst tile in stops.
|
||||
fn measure(got: &(PathBuf, Ran), cycles: &Path) -> R<Value> {
|
||||
let d = raea_light::metric::distance(&raea_light::metric::load(&got.0)?, &raea_light::metric::load(cycles)?)?;
|
||||
Ok(json!({ "rmse": round(rmse(&got.0, cycles)?), "mean_stops": round(d.mean as f64), "worst_stops": round(d.worst as f64), "render": got.1.json() }))
|
||||
}
|
||||
|
||||
/// A lightmap against another on the same UVs, each scaled by its lightmap_exposure: over the texels both cover, the
|
||||
/// mean distance in stops, the mean signed (brighter is positive), and the worst 8 x 8 tile's mean distance.
|
||||
pub fn map_stops(a: &Path, a_exposure: f64, b: &Path, b_exposure: f64) -> R<Value> {
|
||||
let lum = |p: &Path, k: f64| -> R<(u32, u32, Vec<f64>)> {
|
||||
let i = image::open(p).map_err(|e| format!("{}: {e}", p.display()))?.to_rgb32f();
|
||||
Ok((i.width(), i.height(), i.pixels().map(|q| k * (0.2126 * q[0] as f64 + 0.7152 * q[1] as f64 + 0.0722 * q[2] as f64)).collect()))
|
||||
};
|
||||
let ((w, h, a), (bw, bh, b)) = (lum(a, a_exposure)?, lum(b, b_exposure)?);
|
||||
if (w, h) != (bw, bh) {
|
||||
return Err(format!("map sizes differ: {w}x{h} against {bw}x{bh}"));
|
||||
}
|
||||
let (mut sum, mut signed, mut n) = (0.0, 0.0, 0usize);
|
||||
let mut tiles = vec![(0.0, 0usize); w.div_ceil(8) as usize * h.div_ceil(8) as usize];
|
||||
for (i, (x, y)) in a.iter().zip(&b).enumerate() {
|
||||
if *x <= 0.0 || *y <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let st = (x / y).log2();
|
||||
(sum, signed, n) = (sum + st.abs(), signed + st, n + 1);
|
||||
let t = &mut tiles[(i / w as usize / 8) * w.div_ceil(8) as usize + (i % w as usize) / 8];
|
||||
*t = (t.0 + st.abs(), t.1 + 1);
|
||||
}
|
||||
let worst = tiles.iter().filter(|t| t.1 >= 32).map(|t| t.0 / t.1 as f64).fold(0.0, f64::max);
|
||||
let k = n.max(1) as f64;
|
||||
Ok(json!({ "texels": n, "mean_stops": round(sum / k), "bias_stops": round(signed / k), "worst_tile_stops": round(worst) }))
|
||||
}
|
||||
|
||||
/// Whether a set's numbers meet the bar, and why not.
|
||||
fn bar(r: &Value) -> Value {
|
||||
let f = &r["frames"]["raea-bake"];
|
||||
if f["made"] == json!(false) {
|
||||
return json!({ "met": false, "why": f["why"] });
|
||||
}
|
||||
let rmse = f["rmse"].as_f64().is_some_and(|x| x <= BAR_RMSE);
|
||||
let meshes = r["meshes"].as_array().is_some_and(|m| m.iter().all(|m| m["raea"]["mean_stops"].as_f64().is_some_and(|x| x <= BAR_STOPS)));
|
||||
let time = match (f["bake"]["seconds"].as_f64(), r["reference"]["lightbake"]["seconds"].as_f64()) {
|
||||
(Some(a), Some(b)) => a < b * BAR_TIME,
|
||||
_ => false,
|
||||
};
|
||||
json!({ "met": rmse && meshes && time, "rmse": rmse, "meshes": meshes, "time": time })
|
||||
}
|
||||
|
||||
pub fn set(set: &Set, samples: u32, out: &Path, fresh: bool) -> R<Value> {
|
||||
std::fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
let mut r = json!({ "name": set.name, "samples": samples });
|
||||
if let Err(why) = &set.reference {
|
||||
r["reference"] = json!({ "made": false, "why": why });
|
||||
return Ok(r);
|
||||
}
|
||||
let (baked, cycles, made) = (set.dir.join("media/baked").join(&set.name), out.join("cycles.png"), out.join("made.json"));
|
||||
let key = key(set, samples);
|
||||
let kept = std::fs::read_to_string(&made).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok());
|
||||
r["reference"] = match kept.filter(|k| !fresh && k["key"] == json!(key) && cycles.is_file() && baked.join("set.lightmaps.json").is_file()) {
|
||||
Some(k) => {
|
||||
let mut v = k["reference"].clone();
|
||||
v["kept"] = json!(true);
|
||||
v
|
||||
}
|
||||
None => {
|
||||
let v = reference(set, samples, out, &baked)?;
|
||||
std::fs::write(&made, json!({ "key": key, "reference": v }).to_string()).map_err(|e| e.to_string())?;
|
||||
v
|
||||
}
|
||||
};
|
||||
r["frames"]["raea"] = measure(&frame(set, &set.file, &set.composition, out, "raea")?, &cycles)?;
|
||||
if let Some((file, comp)) = &set.cycles {
|
||||
r["frames"]["cycles-bake"] = measure(&frame(set, file, comp, out, "cycles-bake")?, &cycles)?;
|
||||
}
|
||||
// rask: BK5 raea's own bake of the set (<LightBake>): its frame against the Cycles still, its time and memory, and each mesh's map against Cycles' by map_stops on lightbake.py's UVs
|
||||
r["frames"]["raea-bake"] = json!({ "made": false, "why": "raea's bake isn't built yet (BK1-BK5)" });
|
||||
let maps: Value = std::fs::read_to_string(baked.join("set.lightmaps.json")).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default();
|
||||
r["meshes"] = json!(maps["meshes"].as_array().into_iter().flatten().map(|m| json!({ "mesh": m["mesh"], "size": m["size"], "cycles_exposure": m["lightmap_exposure"] })).collect::<Vec<_>>());
|
||||
if set.bar {
|
||||
r["bar"] = bar(&r);
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// The table a person reads: a line a set and frame, then the Cycles bake's cost and the bar.
|
||||
pub fn table(reports: &[Value]) -> String {
|
||||
let mut t = format!("{:<10} {:<12} {:>7} {:>7} {:>7}\n", "set", "frame", "rmse", "stops", "worst");
|
||||
for r in reports {
|
||||
let name = r["name"].as_str().unwrap_or("");
|
||||
if r["reference"]["made"] == json!(false) {
|
||||
t += &format!("{name:<10} (no reference: {})\n", r["reference"]["why"].as_str().unwrap_or(""));
|
||||
continue;
|
||||
}
|
||||
for (label, f) in r["frames"].as_object().into_iter().flatten() {
|
||||
let n = |k: &str| match f[k].as_f64() {
|
||||
Some(x) => format!("{x:.4}"),
|
||||
None => "-".into(),
|
||||
};
|
||||
let why = f["why"].as_str().map(|w| format!(" ({w})")).unwrap_or_default();
|
||||
t += &format!("{name:<10} {label:<12} {:>7} {:>7} {:>7}{why}\n", n("rmse"), n("mean_stops"), n("worst_stops"));
|
||||
}
|
||||
let (lb, st) = (&r["reference"]["lightbake"], &r["reference"]["still"]);
|
||||
t += &format!("{name:<10} Cycles at {} samples: lightbake.py {}s (peak {} MB) for {} meshes, the still {}s\n", r["samples"], lb["seconds"], lb["peak_mb"], r["meshes"].as_array().map_or(0, Vec::len), st["seconds"]);
|
||||
if let Some(b) = r.get("bar") {
|
||||
t += &format!("{name:<10} bar: {}\n", if b["met"] == json!(true) { "met".to_string() } else { format!("not met: {}", b["why"].as_str().unwrap_or("see report.json")) });
|
||||
}
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn png16(path: &Path, w: u32, h: u32, v: u16) {
|
||||
image::ImageBuffer::<image::Rgb<u16>, _>::from_pixel(w, h, image::Rgb([v, v, v])).save(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_twice_as_bright_is_one_stop_off_and_its_exposure_brings_it_back() {
|
||||
let d = std::env::temp_dir().join(format!("raea-lightbake-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let (a, b) = (d.join("a.png"), d.join("b.png"));
|
||||
png16(&a, 16, 16, 40000);
|
||||
png16(&b, 16, 16, 20000);
|
||||
let off = map_stops(&a, 1.0, &b, 1.0).unwrap();
|
||||
assert_eq!((off["mean_stops"].as_f64(), off["bias_stops"].as_f64(), off["texels"].as_u64()), (Some(1.0), Some(1.0), Some(256)));
|
||||
assert_eq!(map_stops(&a, 1.0, &b, 2.0).unwrap()["mean_stops"].as_f64(), Some(0.0));
|
||||
assert!(rmse(&a, &b).unwrap() > 0.3 && rmse(&a, &a).unwrap() == 0.0);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bar_is_unmet_until_raeas_bake_exists() {
|
||||
let r = json!({ "frames": { "raea-bake": { "made": false, "why": "not yet" } } });
|
||||
assert_eq!(bar(&r)["met"], json!(false));
|
||||
let r = json!({ "frames": { "raea-bake": { "rmse": 0.04, "bake": { "seconds": 4.0 } } }, "meshes": [{ "raea": { "mean_stops": 0.2 } }], "reference": { "lightbake": { "seconds": 20.0 } } });
|
||||
assert_eq!(bar(&r)["met"], json!(true));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
//! `raea make bake light EDIT.tsx [--composition ID] [--samples N] [--compare DIR]` (docs/bake.feature): raea's own bake of a
|
||||
//! composition's static parts (BK1-BK5), and the bar it is held to (BK0). `--compare DIR` runs the test set (sets.json)
|
||||
//! through Cycles (blender/look.py's still and blender/lightbake.py's bake, both at --samples, 1024 by default) and
|
||||
//! through raea, then writes DIR/report.json and a table: each frame's RMSE and stops against the Cycles still, each
|
||||
//! mesh's lightmap against Cycles', and each bake's time and peak memory.
|
||||
//!
|
||||
//! A set in sets.json: { "name", "dir" (under raea's home, or ~/...), "file", "composition", "cycles": [file,
|
||||
//! composition] (the set drawn with lightbake.py's maps), "look": [look.py's flags, the composition's own values],
|
||||
//! "texels" (lightbake.py's texels a metre), "bar": true (the set the bar is read on), "reference": false and "why" (a
|
||||
//! set whose references can't be made yet) }.
|
||||
|
||||
pub mod compare;
|
||||
|
||||
use raea_runtime_bundle::{flag, R};
|
||||
use serde_json::{json, Value};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub const USAGE: &str = "raea make bake light EDIT.tsx [--composition ID] [--samples N] | raea make bake light --compare DIR [--sets FILE] [--set NAME] [--samples N] [--fresh] (bounce light baked into lightmaps on raea's ray tracer; --compare measures the test set against Cycles' bake and still, docs/bake.feature)";
|
||||
|
||||
/// One set of the test set, as sets.json lists it.
|
||||
pub struct Set {
|
||||
pub name: String,
|
||||
pub dir: PathBuf,
|
||||
pub file: String,
|
||||
pub composition: String,
|
||||
pub cycles: Option<(String, String)>,
|
||||
pub look: Vec<String>,
|
||||
pub texels: u32,
|
||||
pub bar: bool,
|
||||
pub reference: Result<(), String>,
|
||||
}
|
||||
|
||||
fn home_path(p: &str) -> PathBuf {
|
||||
match (p.strip_prefix("~/"), raea_io_home::user_home()) {
|
||||
(Some(rest), Some(h)) => h.join(rest),
|
||||
_ if Path::new(p).is_absolute() => PathBuf::from(p),
|
||||
_ => raea_io_home::home().join(p),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn sets(path: &Path) -> R<Vec<Set>> {
|
||||
let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let v: Value = serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let list = v["sets"].as_array().ok_or(format!("{}: no \"sets\" list", path.display()))?;
|
||||
let strs = |x: &Value| x.as_array().map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect::<Vec<_>>()).unwrap_or_default();
|
||||
list.iter()
|
||||
.map(|s| {
|
||||
let text = |k: &str| match &s[k] {
|
||||
Value::String(v) => Ok(v.clone()),
|
||||
_ => Err(format!("{}: a set without \"{k}\"", path.display())),
|
||||
};
|
||||
let cycles = match strs(&s["cycles"]).as_slice() {
|
||||
[file, comp] => Some((file.clone(), comp.clone())),
|
||||
_ => None,
|
||||
};
|
||||
let reference = if s["reference"] == json!(false) { Err(s["why"].as_str().unwrap_or("not yet").to_string()) } else { Ok(()) };
|
||||
Ok(Set { name: text("name")?, dir: home_path(&text("dir")?), file: text("file")?, composition: text("composition")?, cycles, look: strs(&s["look"]), texels: s["texels"].as_u64().unwrap_or(128) as u32, bar: s["bar"] == json!(true), reference })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What a step cost: its seconds, and its peak memory in MB where the OS reports it (a child's and its children's).
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Ran {
|
||||
pub seconds: f64,
|
||||
pub peak_mb: Option<u64>,
|
||||
}
|
||||
|
||||
impl Ran {
|
||||
pub fn json(&self) -> Value {
|
||||
json!({ "seconds": (self.seconds * 10.0).round() / 10.0, "peak_mb": self.peak_mb })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn wait(child: std::process::Child) -> R<(bool, Option<u64>)> {
|
||||
let (mut status, pid) = (0, child.id() as libc::pid_t);
|
||||
// SAFETY: rusage is plain data, zeroed is a valid value; wait4 reaps the child std spawned and never waited on
|
||||
let mut ru: libc::rusage = unsafe { std::mem::zeroed() };
|
||||
if unsafe { libc::wait4(pid, &mut status, 0, &mut ru) } < 0 {
|
||||
return Err(format!("waiting for {pid}: {}", std::io::Error::last_os_error()));
|
||||
}
|
||||
// ru_maxrss is bytes on macOS, kilobytes elsewhere
|
||||
let kb = if cfg!(target_os = "macos") { ru.ru_maxrss as u64 / 1024 } else { ru.ru_maxrss as u64 };
|
||||
Ok((libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, Some(kb / 1024)))
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn wait(mut child: std::process::Child) -> R<(bool, Option<u64>)> {
|
||||
Ok((child.wait().map_err(|e| e.to_string())?.success(), None))
|
||||
}
|
||||
|
||||
/// This raea with `args` in `dir`, its output into `log`: what it cost, or the log's last lines.
|
||||
pub fn run(dir: &Path, args: &[String], log: &Path) -> R<Ran> {
|
||||
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
let out = std::fs::File::create(log).map_err(|e| format!("{}: {e}", log.display()))?;
|
||||
let err = out.try_clone().map_err(|e| e.to_string())?;
|
||||
let t = std::time::Instant::now();
|
||||
let child = std::process::Command::new(exe).current_dir(dir).args(args).stdout(out).stderr(err).spawn().map_err(|e| e.to_string())?;
|
||||
let (ok, peak_mb) = wait(child)?;
|
||||
let ran = Ran { seconds: t.elapsed().as_secs_f64(), peak_mb };
|
||||
if ok {
|
||||
return Ok(ran);
|
||||
}
|
||||
let text = std::fs::read_to_string(log).unwrap_or_default();
|
||||
let last: Vec<&str> = text.lines().filter(|l| !l.starts_with("Fra:") && l.chars().any(|c| !c.is_whitespace())).rev().take(4).collect();
|
||||
Err(format!("raea {} failed ({}): {}", args.first().map_or("", String::as_str), log.display(), last.into_iter().rev().collect::<Vec<_>>().join(" | ")))
|
||||
}
|
||||
|
||||
/// A set's identity for its kept references: every .tsx in its folder and its parts/, the flags look.py and lightbake.py
|
||||
/// get, and the samples.
|
||||
pub fn key(s: &Set, samples: u32) -> String {
|
||||
let mut h = Sha256::new();
|
||||
for d in [s.dir.clone(), s.dir.join("parts")] {
|
||||
let mut fs: Vec<PathBuf> = std::fs::read_dir(&d).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "tsx")).collect();
|
||||
fs.sort();
|
||||
for f in fs {
|
||||
h.update(f.file_name().unwrap_or_default().as_encoded_bytes());
|
||||
h.update(std::fs::read(&f).unwrap_or_default());
|
||||
}
|
||||
}
|
||||
h.update(format!("{:?} {} {samples}", s.look, s.texels));
|
||||
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
/// Where the Blender library scripts are (sdk/guides/craft/bevy/blender), with `name` there, or why not.
|
||||
pub fn library(name: &str) -> R<PathBuf> {
|
||||
let p = raea_io_home::home().join("sdk/guides/craft/bevy/blender").join(name);
|
||||
if p.is_file() { Ok(p) } else { Err(format!("no {} (the Blender library script the Cycles reference is made with)", p.display())) }
|
||||
}
|
||||
|
||||
pub fn cli(args: &[String]) -> R<String> {
|
||||
if args.get(1).map(String::as_str) != Some("light") {
|
||||
return Err(format!("usage: {USAGE}"));
|
||||
}
|
||||
let samples: u32 = flag(args, "--samples").map(|v| v.parse().map_err(|_| format!("--samples {v}: a count of samples a texel"))).transpose()?.unwrap_or(1024);
|
||||
let Some(out) = flag(args, "--compare").map(PathBuf::from) else {
|
||||
// rask: BK5 `raea make bake light EDIT.tsx` bakes a composition's <LightBake> ahead of a render and says what it baked
|
||||
return Err("raea's own bake isn't built yet (docs/bake.feature BK1-BK5); `raea make bake light --compare DIR` measures the test set against Cycles".into());
|
||||
};
|
||||
let list = sets(&flag(args, "--sets").map_or_else(|| raea_io_home::home().join("apps/lightbake/sets.json"), PathBuf::from))?;
|
||||
let only = flag(args, "--set");
|
||||
let fresh = args.iter().any(|a| a == "--fresh");
|
||||
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
let mut reports = Vec::new();
|
||||
for s in list.iter().filter(|s| only.is_none() || only.as_deref() == Some(s.name.as_str())) {
|
||||
eprintln!("raea make bake light: {} ...", s.name);
|
||||
reports.push(compare::set(s, samples, &out.join(&s.name), fresh)?);
|
||||
}
|
||||
if reports.is_empty() {
|
||||
return Err(format!("no set named {}", only.unwrap_or_default()));
|
||||
}
|
||||
let report = json!({ "samples": samples, "sets": reports });
|
||||
let path = out.join("report.json");
|
||||
std::fs::write(&path, serde_json::to_string_pretty(&report).unwrap_or_default()).map_err(|e| e.to_string())?;
|
||||
Ok(format!("{}raea make bake light: wrote {}", compare::table(&reports), path.display()))
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "raea-app-make"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "raea make's Rust: a scene, kit or shot goal's asset steps (docs/goal.feature)"
|
||||
|
||||
[dependencies]
|
||||
# the plan: `make` on brief.ts
|
||||
raea-core-brief = { path = "../../core/brief" }
|
||||
# the folder a project lives in
|
||||
raea-core-facts = { path = "../../core/facts" }
|
||||
# a lens's field of view (MK15's lens chart), as the review sheets work it out
|
||||
raea-core-review = { path = "../../core/review" }
|
||||
# the contact sheets: tiles composited, labels drawn in the system's fonts
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
|
||||
resvg = { version = "=0.48.1", default-features = false, features = ["text", "system-fonts"] }
|
||||
dunce = "1"
|
||||
serde_json = "1"
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
//! The plan stop (docs/goal.feature MK18, from AnyScene's endpoint/floorplan.py, MIT): before anything is generated,
|
||||
//! the plan drawn so a person can approve it. A floor plan from above (every object's footprint at its `at`, turned by
|
||||
//! its `rot`, labelled; invented ones dashed, so what came from the reference and what was added are told apart), a
|
||||
//! grey-box blockout of the same plan rendered from the entrance and through `raea render --review`, and the
|
||||
//! reference beside the blockout on one comparison sheet.
|
||||
//!
|
||||
//! raea make blockout [DIR] -> review/plan/floor-plan.png, blockout.tsx, blockout.png, comparison.png, colour/clay sheets
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use raea_core_brief::goal::{Goal, Object, Origin};
|
||||
|
||||
use crate::sheet::{Tile, esc, sheet, svg_png};
|
||||
use crate::shots::raea;
|
||||
|
||||
/// An object's footprint, metres: [width, depth] (its box, else a square about as wide as it's tall).
|
||||
pub fn footprint(o: &Object) -> [f64; 2] {
|
||||
if let Some([w, d, _]) = o.dims {
|
||||
return [w, d];
|
||||
}
|
||||
let s = o.max.unwrap_or_else(|| o.h.unwrap_or(0.5) * 0.6).max(0.05);
|
||||
[s, s]
|
||||
}
|
||||
|
||||
fn height(o: &Object) -> f64 {
|
||||
o.dims.map(|d| d[2]).or(o.h).unwrap_or(0.05).max(0.01)
|
||||
}
|
||||
|
||||
/// The placed objects and the floor they span: (objects with an `at`, [x0, z0, x1, z1] with half a metre around).
|
||||
pub fn extent(m: &Goal) -> (Vec<&Object>, [f64; 4]) {
|
||||
let placed: Vec<&Object> = m.objects.iter().filter(|o| o.at.is_some()).collect();
|
||||
let mut b = [0.0f64, 0.0, 1.0, 1.0];
|
||||
for o in &placed {
|
||||
let at = o.at.unwrap();
|
||||
let [w, d] = footprint(o);
|
||||
let r = 0.5 * (w * w + d * d).sqrt();
|
||||
b = [b[0].min(at[0] - r), b[1].min(at[2] - r), b[2].max(at[0] + r), b[3].max(at[2] + r)];
|
||||
}
|
||||
(placed, [b[0] - 0.5, b[1] - 0.5, b[2] + 0.5, b[3] + 0.5])
|
||||
}
|
||||
|
||||
/// The floor plan as SVG: the entrance (z = 0) at the bottom, a metre grid, each footprint turned and labelled.
|
||||
pub fn floor_svg(m: &Goal) -> Result<String, String> {
|
||||
let (placed, [x0, z0, x1, z1]) = extent(m);
|
||||
if placed.is_empty() {
|
||||
return Err("raea make blockout: no object has an `at` (where it stands, in metres: x right, z away from the entrance)".into());
|
||||
}
|
||||
let px = (1400.0 / (x1 - x0).max(z1 - z0)).min(260.0);
|
||||
let (w, h) = (((x1 - x0) * px).ceil() as u32 + 40, ((z1 - z0) * px).ceil() as u32 + 130);
|
||||
// text sized to the plan, so it still reads once the plan is a third of a comparison sheet
|
||||
let t = (w as f64 * 0.02).max(16.0);
|
||||
// plan x right, z away from the entrance: up the page
|
||||
let sx = |x: f64| (x - x0).mul_add(px, 20.0);
|
||||
let sy = |z: f64| 70.0 + (z1 - z) * px;
|
||||
let mut s = format!("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{w}\" height=\"{h}\"><rect width=\"100%\" height=\"100%\" fill=\"#f4f2ee\"/>");
|
||||
s += &format!("<text x=\"20\" y=\"{:.0}\" font-size=\"{:.0}\" font-weight=\"bold\" fill=\"#222\">Floor plan: {} objects (solid: from the reference; dashed: invented)</text>", t * 1.6, t * 1.1, placed.len());
|
||||
let mut g = x0.ceil();
|
||||
while g <= x1 {
|
||||
s += &format!("<line x1=\"{0:.1}\" y1=\"{1:.1}\" x2=\"{0:.1}\" y2=\"{2:.1}\" stroke=\"#dedad2\" stroke-width=\"1\"/>", sx(g), sy(z1), sy(z0));
|
||||
g += 1.0;
|
||||
}
|
||||
let mut g = z0.ceil();
|
||||
while g <= z1 {
|
||||
s += &format!("<line x1=\"{1:.1}\" y1=\"{0:.1}\" x2=\"{2:.1}\" y2=\"{0:.1}\" stroke=\"#dedad2\" stroke-width=\"1\"/>", sy(g), sx(x0), sx(x1));
|
||||
g += 1.0;
|
||||
}
|
||||
// the entrance: the front edge, and where the camera looks in from
|
||||
s += &format!("<line x1=\"{0:.1}\" y1=\"{1:.1}\" x2=\"{2:.1}\" y2=\"{1:.1}\" stroke=\"#3a7bd5\" stroke-width=\"4\"/>", sx(x0), sy(z0), sx(x1));
|
||||
s += &format!("<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"{:.0}\" fill=\"#3a7bd5\" text-anchor=\"middle\">entrance: the camera looks in from here</text>", (sx(x0) + sx(x1)) / 2.0, sy(z0) + t * 1.3, t * 0.9);
|
||||
for o in &placed {
|
||||
let at = o.at.unwrap();
|
||||
let [fw, fd] = footprint(o);
|
||||
let invented = o.source == Some(Origin::Invented);
|
||||
let dash = if invented { " stroke-dasharray=\"8 5\"" } else { "" };
|
||||
let fill = if o.hero == Some(true) { "#f2c46d" } else if invented { "#ece8f4" } else { "#d9e4d2" };
|
||||
s += &format!(
|
||||
"<g transform=\"translate({:.1} {:.1}) rotate({:.1})\"><rect x=\"{:.1}\" y=\"{:.1}\" width=\"{:.1}\" height=\"{:.1}\" fill=\"{fill}\" stroke=\"#333\" stroke-width=\"2\"{dash}/><line x1=\"0\" y1=\"0\" x2=\"0\" y2=\"{:.1}\" stroke=\"#333\" stroke-width=\"2\"/></g>",
|
||||
sx(at[0]),
|
||||
sy(at[2]),
|
||||
-o.rot.unwrap_or(0.0),
|
||||
-fw * px / 2.0,
|
||||
-fd * px / 2.0,
|
||||
fw * px,
|
||||
fd * px,
|
||||
fd * px / 2.0
|
||||
);
|
||||
s += &format!("<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"{:.0}\" fill=\"#111\" text-anchor=\"middle\">{}</text>", sx(at[0]), sy(at[2]) - t * 0.25, t, esc(&o.label));
|
||||
s += &format!("<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"{:.0}\" fill=\"#555\" text-anchor=\"middle\">{:.2} m{}</text>", sx(at[0]), sy(at[2]) + t * 0.9, t * 0.8, height(o), o.lod.map(|l| format!(", LOD {l}")).unwrap_or_default());
|
||||
}
|
||||
s += &format!("<line x1=\"20\" y1=\"{0}\" x2=\"{1:.1}\" y2=\"{0}\" stroke=\"#111\" stroke-width=\"5\"/><text x=\"20\" y=\"{2:.0}\" font-size=\"{3:.0}\" fill=\"#111\">1 m</text>", h - 18, 20.0 + px, h as f64 - 26.0, t * 0.9);
|
||||
s += "</svg>";
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
/// The blockout: a grey box for each placed object at its place and turn on a floor, seen from the entrance.
|
||||
pub fn blockout_tsx(m: &Goal) -> String {
|
||||
let (placed, [x0, z0, x1, z1]) = extent(m);
|
||||
let mut boxes = String::new();
|
||||
for o in &placed {
|
||||
let at = o.at.unwrap();
|
||||
let [w, d] = footprint(o);
|
||||
let h = height(o);
|
||||
let colour = if o.source == Some(Origin::Invented) { "#b4b0bd" } else { "#bdbdb8" };
|
||||
let a = -o.rot.unwrap_or(0.0).to_radians() / 2.0;
|
||||
let lod = o.lod.map(|l| format!(" lod={{{l}}}")).unwrap_or_default();
|
||||
boxes += &format!(
|
||||
" <Mesh3d name=\"{}\"{lod} transform={{Transform.fromXyz({:.3}, {:.3}, {:.3}).withRotation([0, {:.5}, 0, {:.5}])}}>\n <Cuboid half_size={{[{:.3}, {:.3}, {:.3}]}} />\n <StandardMaterial base_color=\"{colour}\" perceptual_roughness={{0.9}} />\n </Mesh3d>\n",
|
||||
o.id,
|
||||
at[0],
|
||||
at[1] + h / 2.0,
|
||||
at[2],
|
||||
a.sin(),
|
||||
a.cos(),
|
||||
w / 2.0,
|
||||
h / 2.0,
|
||||
d / 2.0
|
||||
);
|
||||
}
|
||||
let (cx, cz) = ((x0 + x1) / 2.0, (z0 + z1) / 2.0);
|
||||
let (fw, fd) = ((x1 - x0) / 2.0, (z1 - z0) / 2.0);
|
||||
format!(
|
||||
"// written by raea make blockout: the plan as grey boxes, seen from the entrance (approve it before anything is made)\nimport {{ AbsoluteFill, Composition, registerRoot }} from \"raea\";\nimport {{ StandardMaterial }} from \"raea/pbr\";\nimport {{ Cuboid, Mesh3d }} from \"raea/mesh\";\nimport {{ AmbientLight, DirectionalLight }} from \"raea/light\";\nimport {{ Transform }} from \"raea/transform\";\nimport {{ Camera3d }} from \"raea/camera\";\n\nfunction Blockout() {{\n return (\n <AbsoluteFill style={{{{ background: \"#cfd3d6\" }}}}>\n <Camera3d transform={{Transform.fromXyz({cx:.3}, 1.6, {ez:.3}).lookingAt([{cx:.3}, 0.9, {cz:.3}])}} projection={{{{ Perspective: {{ fov: (50 * Math.PI) / 180 }} }}}} />\n <AmbientLight brightness={{350}} />\n <DirectionalLight transform={{Transform.fromXyz({lx:.3}, 6, -2).lookingAt([{cx:.3}, 0, {cz:.3}])}} illuminance={{8000}} shadow_maps_enabled />\n <Mesh3d transform={{Transform.fromXyz({cx:.3}, -0.01, {cz:.3})}}>\n <Cuboid half_size={{[{fw:.3}, 0.01, {fd:.3}]}} />\n <StandardMaterial base_color=\"#e6e3dc\" perceptual_roughness={{0.95}} />\n </Mesh3d>\n{boxes} </AbsoluteFill>\n );\n}}\n\nregisterRoot(() => <Composition id=\"blockout\" component={{Blockout}} width={{1280}} height={{720}} fps={{30}} durationInFrames={{1}} />);\n",
|
||||
ez = z0 - 0.4,
|
||||
lx = cx + 2.0,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn plan_dir(dir: &Path) -> PathBuf {
|
||||
dir.join("review/plan")
|
||||
}
|
||||
|
||||
/// The plan stop's pictures: floor plan, blockout (and its review sheets), and the comparison with reference 0.
|
||||
pub fn draw_plan(dir: &Path, m: &Goal, review: bool) -> Result<String, String> {
|
||||
let out = plan_dir(dir);
|
||||
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
let floor = out.join("floor-plan.png");
|
||||
svg_png(&floor_svg(m)?)?.save(&floor).map_err(|e| format!("{}: {e}", floor.display()))?;
|
||||
let tsx = out.join("blockout.tsx");
|
||||
std::fs::write(&tsx, blockout_tsx(m)).map_err(|e| format!("{}: {e}", tsx.display()))?;
|
||||
let shot = out.join("blockout.png");
|
||||
raea(&["render".into(), tsx.display().to_string(), "-o".into(), shot.display().to_string(), "--frame".into(), "0".into()], &[])?;
|
||||
let mut said = vec![format!("wrote {}", floor.display()), format!("wrote {}", shot.display())];
|
||||
if review {
|
||||
raea(&["render".into(), tsx.display().to_string(), "--review".into(), out.display().to_string()], &[])?;
|
||||
said.push(format!("review sheets of the blockout in {}", out.display()));
|
||||
}
|
||||
let mut row = Vec::new();
|
||||
if let Some(r) = m.references.first() {
|
||||
row.push(Tile { img: dir.join(r), label: "reference".into() });
|
||||
}
|
||||
row.push(Tile { img: shot, label: "blockout from the entrance".into() });
|
||||
row.push(Tile { img: floor, label: "floor plan".into() });
|
||||
let cmp = out.join("comparison.png");
|
||||
sheet("Plan: the reference, the blockout from the entrance, the floor plan", &[row], 640, &cmp)?;
|
||||
said.push(format!("wrote {}: approve the plan (positions, sizes, what's invented) before any generation", cmp.display()));
|
||||
Ok(said.join("\n"))
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
//! A kit's steps (docs/goal.feature MK10-MK12, from AnyKit): every object's reference made in one style from the
|
||||
//! style images, checked on one sheet before any 3D; each reference to both generators (Tripo H3.1 and Meshy, on fal)
|
||||
//! and the pick made on clay renders (kitout.rs draws the pick sheets); the pick fitted to its real size with a
|
||||
//! quarter-triangle LOD beside it, each with a sidecar saying how it was made.
|
||||
//!
|
||||
//! raea make refs [DIR] [--only ID,...] [--model M] [--dry]
|
||||
//! raea make sheet refs [DIR]
|
||||
//! raea make gen [DIR] [--only ID,...] [--tripo M] [--meshy M] [--dry]
|
||||
//! raea make pick ID GENERATOR "why"
|
||||
//! raea make prep [DIR] [--only ID,...]
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use raea_core_brief::goal::{Goal, Object};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::sheet::{Tile, sheet};
|
||||
use crate::shots::raea;
|
||||
|
||||
/// What every reference prompt ends with: one object, whole, on a plain ground, in even light (the scan template).
|
||||
pub const SCAN: &str = "One object only, whole and centred, on a plain light grey background, soft even studio light, a three-quarter view from slightly above. Its own printed labels only, from the one maker named; no real brands, no text overlays.";
|
||||
/// The two generators every reference goes to (MK11).
|
||||
pub const TRIPO: &str = "tripo:H3.1";
|
||||
pub const MESHY: &str = "fal:meshy/v7.1/image-to-3d";
|
||||
/// Face limits: a hero, a small prop.
|
||||
const HERO_FACES: u32 = 150_000;
|
||||
const PROP_FACES: u32 = 60_000;
|
||||
|
||||
/// The objects named in `--only` (all when it's empty).
|
||||
pub fn objects<'a>(m: &'a Goal, only: &[String]) -> Vec<&'a Object> {
|
||||
crate::only(&m.objects, only, |o| o.id.as_str())
|
||||
}
|
||||
|
||||
/// The prompt a reference is made from: the plan's style paragraph, the object's own words, the scan template.
|
||||
pub fn ref_prompt(m: &Goal, o: &Object) -> String {
|
||||
let style = m.style.as_deref().unwrap_or("").trim().trim_end_matches('.');
|
||||
let what = o.prompt.as_deref().unwrap_or(&o.label).trim().trim_end_matches('.');
|
||||
format!("{style}. {what}. {SCAN}")
|
||||
}
|
||||
|
||||
/// `--h`, `--dims` or nothing: how gen check fits an object to its real size.
|
||||
pub fn size_args(o: &Object) -> Vec<String> {
|
||||
if let Some([w, d, h]) = o.dims {
|
||||
return vec!["--dims".into(), format!("{w},{d},{h}")];
|
||||
}
|
||||
if let Some(h) = o.h {
|
||||
return vec!["--h".into(), h.to_string()];
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// How `raea gen check -o` fits one generator's model to the object's size: its height (`--h`, which is what scales;
|
||||
/// a boxy object's is the third of its dims) and, for a boxy one, a quarter turn when the model's long side lies
|
||||
/// across (x) where the plan's lies front to back (z), or the other way: generators don't agree on which way is front.
|
||||
/// `measured` is the raw model's [w, h, d] (`raea gen check --json`'s measured.size).
|
||||
pub fn fit_args(o: &Object, measured: Option<[f64; 3]>) -> Vec<String> {
|
||||
let mut a = size_args(o);
|
||||
if let Some([w, d, h]) = o.dims {
|
||||
a.extend(["--h".into(), h.to_string()]);
|
||||
if let Some([mw, _, md]) = measured {
|
||||
let long = |x: f64, z: f64| if x > z * 1.2 { Some(true) } else if z > x * 1.2 { Some(false) } else { None };
|
||||
if let (Some(want), Some(got)) = (long(w, d), long(mw, md)) {
|
||||
if want != got {
|
||||
a.extend(["--turn".into(), "90".into()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
/// The raw model's size [w, h, d], measured by `raea gen check --json`.
|
||||
pub fn measured_size(model: &Path) -> Option<[f64; 3]> {
|
||||
let out = raea(&["gen".into(), "check".into(), model.display().to_string(), "--json".into()], &[]).ok()?;
|
||||
let v = json_of(&out)?;
|
||||
let s = v["measured"]["size"].as_array()?;
|
||||
Some([s.first()?.as_f64()?, s.get(1)?.as_f64()?, s.get(2)?.as_f64()?])
|
||||
}
|
||||
|
||||
/// The file a single-shot `raea gen` wrote: its JSON's `out.out`, a path or the first of a list.
|
||||
pub fn gen_file(out: &str) -> Option<PathBuf> {
|
||||
let v: Value = serde_json::from_str(out.trim()).ok()?;
|
||||
let o = &v["out"]["out"];
|
||||
o.as_str().or_else(|| o.as_array()?.first()?.as_str()).map(PathBuf::from)
|
||||
}
|
||||
|
||||
fn cents(out: &str) -> f64 {
|
||||
json_of(out).and_then(|v| v["cents"].as_f64()).unwrap_or(0.0)
|
||||
}
|
||||
|
||||
/// raea gen's JSON from its output (anything printed before it skipped).
|
||||
fn json_of(out: &str) -> Option<Value> {
|
||||
serde_json::from_str(out[out.find('{')?..].trim()).ok()
|
||||
}
|
||||
|
||||
/// A `--plan` or `gen plan` quote in a line: what each paid step runs on, and the total.
|
||||
pub fn quote(out: &str) -> String {
|
||||
let Some(v) = json_of(out) else { return out.split_whitespace().collect::<Vec<_>>().join(" ") };
|
||||
let on: Vec<&str> = v["steps"].as_array().into_iter().flatten().filter_map(|s| s["runs_on"].as_str()).filter(|r| *r != "load").collect();
|
||||
format!("{} (about {}¢)", if on.is_empty() { "nothing paid".to_string() } else { on.join(" + ") }, v["cents"].as_f64().unwrap_or(0.0))
|
||||
}
|
||||
|
||||
pub fn refs_dir(dir: &Path) -> PathBuf {
|
||||
dir.join("out/kit/refs")
|
||||
}
|
||||
|
||||
/// Every object's reference, made from the style images (`references`) in the plan's style; then the sheet.
|
||||
pub fn refs(dir: &Path, m: &Goal, only: &[String], model: Option<&str>, dry: bool) -> Result<String, String> {
|
||||
if m.references.is_empty() {
|
||||
return Err("raea make refs: the plan has no `references` (the style images every reference is made from)".into());
|
||||
}
|
||||
let mut said = Vec::new();
|
||||
let mut spent = 0.0;
|
||||
for o in objects(m, only) {
|
||||
let work = refs_dir(dir).join("gen").join(&o.id);
|
||||
let mut args: Vec<String> = vec!["gen".into(), "image".into(), ref_prompt(m, o)];
|
||||
for r in &m.references {
|
||||
args.extend(["--image".into(), dir.join(r).display().to_string()]);
|
||||
}
|
||||
args.extend(["--aspect".into(), "1:1".into(), "-o".into(), work.display().to_string()]);
|
||||
if let Some(md) = model {
|
||||
args.extend(["--model".into(), md.to_string()]);
|
||||
}
|
||||
if dry {
|
||||
args.push("--plan".into());
|
||||
let out = raea(&args, &[])?;
|
||||
spent += cents(&out);
|
||||
said.push(format!("{}: {}", o.id, quote(&out)));
|
||||
continue;
|
||||
}
|
||||
eprintln!("raea make refs: {}", o.id);
|
||||
let out = raea(&args, &[])?;
|
||||
spent += cents(&out);
|
||||
let made = gen_file(&out).ok_or_else(|| format!("{}: raea gen image wrote no file: {}", o.id, out.trim()))?;
|
||||
let to = refs_dir(dir).join(format!("{}.png", o.id));
|
||||
std::fs::copy(&made, &to).map_err(|e| format!("{}: {e}", to.display()))?;
|
||||
said.push(format!("{}: {}", o.id, to.display()));
|
||||
}
|
||||
if dry {
|
||||
return Ok(format!("would make {} reference{} for about ${:.2} (nothing spent):\n{}", said.len(), if said.len() == 1 { "" } else { "s" }, spent / 100.0, said.join("\n")));
|
||||
}
|
||||
let sheet = sheet_refs(dir, m)?;
|
||||
Ok(format!("{}\n{sheet}\nspent about ${:.2}", said.join("\n"), spent / 100.0))
|
||||
}
|
||||
|
||||
/// The reference sheet: the style images first, then every object's reference, labelled with its id and size.
|
||||
pub fn sheet_refs(dir: &Path, m: &Goal) -> Result<String, String> {
|
||||
let style: Vec<Tile> = m.references.iter().enumerate().map(|(i, r)| Tile { img: dir.join(r), label: format!("style {}", i + 1) }).collect();
|
||||
let refs: Vec<Tile> = m
|
||||
.objects
|
||||
.iter()
|
||||
.map(|o| {
|
||||
let size = o.h.map(|h| format!("{h} m tall")).or(o.dims.map(|d| format!("{} x {} x {} m", d[0], d[1], d[2]))).or(o.max.map(|x| format!("{x} m long"))).unwrap_or_default();
|
||||
Tile { img: refs_dir(dir).join(format!("{}.png", o.id)), label: format!("{} {size}", o.id) }
|
||||
})
|
||||
.collect();
|
||||
let mut rows = vec![style];
|
||||
rows.extend(refs.chunks(4).map(|c| c.iter().map(|t| Tile { img: t.img.clone(), label: t.label.clone() }).collect()));
|
||||
let file = dir.join("review/refs.png");
|
||||
sheet("Reference sheet: the style, then every object's reference", &rows, 320, &file)?;
|
||||
Ok(format!("wrote {}: regenerate an outlier before any 3D (raea make refs --only ID)", file.display()))
|
||||
}
|
||||
|
||||
/// The flow that sends one reference to both generators, each at its face limit.
|
||||
pub fn gen_flow(m: &Goal, o: &Object, reference: &Path, tripo: &str, meshy: &str) -> Value {
|
||||
let faces = if o.hero == Some(true) { HERO_FACES } else { PROP_FACES };
|
||||
let prompt = o.prompt.clone().unwrap_or_else(|| o.label.clone());
|
||||
let _ = m;
|
||||
json!({"flow": 1, "steps": {
|
||||
"ref": {"op": "media.load", "in": {"path": reference.display().to_string()}},
|
||||
"tripo": {"op": "mesh.generate", "model": tripo, "in": {"prompt": prompt, "image": "@ref", "x_face_limit": faces}},
|
||||
"meshy": {"op": "mesh.generate", "model": meshy, "in": {"prompt": prompt, "image": "@ref"}}
|
||||
}, "out": ["tripo", "meshy"]})
|
||||
}
|
||||
|
||||
pub fn gen_dir(dir: &Path, id: &str) -> PathBuf {
|
||||
dir.join("out/kit/gen").join(id)
|
||||
}
|
||||
|
||||
/// Every reference to both generators: out/kit/gen/ID/tripo.glb and meshy.glb.
|
||||
pub fn generate(dir: &Path, m: &Goal, only: &[String], tripo: &str, meshy: &str, dry: bool) -> Result<String, String> {
|
||||
let mut said = Vec::new();
|
||||
let mut spent = 0.0;
|
||||
for o in objects(m, only) {
|
||||
let reference = refs_dir(dir).join(format!("{}.png", o.id));
|
||||
if !reference.is_file() {
|
||||
return Err(format!("raea make gen: no reference for {} ({}): raea make refs --only {}", o.id, reference.display(), o.id));
|
||||
}
|
||||
let to = gen_dir(dir, &o.id);
|
||||
// both models already there: a rerun (after a stop, or for the pieces still missing) doesn't pay twice
|
||||
if !dry && to.join("tripo.glb").is_file() && to.join("meshy.glb").is_file() {
|
||||
said.push(format!("{}: already made ({})", o.id, to.display()));
|
||||
continue;
|
||||
}
|
||||
std::fs::create_dir_all(&to).map_err(|e| format!("{}: {e}", to.display()))?;
|
||||
if !dry {
|
||||
eprintln!("raea make gen: {} on {tripo} and {meshy} (a few minutes each)", o.id);
|
||||
}
|
||||
let flow = to.join("flow.json");
|
||||
std::fs::write(&flow, serde_json::to_string_pretty(&gen_flow(m, o, &reference, tripo, meshy)).unwrap_or_default()).map_err(|e| e.to_string())?;
|
||||
// quoted first: the run is capped at its own quote (a little over, for rounding), never gen's default cap
|
||||
let plan = raea(&["gen".into(), "plan".into(), flow.display().to_string()], &[])?;
|
||||
let out = if dry {
|
||||
plan
|
||||
} else {
|
||||
let cap = (cents(&plan) * 1.1).ceil().max(1.0) as u64;
|
||||
raea(&["gen".into(), "run".into(), flow.display().to_string(), "-o".into(), to.display().to_string(), "--max-cents".into(), cap.to_string()], &[])?
|
||||
};
|
||||
spent += cents(&out);
|
||||
said.push(if dry { format!("{}: {}", o.id, quote(&out)) } else { format!("{}: {}", o.id, to.display()) });
|
||||
}
|
||||
let tail = if dry { format!("about ${:.2} in all; nothing spent", spent / 100.0) } else { format!("spent about ${:.2}; next: raea make pick-sheet", spent / 100.0) };
|
||||
Ok(format!("{}\n{tail}", said.join("\n")))
|
||||
}
|
||||
|
||||
/// The model a pick's generator ran (from its flow.json), for the sidecar.
|
||||
fn pick_model(dir: &Path, id: &str, generator: &str) -> String {
|
||||
let flow: Option<Value> = std::fs::read_to_string(gen_dir(dir, id).join("flow.json")).ok().and_then(|t| serde_json::from_str(&t).ok());
|
||||
flow.and_then(|f| f["steps"][generator]["model"].as_str().map(String::from)).unwrap_or_else(|| generator.to_string())
|
||||
}
|
||||
|
||||
pub fn picks_file(dir: &Path) -> PathBuf {
|
||||
dir.join("out/kit/picks.json")
|
||||
}
|
||||
|
||||
/// The picks so far, by object id: {generator, why}.
|
||||
pub fn picks(dir: &Path) -> serde_json::Map<String, Value> {
|
||||
std::fs::read_to_string(picks_file(dir)).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// One object's pick and why, recorded (MK11).
|
||||
pub fn choose(dir: &Path, m: &Goal, id: &str, generator: &str, why: &str) -> Result<String, String> {
|
||||
if !m.objects.iter().any(|o| o.id == id) {
|
||||
return Err(format!("raea make pick: no object `{id}` in the plan"));
|
||||
}
|
||||
let glb = gen_dir(dir, id).join(format!("{generator}.glb"));
|
||||
if !glb.is_file() {
|
||||
return Err(format!("raea make pick: no {} (the generators are tripo and meshy: raea make gen --only {id})", glb.display()));
|
||||
}
|
||||
if why.trim().is_empty() {
|
||||
return Err("raea make pick: say why in one line (\"sharper dial numerals; Tripo fused the handset to the cradle\")".into());
|
||||
}
|
||||
let mut p = picks(dir);
|
||||
p.insert(id.into(), json!({"generator": generator, "why": why.trim()}));
|
||||
let f = picks_file(dir);
|
||||
std::fs::write(&f, serde_json::to_string_pretty(&p).unwrap_or_default()).map_err(|e| format!("{}: {e}", f.display()))?;
|
||||
Ok(format!("picked {generator} for {id}: {}", why.trim()))
|
||||
}
|
||||
|
||||
/// The triangles gen check measured.
|
||||
fn triangles(glb: &Path) -> Result<u64, String> {
|
||||
let out = raea(&["gen".into(), "check".into(), glb.display().to_string(), "--json".into()], &[]).or_else(|e| if e.contains('{') { Ok(e) } else { Err(e) })?;
|
||||
let v: Value = serde_json::from_str(out.trim()).map_err(|e| format!("gen check {}: {e}", glb.display()))?;
|
||||
v["measured"]["triangles"].as_u64().ok_or_else(|| format!("gen check couldn't read {}", glb.display()))
|
||||
}
|
||||
|
||||
/// Each pick fitted to its real size (front -Y, bottom-centre, metres) and a quarter-triangle LOD1 beside it, each
|
||||
/// with a sidecar saying how it was made (MK12).
|
||||
pub fn prep(dir: &Path, m: &Goal, only: &[String]) -> Result<String, String> {
|
||||
let p = picks(dir);
|
||||
let mut said = Vec::new();
|
||||
for o in objects(m, only) {
|
||||
let Some(pick) = p.get(&o.id) else {
|
||||
said.push(format!("{}: no pick yet (raea make pick {} tripo|meshy \"why\")", o.id, o.id));
|
||||
continue;
|
||||
};
|
||||
let generator = pick["generator"].as_str().unwrap_or("tripo");
|
||||
let src = gen_dir(dir, &o.id).join(format!("{generator}.glb"));
|
||||
let to = dir.join("out/kit").join(&o.id);
|
||||
std::fs::create_dir_all(&to).map_err(|e| format!("{}: {e}", to.display()))?;
|
||||
let full = to.join(format!("{}.glb", o.id));
|
||||
let mut args = vec!["gen".into(), "check".into(), src.display().to_string()];
|
||||
args.extend(fit_args(o, measured_size(&src)));
|
||||
args.extend(["-o".into(), full.display().to_string()]);
|
||||
// gen check exits non-zero on a finding it can't fix; the fitted copy is still written, and its findings said
|
||||
let _ = raea(&args, &[]);
|
||||
if !full.is_file() {
|
||||
return Err(format!("{}: gen check wrote no fitted copy of {}", o.id, src.display()));
|
||||
}
|
||||
let tris = triangles(&full)?;
|
||||
let lod = to.join(format!("{}_lod1.glb", o.id));
|
||||
let quarter = (tris / 4).max(500);
|
||||
let model = pick_model(dir, &o.id, generator);
|
||||
// the sidecar the Blender scripts carry along (source, licence, credit) and how it was made: ours, generated
|
||||
let made = |what: &str, tris: u64| {
|
||||
json!({"source": format!("generated by raea make: {model} from out/kit/refs/{}.png", o.id), "license": "ours (generated for this project)", "credit": "",
|
||||
"made": {"by": "raea make (docs/goal.feature)", "route": "gen", "generator": generator, "model": model, "why": pick["why"], "prompt": o.prompt, "reference": format!("out/kit/refs/{}.png", o.id),
|
||||
"style": m.style, "what": what, "triangles": tris, "source": if o.source.is_some() { json!(o.source) } else { Value::Null }}})
|
||||
};
|
||||
std::fs::write(full.with_extension("glb.json"), serde_json::to_string_pretty(&made("fitted to its real size", tris)).unwrap_or_default()).map_err(|e| e.to_string())?;
|
||||
raea(&["blender".into(), "run".into(), "blender/decimate.py".into(), full.display().to_string(), lod.display().to_string(), quarter.to_string()], &[])?;
|
||||
// decimate.py wrote the LOD's sidecar from the model's, with its step; it says what it is, over the copy
|
||||
let side = lod.with_extension("glb.json");
|
||||
let mut v: Value = std::fs::read_to_string(&side).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_else(|| made("", 0));
|
||||
v["made"] = made("LOD1: a quarter of the fitted model's triangles", quarter)["made"].clone();
|
||||
std::fs::write(&side, serde_json::to_string_pretty(&v).unwrap_or_default()).map_err(|e| e.to_string())?;
|
||||
said.push(format!("{}: {} ({tris} triangles) and its LOD1 ({quarter})", o.id, full.display()));
|
||||
}
|
||||
Ok(said.join("\n"))
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
//! The kit's sheets and its landing (docs/goal.feature MK11, MK13): the pick sheet (each object's reference beside
|
||||
//! both generators' models, each in colour and in clay, drawn in raea), and the kit landed as a component set (one
|
||||
//! component per object, its model and LOD imported beside it, so it travels as one folder), a `<Lineup>` of them all
|
||||
//! with a scale bar, a thumb each, and kit.json.
|
||||
//!
|
||||
//! raea make pick-sheet [DIR] [--only ID,...]
|
||||
//! raea make kit [DIR] [--name KIT] [--to FOLDER]
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use raea_core_brief::goal::{Goal, Object};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::kit::{gen_dir, objects, picks};
|
||||
use crate::sheet::{Tile, sheet};
|
||||
use crate::shots::raea;
|
||||
|
||||
/// The tallest side an object will have once fitted, metres (for framing it): its height, its box, or its longest side.
|
||||
pub fn tall(o: &Object) -> f64 {
|
||||
o.h.or(o.dims.map(|d| d[2])).or(o.max).unwrap_or(0.5).max(0.02)
|
||||
}
|
||||
|
||||
/// The size a model is framed to: its biggest side (a stapler is framed by its length, not its height).
|
||||
pub fn frame_size(o: &Object) -> f64 {
|
||||
o.dims.map(|[w, d, h]| w.max(d).max(h)).unwrap_or_else(|| tall(o))
|
||||
}
|
||||
|
||||
/// A composition showing one model alone, fitted (bottom-centred at the origin, metres), on a pale floor in a
|
||||
/// three-quarter view from slightly above, framed to its height.
|
||||
pub fn viewer(model: &Path, h: f64) -> String {
|
||||
let d = h * 3.2 + 0.06;
|
||||
let m = model.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_default();
|
||||
format!(
|
||||
"// written by raea make (pick sheet, kit thumbs): one model, framed to its height\nimport {{ AbsoluteFill, Composition, registerRoot }} from \"raea\";\nimport {{ Model }} from \"raea/3d\";\nimport {{ StandardMaterial }} from \"raea/pbr\";\nimport {{ Cuboid, Mesh3d }} from \"raea/mesh\";\nimport {{ AmbientLight, DirectionalLight }} from \"raea/light\";\nimport {{ Transform }} from \"raea/transform\";\nimport {{ Camera3d }} from \"raea/camera\";\nimport model from \"./{m}\";\n\nfunction View() {{\n return (\n <AbsoluteFill style={{{{ background: \"#d9d6d0\" }}}}>\n <Camera3d transform={{Transform.fromXyz({x:.3}, {y:.3}, {z:.3}).lookingAt([0, {cy:.3}, 0])}} projection={{{{ Perspective: {{ fov: (30 * Math.PI) / 180 }} }}}} />\n <AmbientLight brightness={{300}} />\n <DirectionalLight transform={{Transform.fromXyz(2, 5, 3).lookingAt([0, 0, 0])}} illuminance={{9000}} shadow_maps_enabled />\n <Mesh3d transform={{Transform.fromXyz(0, -0.005, 0)}}>\n <Cuboid half_size={{[{g:.2}, 0.005, {g:.2}]}} />\n <StandardMaterial base_color=\"#cfccc6\" perceptual_roughness={{0.95}} />\n </Mesh3d>\n <Model src={{model}} />\n </AbsoluteFill>\n );\n}}\n\nregisterRoot(() => <Composition id=\"view\" component={{View}} width={{768}} height={{768}} fps={{30}} durationInFrames={{1}} />);\n",
|
||||
x = d * 0.62,
|
||||
y = h * 0.55 + d * 0.32,
|
||||
z = d * 0.78,
|
||||
cy = h * 0.45,
|
||||
g = (h * 4.0).max(1.0),
|
||||
)
|
||||
}
|
||||
|
||||
/// One model drawn in colour and in clay: (colour.png, clay.png) beside it.
|
||||
pub fn draw(model: &Path, h: f64) -> Result<(PathBuf, PathBuf), String> {
|
||||
let dir = model.parent().ok_or("a model's folder")?;
|
||||
let stem = model.file_stem().map(|f| f.to_string_lossy().to_string()).unwrap_or_default();
|
||||
let tsx = dir.join(format!("{stem}.view.tsx"));
|
||||
std::fs::write(&tsx, viewer(model, h)).map_err(|e| format!("{}: {e}", tsx.display()))?;
|
||||
let (colour, clay) = (dir.join(format!("{stem}.colour.png")), dir.join(format!("{stem}.clay.png")));
|
||||
raea(&["render".into(), tsx.display().to_string(), "-o".into(), colour.display().to_string(), "--frame".into(), "0".into()], &[])?;
|
||||
raea(&["render".into(), tsx.display().to_string(), "-o".into(), clay.display().to_string(), "--frame".into(), "0".into(), "--clay".into()], &[])?;
|
||||
Ok((colour, clay))
|
||||
}
|
||||
|
||||
/// The pick sheet: a row an object, its reference, then each generator's model fitted to size, in colour and in clay.
|
||||
pub fn pick_sheet(dir: &Path, m: &Goal, only: &[String]) -> Result<String, String> {
|
||||
let mut rows = Vec::new();
|
||||
for o in objects(m, only) {
|
||||
let g = gen_dir(dir, &o.id);
|
||||
let mut row = vec![Tile { img: crate::kit::refs_dir(dir).join(format!("{}.png", o.id)), label: format!("{} reference", o.id) }];
|
||||
for generator in ["tripo", "meshy"] {
|
||||
let raw = g.join(format!("{generator}.glb"));
|
||||
if !raw.is_file() {
|
||||
row.push(Tile { img: g.join("none.png"), label: format!("{generator}: not made") });
|
||||
continue;
|
||||
}
|
||||
// fitted to its real size first, so both are framed alike
|
||||
let fit = g.join(format!("{generator}.fit.glb"));
|
||||
let mut args = vec!["gen".into(), "check".into(), raw.display().to_string()];
|
||||
args.extend(crate::kit::fit_args(o, crate::kit::measured_size(&raw)));
|
||||
args.extend(["-o".into(), fit.display().to_string()]);
|
||||
let _ = raea(&args, &[]);
|
||||
let shown = if fit.is_file() { fit } else { raw };
|
||||
let (colour, clay) = draw(&shown, frame_size(o))?;
|
||||
row.push(Tile { img: colour, label: generator.to_string() });
|
||||
row.push(Tile { img: clay, label: format!("{generator} clay") });
|
||||
}
|
||||
rows.push(row);
|
||||
}
|
||||
if rows.is_empty() {
|
||||
return Err("raea make pick-sheet: no objects in the plan (or none named)".into());
|
||||
}
|
||||
let file = dir.join("review/picks.png");
|
||||
sheet("Pick sheet: reference | Tripo | Tripo clay | Meshy | Meshy clay", &rows, 300, &file)?;
|
||||
Ok(format!("wrote {}: judge each on its clay (fused parts, blobs, fidelity to the reference), then: raea make pick ID tripo|meshy \"why\"", file.display()))
|
||||
}
|
||||
|
||||
/// A component's name from an object id: rotary_phone -> RotaryPhone.
|
||||
pub fn component_name(id: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for w in id.split(['_', '-']) {
|
||||
let mut c = w.chars();
|
||||
out.extend(c.next().into_iter().flat_map(char::to_uppercase).chain(c));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One object's component: its model imported beside it, its LOD for far away, placed by the props a composition gives.
|
||||
pub fn component(o: &Object, why: &str) -> String {
|
||||
let n = component_name(&o.id);
|
||||
format!(
|
||||
"// raea make component add: {label}, {h} m, from the kit's style (raea make kit; {why})\nimport {{ Model }} from \"raea/3d\";\nimport full from \"./{id}.glb\";\nimport far from \"./{id}_lod1.glb\";\n\ntype Props = {{\n position?: [number, number, number];\n rotation?: [number, number, number];\n /** the quarter-triangle model, for when it's small on screen */\n lod?: boolean;\n}};\n\n/** {label}: fitted to its real size, its bottom at the origin, its front toward +z. */\nexport default function {n}({{ position = [0, 0, 0], rotation = [0, 0, 0], lod = false }}: Props) {{\n return <Model src={{lod ? far : full}} position={{position}} rotation={{rotation}} />;\n}}\n",
|
||||
label = o.label,
|
||||
h = tall(o),
|
||||
id = o.id,
|
||||
why = why.replace('\n', " "),
|
||||
)
|
||||
}
|
||||
|
||||
/// The lineup: every component side by side in the plan's order, gaps between, a label each lying in front of the pieces and a
|
||||
/// scale bar (the longest round length the set covers), seen from a little right of centre and above.
|
||||
pub fn lineup(m: &Goal, kit: &str) -> String {
|
||||
let mut imports = String::new();
|
||||
let mut parts = String::new();
|
||||
let mut x = 0.0;
|
||||
let foot = |o: &Object| o.dims.map(|d| (d[0], d[1])).unwrap_or((tall(o) * 0.8, tall(o) * 0.8));
|
||||
let widths: Vec<f64> = m.objects.iter().map(|o| foot(o).0).collect();
|
||||
let gap = (widths.iter().cloned().fold(0.0, f64::max) * 0.6).clamp(0.03, 0.3);
|
||||
let total: f64 = widths.iter().sum::<f64>() + gap * (m.objects.len().saturating_sub(1)) as f64;
|
||||
let highest = m.objects.iter().map(tall).fold(0.02, f64::max);
|
||||
let deepest = m.objects.iter().map(|o| foot(o).1).fold(0.02, f64::max);
|
||||
// labels lie on the floor in front of every piece, so none hides one; the bar in front of them
|
||||
let fs = (total * 0.035).clamp(0.01, 0.06);
|
||||
let lz = deepest / 2.0 + fs * 1.9;
|
||||
let (bar, bar_label) = scale_bar(total);
|
||||
let bz = lz + fs * 2.8;
|
||||
for (o, w) in m.objects.iter().zip(&widths) {
|
||||
let n = component_name(&o.id);
|
||||
imports.push_str(&format!("import {n} from \"./{n}\";\n"));
|
||||
let cx = x + w / 2.0 - total / 2.0;
|
||||
parts.push_str(&format!(" <{n} position={{[{cx:.3}, 0, 0]}} />\n <Mesh3d transform={{Transform.fromXyz({cx:.3}, 0.002, {lz:.3}).withRotation(FLAT)}}>\n <Text3D size={{{fs:.3}}} depth={{0.001}} read={{false}}>{{{label:?}}}</Text3D>\n <StandardMaterial base_color=\"#2a2a2a\" />\n </Mesh3d>\n", label = o.label));
|
||||
x += w + gap;
|
||||
}
|
||||
// framed to the set: wide enough for every piece, tall enough for the highest and the bar in front, from a little
|
||||
// to the right and above, so a long piece shows its length
|
||||
let d = (total * 1.45).max(highest * 4.2).max(bz * 3.0).max(0.35);
|
||||
let (cx, cy, cz) = (d * 0.34, highest * 0.5 + d * 0.36, d * 0.88 + bz * 0.5);
|
||||
format!(
|
||||
"// raea make kit: the {kit} kit's lineup, every piece at its real size beside a {bar_label} bar (the kit's cover)\nimport {{ AbsoluteFill, Composition, registerRoot }} from \"raea\";\nimport {{ Text3D }} from \"raea/3d\";\nimport {{ StandardMaterial }} from \"raea/pbr\";\nimport {{ Cuboid, Mesh3d }} from \"raea/mesh\";\nimport {{ AmbientLight, DirectionalLight }} from \"raea/light\";\nimport {{ Transform }} from \"raea/transform\";\nimport {{ Camera3d }} from \"raea/camera\";\n{imports}\n// lying flat on the floor, reading toward the camera\nconst FLAT: [number, number, number, number] = [-0.7071068, 0, 0, 0.7071068];\n\nexport function Lineup() {{\n return (\n <AbsoluteFill style={{{{ background: \"#d6d2ca\" }}}}>\n <Camera3d transform={{Transform.fromXyz({cx:.3}, {cy:.3}, {cz:.3}).lookingAt([0, {ty:.3}, {tz:.3}])}} projection={{{{ Perspective: {{ fov: (30 * Math.PI) / 180 }} }}}} />\n <AmbientLight brightness={{300}} />\n <DirectionalLight transform={{Transform.fromXyz(2, 6, 4).lookingAt([0, 0, 0])}} illuminance={{9000}} shadow_maps_enabled />\n <Mesh3d transform={{Transform.fromXyz(0, -0.005, 0)}}>\n <Cuboid half_size={{[{g:.2}, 0.005, {g:.2}]}} />\n <StandardMaterial base_color=\"#d6d2ca\" perceptual_roughness={{0.95}} />\n </Mesh3d>\n <Mesh3d transform={{Transform.fromXyz({bx:.3}, 0.002, {bz:.3})}}>\n <Cuboid half_size={{[{bh:.3}, 0.002, {bt:.4}]}} />\n <StandardMaterial base_color=\"#202020\" />\n </Mesh3d>\n <Mesh3d transform={{Transform.fromXyz({bx:.3}, 0.002, {blz:.3}).withRotation(FLAT)}}>\n <Text3D size={{{fs:.3}}} depth={{0.001}} read={{false}}>{bar_label}</Text3D>\n <StandardMaterial base_color=\"#202020\" />\n </Mesh3d>\n{parts} </AbsoluteFill>\n );\n}}\n\nregisterRoot(() => <Composition id=\"lineup\" component={{Lineup}} width={{1920}} height={{1080}} fps={{30}} durationInFrames={{1}} />);\n",
|
||||
ty = highest * 0.35,
|
||||
tz = bz * 0.45,
|
||||
// a floor past every edge of the frame (the review's views leave a ground slab out of their framing)
|
||||
g = (total * 3.0).max(2.0),
|
||||
bh = bar / 2.0,
|
||||
bt = fs * 0.25,
|
||||
bx = -total / 2.0 + bar / 2.0,
|
||||
blz = bz + fs * 1.3,
|
||||
)
|
||||
}
|
||||
|
||||
/// The scale bar for a set this wide: the longest round length that fits under it, and its label.
|
||||
pub fn scale_bar(width: f64) -> (f64, &'static str) {
|
||||
[(1.0, "1 m"), (0.5, "50 cm"), (0.25, "25 cm"), (0.1, "10 cm"), (0.05, "5 cm")].into_iter().find(|(l, _)| *l <= width.max(0.05)).unwrap_or((0.05, "5 cm"))
|
||||
}
|
||||
|
||||
/// Where a kit lands: `--to`, else the workspace's shared/components/KIT (every project imports it as
|
||||
/// @shared/components/KIT), else the project's components/KIT.
|
||||
pub fn kit_dir(dir: &Path, kit: &str, to: Option<&str>) -> PathBuf {
|
||||
if let Some(t) = to {
|
||||
return PathBuf::from(t);
|
||||
}
|
||||
if let Some(ws) = raea_core_facts::record::up(dir, ".raea/workspace") {
|
||||
let shared = if !ws.join("shared").is_dir() && ws.join("components").is_dir() { ws.join("components") } else { ws.join("shared/components") };
|
||||
return shared.join(kit);
|
||||
}
|
||||
let project = raea_core_facts::record::up(dir, ".raea/project").unwrap_or_else(|| dir.to_path_buf());
|
||||
project.join("components").join(kit)
|
||||
}
|
||||
|
||||
fn copy(a: &Path, b: &Path) -> Result<(), String> {
|
||||
match std::fs::copy(a, b) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(e) => Err(format!("{} -> {}: {e}", a.display(), b.display())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The kit landed: each prepped object's model, LOD and sidecars, its component and thumb; the lineup and its cover
|
||||
/// render; kit.json. Objects not prepped yet are named, not skipped silently.
|
||||
pub fn land(dir: &Path, m: &Goal, name: Option<&str>, to: Option<&str>) -> Result<String, String> {
|
||||
let kit = name.map(str::to_string).unwrap_or_else(|| dir.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or("kit".into()));
|
||||
let dest = kit_dir(dir, &kit, to);
|
||||
std::fs::create_dir_all(dest.join("thumbs")).map_err(|e| format!("{}: {e}", dest.display()))?;
|
||||
let p = picks(dir);
|
||||
let (mut items, mut missing) = (Vec::new(), Vec::new());
|
||||
for o in &m.objects {
|
||||
let from = dir.join("out/kit").join(&o.id);
|
||||
let (full, lod) = (from.join(format!("{}.glb", o.id)), from.join(format!("{}_lod1.glb", o.id)));
|
||||
if !full.is_file() || !lod.is_file() {
|
||||
missing.push(o.id.clone());
|
||||
continue;
|
||||
}
|
||||
for f in [&full, &lod] {
|
||||
let name = f.file_name().unwrap();
|
||||
copy(f, &dest.join(name))?;
|
||||
let side = f.with_extension("glb.json");
|
||||
if side.is_file() {
|
||||
copy(&side, &dest.join(format!("{}.json", name.to_string_lossy())))?;
|
||||
}
|
||||
}
|
||||
let why = p.get(&o.id).and_then(|v| v["why"].as_str()).unwrap_or("");
|
||||
let n = component_name(&o.id);
|
||||
std::fs::write(dest.join(format!("{n}.tsx")), component(o, why)).map_err(|e| e.to_string())?;
|
||||
let (colour, _) = draw(&full, frame_size(o))?;
|
||||
copy(&colour, &dest.join("thumbs").join(format!("{}.png", o.id)))?;
|
||||
std::fs::create_dir_all(dir.join("out/kit/thumbs")).map_err(|e| e.to_string())?;
|
||||
copy(&colour, &dir.join("out/kit/thumbs").join(format!("{}.png", o.id)))?;
|
||||
items.push(json!({"id": o.id, "label": o.label, "component": format!("{n}.tsx"), "model": format!("{}.glb", o.id), "lod1": format!("{}_lod1.glb", o.id),
|
||||
"thumb": format!("thumbs/{}.png", o.id), "h": tall(o), "pick": p.get(&o.id).cloned().unwrap_or(Value::Null)}));
|
||||
}
|
||||
if !missing.is_empty() {
|
||||
return Err(format!("raea make kit: not prepped yet: {} (raea make prep --only {})", missing.join(", "), missing.join(",")));
|
||||
}
|
||||
let lineup_tsx = dest.join("lineup.tsx");
|
||||
std::fs::write(&lineup_tsx, lineup(m, &kit)).map_err(|e| e.to_string())?;
|
||||
let cover = dest.join("cover.png");
|
||||
raea(&["render".into(), lineup_tsx.display().to_string(), "-o".into(), cover.display().to_string(), "--frame".into(), "0".into()], &[])?;
|
||||
let doc = json!({"kit": kit, "style": m.style, "references": m.references, "items": items, "lineup": "lineup.tsx", "cover": "cover.png", "landed": dest.display().to_string(), "made": {"by": "raea make kit (docs/goal.feature MK13)"}});
|
||||
let text = serde_json::to_string_pretty(&doc).unwrap_or_default();
|
||||
std::fs::write(dest.join("kit.json"), &text).map_err(|e| e.to_string())?;
|
||||
// the job's own record of it, what raea/goal's deliverables pack counts
|
||||
std::fs::write(dir.join("out/kit/kit.json"), &text).map_err(|e| e.to_string())?;
|
||||
copy(&cover, &dir.join("out/kit/lineup.png"))?;
|
||||
Ok(format!("landed the {kit} kit ({} pieces) in {}: components, lineup.tsx, cover.png, thumbs/, kit.json", items.len(), dest.display()))
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
//! 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). The loop itself, every rule at its moments, is TypeScript:
|
||||
//! `raea check` and `raea goal tasks` run sdk/goal/src/run.ts (engine/cli verbs.rs goal_ts).
|
||||
//!
|
||||
//! raea make blockout|refs|sheet refs|gen|pick-sheet|pick|prep|kit|framing|lenschart ... (the steps, USAGE)
|
||||
|
||||
pub mod floor;
|
||||
pub mod kit;
|
||||
pub mod kitout;
|
||||
pub mod sheet;
|
||||
pub mod shots;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use raea_core_brief::goal::Goal;
|
||||
use serde_json::Value;
|
||||
|
||||
pub const USAGE: &str = "raea make place FILE [--at S[,S...]] [--box WxH] (the clearest places in a shot for a text box that size, in a 1080-wide frame)
|
||||
raea make blockout [DIR] [--no-review] (a scene's blockout stop: review/plan/floor-plan.png, a grey-box blockout from the entrance and its review sheets, comparison.png beside reference 0)
|
||||
raea make refs [DIR] [--only ID,...] [--model M] [--dry] (a kit: every object's reference from the style images, in the plan's style, then review/refs.png; --dry quotes it)
|
||||
raea make sheet refs [DIR] (review/refs.png again: the style images, then every reference)
|
||||
raea make gen [DIR] [--only ID,...] [--tripo M] [--meshy M] [--dry] (each reference to both generators, Tripo H3.1 and Meshy on fal: out/kit/gen/ID/)
|
||||
raea make pick-sheet [DIR] [--only ID,...] (review/picks.png: reference | Tripo | Tripo clay | Meshy | Meshy clay, fitted to size)
|
||||
raea make pick ID tripo|meshy \"why\" [DIR] (the pick and its reason, out/kit/picks.json)
|
||||
raea make prep [DIR] [--only ID,...] (each pick fitted to its real size, a quarter-triangle _lod1 beside it, .glb.json sidecars)
|
||||
raea make kit [DIR] [--name KIT] [--to FOLDER] (the kit as a component set: shared/components/KIT, lineup.tsx, cover.png, thumbs, kit.json)
|
||||
raea make framing [DIR] [--only NAME,...] [--out DIR] (a shot list: each shot's first, middle and last frame on framing.png, stamped)
|
||||
raea make lenschart SHOT [DIR] [--out DIR] (a shot's first frame at 18, 24, 35, 50, 85 and 135 mm on lens-SHOT.png)";
|
||||
|
||||
/// The brief.ts the job is read from: DIR's own, else the nearest above it inside its raea project.
|
||||
pub fn brief_path(dir: &Path) -> Option<PathBuf> {
|
||||
let dir = dunce::canonicalize(dir).ok()?;
|
||||
let project = raea_core_facts::record::up(&dir, ".raea/project");
|
||||
for d in dir.ancestors() {
|
||||
let p = d.join("brief.ts");
|
||||
if p.is_file() {
|
||||
return Some(p);
|
||||
}
|
||||
if project.as_deref() == Some(d) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether a brief.ts has a goal at all, read from its words: cheap enough for a hook at every turn's end, so the
|
||||
/// module is only evaluated when it can matter.
|
||||
pub fn has_goal(brief: &Path) -> bool {
|
||||
std::fs::read_to_string(brief).is_ok_and(|t| t.contains("goal:") || t.contains("goal :"))
|
||||
}
|
||||
|
||||
/// The goals of brief.ts, evaluated by `raea spec FILE --as brief` (the module runs; Rust checks it against core/brief).
|
||||
pub fn read_goals(brief: &Path) -> Result<Vec<Goal>, String> {
|
||||
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
let out = std::process::Command::new(exe).arg("spec").arg(brief).args(["--as", "brief"]).env("RAEA_RECORD", "off").output().map_err(|e| e.to_string())?;
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
let start = text.find('{').ok_or_else(|| format!("{} didn't read as a brief: {}", brief.display(), why_refused(&out)))?;
|
||||
let v: Value = serde_json::from_str(&text[start..]).map_err(|e| format!("{}: {e}", brief.display()))?;
|
||||
let b = v.get("brief").cloned().unwrap_or(v);
|
||||
match b.get("goal") {
|
||||
None | Some(Value::Null) => Ok(vec![]),
|
||||
Some(g) => {
|
||||
let gs: raea_core_brief::goal::Goals = serde_json::from_value(g.clone()).map_err(|e| format!("{}: goal: {e}", brief.display()))?;
|
||||
Ok(gs.all().into_iter().cloned().collect())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a raea that ran printed no answer: its last line said (a refusal's word taken off), else that it printed nothing.
|
||||
fn why_refused(out: &std::process::Output) -> String {
|
||||
let last = |b: &[u8]| String::from_utf8_lossy(b).lines().rev().find(|l| !l.trim().is_empty()).map(|l| l.trim().trim_start_matches("REFUSED").trim().to_string());
|
||||
last(&out.stderr).or_else(|| last(&out.stdout)).unwrap_or_else(|| "raea spec printed nothing".into())
|
||||
}
|
||||
|
||||
/// The scene, kit or shot goal the asset tools build to: the one named, else the only one of those kinds.
|
||||
pub fn read_goal(brief: &Path) -> Result<Option<Goal>, String> {
|
||||
read_goal_named(brief, None)
|
||||
}
|
||||
|
||||
pub fn read_goal_named(brief: &Path, name: Option<&str>) -> Result<Option<Goal>, String> {
|
||||
use raea_core_brief::goal::{name_of, Kind};
|
||||
let all = read_goals(brief)?;
|
||||
if let Some(n) = name {
|
||||
return all.into_iter().find(|g| name_of(g) == n).map(Some).ok_or_else(|| format!("{}: no goal is named {n}", brief.display()));
|
||||
}
|
||||
let mut built: Vec<Goal> = all.into_iter().filter(|g| matches!(g.kind, Kind::Scene | Kind::Kit | Kind::Shot)).collect();
|
||||
match built.len() {
|
||||
0 => Ok(None),
|
||||
1 => Ok(built.pop()),
|
||||
_ => Err(format!("{}: several scene, kit or shot goals ({}): name one with --goal", brief.display(), built.iter().map(name_of).collect::<Vec<_>>().join(", "))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The flags that take a value: what follows them isn't a positional argument.
|
||||
const VALUED: [&str; 8] = ["--only", "--model", "--tripo", "--meshy", "--name", "--to", "--out", "--goal"];
|
||||
|
||||
fn flag<'a>(args: &'a [String], k: &str) -> Option<&'a str> {
|
||||
args.iter().position(|a| a == k).and_then(|i| args.get(i + 1)).map(String::as_str)
|
||||
}
|
||||
|
||||
/// The positional arguments after the verb (words), flags and their values left out.
|
||||
pub fn positional(args: &[String], skip: usize) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut i = skip;
|
||||
while i < args.len() {
|
||||
if VALUED.contains(&args[i].as_str()) {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if !args[i].starts_with("--") {
|
||||
out.push(args[i].clone());
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A flag's comma list (`--only a,b`), empty when it isn't given.
|
||||
fn list(args: &[String], k: &str) -> Vec<String> {
|
||||
let Some(v) = flag(args, k) else { return vec![] };
|
||||
v.split(',').map(str::trim).filter(|s| !s.is_empty()).map(String::from).collect()
|
||||
}
|
||||
|
||||
/// What `--only` names of a list (all of it when it names nothing), each item known by `name`.
|
||||
pub(crate) fn only<'a, T>(all: &'a [T], only: &[String], name: impl Fn(&T) -> &str) -> Vec<&'a T> {
|
||||
all.iter().filter(|t| only.is_empty() || only.iter().any(|n| n.as_str() == name(t))).collect()
|
||||
}
|
||||
|
||||
/// The job's brief and plan from a folder.
|
||||
fn job(dir: &Path, name: Option<&str>) -> Result<(PathBuf, Goal), String> {
|
||||
let brief = brief_path(dir).ok_or_else(|| format!("no brief.ts at or above {} in its project", dir.display()))?;
|
||||
let goal = read_goal_named(&brief, name)?.ok_or_else(|| format!("{} has no scene, kit or shot goal (`goal: scene({{...}})`, kit() or shot() from raea/brief)", brief.display()))?;
|
||||
Ok((brief, goal))
|
||||
}
|
||||
|
||||
/// The steps: each reads the plan from DIR's brief.ts and works beside it.
|
||||
fn step(verb: &str, args: &[String]) -> Result<String, String> {
|
||||
let skip = if verb == "sheet" { 3 } else { 2 };
|
||||
let pos = positional(args, skip);
|
||||
let (words, dir_at) = match verb {
|
||||
"pick" => (3, 3),
|
||||
"lenschart" => (1, 1),
|
||||
_ => (0, 0),
|
||||
};
|
||||
if pos.len() < words {
|
||||
return Err(USAGE.into());
|
||||
}
|
||||
let dir = pos.get(dir_at).map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."));
|
||||
let (brief, m) = job(&dir, flag(args, "--goal"))?;
|
||||
let here = brief.parent().unwrap_or(Path::new(".")).to_path_buf();
|
||||
let only = list(args, "--only");
|
||||
let dry = args.iter().any(|a| a == "--dry");
|
||||
let out_or = |d: PathBuf| flag(args, "--out").map(PathBuf::from).unwrap_or(d);
|
||||
match verb {
|
||||
"blockout" => floor::draw_plan(&here, &m, !args.iter().any(|a| a == "--no-review")),
|
||||
"refs" => kit::refs(&here, &m, &only, flag(args, "--model"), dry),
|
||||
"sheet" => match args.get(2).map(String::as_str) {
|
||||
Some("refs") => kit::sheet_refs(&here, &m),
|
||||
Some("picks") => kitout::pick_sheet(&here, &m, &only),
|
||||
Some("framing") => shots::framing(&here, &m, &only, &out_or(here.join("review"))),
|
||||
_ => Err("raea make sheet refs|picks|framing [DIR]".into()),
|
||||
},
|
||||
"gen" => kit::generate(&here, &m, &only, flag(args, "--tripo").unwrap_or(kit::TRIPO), flag(args, "--meshy").unwrap_or(kit::MESHY), dry),
|
||||
"pick-sheet" => kitout::pick_sheet(&here, &m, &only),
|
||||
"pick" => kit::choose(&here, &m, &pos[0], &pos[1], &pos[2]),
|
||||
"prep" => kit::prep(&here, &m, &only),
|
||||
"kit" => kitout::land(&here, &m, flag(args, "--name"), flag(args, "--to")),
|
||||
"framing" => shots::framing(&here, &m, &only, &out_or(here.join("review"))),
|
||||
"lenschart" => shots::lenschart(&here, &m, &pos[0], &out_or(here.join("review"))),
|
||||
_ => Err(USAGE.into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
match args.get(1).map(String::as_str) {
|
||||
Some(v @ ("blockout" | "refs" | "sheet" | "gen" | "pick-sheet" | "pick" | "prep" | "kit" | "framing" | "lenschart")) => step(v, args),
|
||||
_ => Err(USAGE.into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_steps;
|
||||
@@ -0,0 +1,96 @@
|
||||
//! The contact sheets a person looks at (docs/goal.feature MK10, MK11, MK15): pictures in rows, each labelled under it,
|
||||
//! a title over them, on one PNG read at once. Labels are drawn by resvg in the system's own fonts; an SVG drawn whole
|
||||
//! (the floor plan, MK18) goes through `svg_png`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
use image::{Rgba, RgbaImage, imageops};
|
||||
use resvg::{tiny_skia, usvg};
|
||||
|
||||
/// One picture on a sheet and what it is.
|
||||
pub struct Tile {
|
||||
pub img: PathBuf,
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
const LABEL_H: u32 = 30;
|
||||
const TITLE_H: u32 = 44;
|
||||
const GAP: u32 = 6;
|
||||
|
||||
fn options() -> usvg::Options<'static> {
|
||||
static DB: OnceLock<Arc<usvg::fontdb::Database>> = OnceLock::new();
|
||||
let db = DB.get_or_init(|| {
|
||||
let mut db = usvg::fontdb::Database::new();
|
||||
db.load_system_fonts();
|
||||
Arc::new(db)
|
||||
});
|
||||
usvg::Options { fontdb: db.clone(), font_family: "Helvetica".into(), ..usvg::Options::default() }
|
||||
}
|
||||
|
||||
/// SVG text escaped.
|
||||
pub fn esc(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'&' => out.push_str("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// An SVG document drawn at its own size.
|
||||
pub fn svg_png(svg: &str) -> Result<RgbaImage, String> {
|
||||
let tree = usvg::Tree::from_str(svg, &options()).map_err(|e| format!("svg: {e}"))?;
|
||||
let size = tree.size().to_int_size();
|
||||
let mut pix = tiny_skia::Pixmap::new(size.width(), size.height()).ok_or("svg: empty size")?;
|
||||
resvg::render(&tree, tiny_skia::Transform::default(), &mut pix.as_mut());
|
||||
// tiny-skia keeps premultiplied alpha; image wants it straight
|
||||
let mut img = RgbaImage::new(size.width(), size.height());
|
||||
for (p, c) in img.pixels_mut().zip(pix.pixels()) {
|
||||
let d = c.demultiply();
|
||||
*p = Rgba([d.red(), d.green(), d.blue(), d.alpha()]);
|
||||
}
|
||||
Ok(img)
|
||||
}
|
||||
|
||||
/// Rows of tiles, each `tile_w` wide (its height from the first picture's shape; any other shape fitted inside it), a label under each and the title
|
||||
/// over them all, written to `out`. A tile whose picture won't open is drawn grey, its label saying so.
|
||||
pub fn sheet(title: &str, rows: &[Vec<Tile>], tile_w: u32, out: &Path) -> Result<(), String> {
|
||||
let first = rows.iter().flatten().find_map(|t| image::open(&t.img).ok()).ok_or_else(|| format!("{title}: no picture to put on the sheet"))?;
|
||||
let th = ((tile_w as f64) * first.height() as f64 / first.width().max(1) as f64).round().max(1.0) as u32;
|
||||
let cols = rows.iter().map(Vec::len).max().unwrap_or(1).max(1) as u32;
|
||||
let (w, h) = (GAP + cols * (tile_w + GAP), TITLE_H + rows.len() as u32 * (th + LABEL_H + GAP));
|
||||
let mut img = RgbaImage::from_pixel(w, h, Rgba([18, 18, 20, 255]));
|
||||
let mut text = format!("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{w}\" height=\"{h}\"><text x=\"{GAP}\" y=\"30\" font-size=\"22\" font-weight=\"bold\" fill=\"#ffffff\">{}</text>", esc(title));
|
||||
for (r, row) in rows.iter().enumerate() {
|
||||
for (c, t) in row.iter().enumerate() {
|
||||
let (x, y) = (GAP + c as u32 * (tile_w + GAP), TITLE_H + r as u32 * (th + LABEL_H + GAP));
|
||||
let label = match image::open(&t.img) {
|
||||
Ok(p) => {
|
||||
// fitted inside the tile, its own shape kept, centred
|
||||
let k = (tile_w as f64 / p.width().max(1) as f64).min(th as f64 / p.height().max(1) as f64);
|
||||
let (pw, ph) = (((p.width() as f64 * k).round() as u32).max(1), ((p.height() as f64 * k).round() as u32).max(1));
|
||||
let small = imageops::resize(&p.to_rgba8(), pw, ph, imageops::FilterType::Triangle);
|
||||
imageops::overlay(&mut img, &small, (x + (tile_w - pw.min(tile_w)) / 2) as i64, (y + (th - ph.min(th)) / 2) as i64);
|
||||
t.label.clone()
|
||||
}
|
||||
Err(_) => {
|
||||
imageops::overlay(&mut img, &RgbaImage::from_pixel(tile_w, th, Rgba([70, 70, 70, 255])), x as i64, y as i64);
|
||||
format!("{} (missing)", t.label)
|
||||
}
|
||||
};
|
||||
text.push_str(&format!("<text x=\"{}\" y=\"{}\" font-size=\"17\" fill=\"#e8e8e8\">{}</text>", x + 4, y + th + 21, esc(&label)));
|
||||
}
|
||||
}
|
||||
text.push_str("</svg>");
|
||||
imageops::overlay(&mut img, &svg_png(&text)?, 0, 0);
|
||||
if let Some(d) = out.parent() {
|
||||
std::fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?;
|
||||
}
|
||||
img.save(out).map_err(|e| format!("{}: {e}", out.display()))
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
//! 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 sees every shot's
|
||||
//! start and end at once; `raea make lenschart SHOT` renders a shot's first frame at 18, 24, 35, 50, 85 and 135 mm
|
||||
//! (RAEA_LENS, core/review) to choose its lens before it's moved.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use raea_core_brief::goal::{Goal, Shot};
|
||||
|
||||
use crate::sheet::{Tile, sheet};
|
||||
|
||||
/// The focal lengths a lens chart shows.
|
||||
pub const LENSES: [u32; 6] = [18, 24, 35, 50, 85, 135];
|
||||
|
||||
/// raea itself, run on `args` with `env`: its output, or what it said when it failed.
|
||||
pub fn raea(args: &[String], env: &[(&str, String)]) -> Result<String, String> {
|
||||
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
let mut c = std::process::Command::new(exe);
|
||||
c.args(args);
|
||||
for (k, v) in env {
|
||||
c.env(k, v);
|
||||
}
|
||||
// stderr passes through as it comes (a generation's progress, a render's frames), so whoever watches sees it
|
||||
// working, and is kept for the error
|
||||
let mut child = c.stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()).spawn().map_err(|e| e.to_string())?;
|
||||
let err = child.stderr.take().map(|e| {
|
||||
std::thread::spawn(move || {
|
||||
use std::io::BufRead;
|
||||
let mut kept = Vec::new();
|
||||
for line in std::io::BufReader::new(e).lines().map_while(Result::ok) {
|
||||
eprintln!(" {line}");
|
||||
kept.push(line);
|
||||
}
|
||||
kept
|
||||
})
|
||||
});
|
||||
let out = child.wait_with_output().map_err(|e| e.to_string())?;
|
||||
let err = err.and_then(|t| t.join().ok()).unwrap_or_default();
|
||||
let text = String::from_utf8_lossy(&out.stdout).to_string();
|
||||
if out.status.success() {
|
||||
Ok(text)
|
||||
} else {
|
||||
Err(format!("raea {}: {}", args.first().map(String::as_str).unwrap_or(""), err.iter().rev().find(|l| !l.trim().is_empty()).map_or(text.trim(), String::as_str)))
|
||||
}
|
||||
}
|
||||
|
||||
/// A shot's frames: its first, middle and last, from its seconds at its frame rate.
|
||||
pub fn frames_of(s: &Shot) -> Vec<i64> {
|
||||
let n = ((s.seconds.unwrap_or(0.0) * s.fps.unwrap_or(30.0)).round() as i64).max(1);
|
||||
if s.still == Some(true) || n == 1 {
|
||||
return vec![0];
|
||||
}
|
||||
let mut v = vec![0, (n - 1) / 2, n - 1];
|
||||
v.dedup();
|
||||
v
|
||||
}
|
||||
|
||||
fn composition(dir: &Path, s: &Shot) -> Result<PathBuf, String> {
|
||||
let c = s.composition.as_deref().ok_or_else(|| format!("shot `{}` has no composition (the .tsx that renders it)", s.name))?;
|
||||
Ok(dir.join(c))
|
||||
}
|
||||
|
||||
/// The framing sheet of the plan's shots (or those named in `only`), written to `out` (OUT/framing.png).
|
||||
pub fn framing(dir: &Path, m: &Goal, only: &[String], out: &Path) -> Result<String, String> {
|
||||
let shots: Vec<&Shot> = crate::only(&m.shots, only, |s| s.name.as_str());
|
||||
if shots.is_empty() {
|
||||
return Err("raea make framing: no shots in the plan (or none named)".into());
|
||||
}
|
||||
let work = out.join("framing-frames");
|
||||
let mut rows = Vec::new();
|
||||
for s in &shots {
|
||||
let tsx = composition(dir, s)?;
|
||||
let fr = frames_of(s);
|
||||
let to = work.join(&s.name);
|
||||
let _ = std::fs::remove_dir_all(&to);
|
||||
std::fs::create_dir_all(&to).map_err(|e| format!("{}: {e}", to.display()))?;
|
||||
let at = fr.iter().map(|f| f.to_string()).collect::<Vec<_>>().join(",");
|
||||
raea(&["render".into(), tsx.display().to_string(), "-o".into(), to.display().to_string(), "--at".into(), at], &[])?;
|
||||
let fps = s.fps.unwrap_or(30.0);
|
||||
rows.push(fr.iter().enumerate().map(|(i, f)| Tile { img: to.join(format!("frame-{i:05}.png")), label: format!("{} t={:.1}s (frame {f})", s.name, *f as f64 / fps) }).collect());
|
||||
}
|
||||
let file = out.join("framing.png");
|
||||
sheet("Framing: each shot's first, middle and last frame", &rows, 480, &file)?;
|
||||
Ok(format!("wrote {} ({} shot{})", file.display(), shots.len(), if shots.len() == 1 { "" } else { "s" }))
|
||||
}
|
||||
|
||||
/// One shot's first frame at every lens of the chart, on one sheet (OUT/lens-SHOT.png).
|
||||
pub fn lenschart(dir: &Path, m: &Goal, name: &str, out: &Path) -> Result<String, String> {
|
||||
let s = m.shots.iter().find(|s| s.name == name).ok_or_else(|| format!("raea make lenschart: no shot `{name}` in the plan"))?;
|
||||
let tsx = composition(dir, s)?;
|
||||
let work = out.join("lens-frames").join(name);
|
||||
std::fs::create_dir_all(&work).map_err(|e| format!("{}: {e}", work.display()))?;
|
||||
let mut tiles = Vec::new();
|
||||
for mm in LENSES {
|
||||
let png = work.join(format!("{mm}mm.png"));
|
||||
raea(&["render".into(), tsx.display().to_string(), "-o".into(), png.display().to_string(), "--frame".into(), "0".into()], &[("RAEA_LENS", mm.to_string())])?;
|
||||
tiles.push(Tile { img: png, label: format!("{mm} mm ({:.0}° vertical)", raea_core_review::fov_of_lens(mm as f64)) });
|
||||
}
|
||||
let rows: Vec<Vec<Tile>> = {
|
||||
let mut it = tiles.into_iter();
|
||||
vec![it.by_ref().take(3).collect(), it.collect()]
|
||||
};
|
||||
let file = out.join(format!("lens-{name}.png"));
|
||||
sheet(&format!("Lens chart: {name}, its first frame"), &rows, 480, &file)?;
|
||||
Ok(format!("wrote {}: pick the lens, then set the shot's `lens` (raea/camera lens(mm) for its fov)", file.display()))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
//! The steps' own work, without a render or a paid call: sheets, prompts, flows, picks, components, the floor plan.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use image::{Rgba, RgbaImage};
|
||||
use raea_core_brief::{goal::Goal as Make, read};
|
||||
|
||||
use crate::sheet::{Tile, sheet};
|
||||
|
||||
fn dir(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("raea-make-steps-{name}-{}", std::process::id()));
|
||||
std::fs::remove_dir_all(&d).ok();
|
||||
std::fs::create_dir_all(&d).expect("a scratch folder");
|
||||
d
|
||||
}
|
||||
|
||||
fn png(p: &PathBuf, w: u32, h: u32, c: [u8; 3]) {
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
RgbaImage::from_pixel(w, h, Rgba([c[0], c[1], c[2], 255])).save(p).unwrap();
|
||||
}
|
||||
|
||||
fn kit() -> Make {
|
||||
read("make", r#"{"kind": "kit", "references": ["media/style.png"], "style": "1970s flight desk, cream enamel, maker Aurora Instruments.", "objects": [
|
||||
{"id": "rotary_phone", "label": "Rotary phone", "h": 0.12, "prompt": "a rotary desk phone, worn bakelite", "hero": true},
|
||||
{"id": "clock", "label": "Wall clock", "dims": [0.3, 0.05, 0.3]}]}"#)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
// MK10, MK11, MK15: a sheet is its tiles in rows, labelled, any shape fitted without stretching, a missing one grey
|
||||
#[test]
|
||||
fn a_sheet_holds_its_tiles_in_rows_with_labels() {
|
||||
let d = dir("sheet");
|
||||
let (a, b, wide) = (d.join("a.png"), d.join("b.png"), d.join("wide.png"));
|
||||
png(&a, 200, 100, [200, 30, 30]);
|
||||
png(&b, 200, 100, [30, 200, 30]);
|
||||
png(&wide, 400, 100, [30, 30, 200]);
|
||||
let out = d.join("review/sheet.png");
|
||||
let rows = vec![
|
||||
vec![Tile { img: a.clone(), label: "red <a&b>".into() }, Tile { img: b, label: "green".into() }],
|
||||
vec![Tile { img: wide, label: "wide".into() }, Tile { img: d.join("gone.png"), label: "gone".into() }],
|
||||
];
|
||||
sheet("Test sheet", &rows, 300, &out).unwrap();
|
||||
let img = image::open(&out).unwrap().to_rgba8();
|
||||
// two columns of 300 and three gaps of 6; the tile is 150 tall (from the first's 2:1), title 44, label 30, gap 6
|
||||
assert_eq!((img.width(), img.height()), (618, 44 + 2 * (150 + 30 + 6)));
|
||||
// the first tile is red in its middle; the wide one is letterboxed (fitted 300x75, centred), not stretched
|
||||
assert_eq!(img.get_pixel(6 + 150, 44 + 75).0[..3], [200, 30, 30]);
|
||||
let row2 = 44 + 150 + 30 + 6;
|
||||
assert_eq!(img.get_pixel(6 + 150, row2 + 75).0[..3], [30, 30, 200]);
|
||||
assert_ne!(img.get_pixel(6 + 150, row2 + 10).0[..3], [30, 30, 200]);
|
||||
// the missing one is grey
|
||||
assert_eq!(img.get_pixel(6 + 300 + 6 + 150, row2 + 75).0[..3], [70, 70, 70]);
|
||||
// a label was drawn under the first tile (light pixels on the dark ground)
|
||||
let lit = (0..300).flat_map(|x| (0..30).map(move |y| (x, y))).filter(|&(x, y)| img.get_pixel(6 + x, 44 + 150 + y).0[0] > 150).count();
|
||||
assert!(lit > 40, "no label drawn ({lit} lit pixels)");
|
||||
assert!(sheet("empty", &[vec![Tile { img: d.join("none.png"), label: "x".into() }]], 100, &d.join("e.png")).is_err());
|
||||
}
|
||||
|
||||
// MK10: a reference prompt is the plan's style, the object's words and the scan template, never a brand
|
||||
#[test]
|
||||
fn a_reference_prompt_is_style_object_and_scan() {
|
||||
let m = kit();
|
||||
let p = crate::kit::ref_prompt(&m, &m.objects[0]);
|
||||
assert!(p.starts_with("1970s flight desk, cream enamel, maker Aurora Instruments. a rotary desk phone, worn bakelite. One object only"), "{p}");
|
||||
assert!(p.contains("no real brands"));
|
||||
// an object with no prompt is described by its label
|
||||
assert!(crate::kit::ref_prompt(&m, &m.objects[1]).contains(". Wall clock. "));
|
||||
assert_eq!(crate::kit::size_args(&m.objects[0]), ["--h", "0.12"]);
|
||||
assert_eq!(crate::kit::size_args(&m.objects[1]), ["--dims", "0.3,0.05,0.3"]);
|
||||
}
|
||||
|
||||
// MK11: one reference to both generators, the hero at 150k faces; the single-shot gen's file read from its JSON
|
||||
#[test]
|
||||
fn both_generators_get_each_reference() {
|
||||
let m = kit();
|
||||
let f = crate::kit::gen_flow(&m, &m.objects[0], std::path::Path::new("/r/rotary_phone.png"), crate::kit::TRIPO, crate::kit::MESHY);
|
||||
assert_eq!(f["out"], serde_json::json!(["tripo", "meshy"]));
|
||||
assert_eq!(f["steps"]["tripo"]["model"], "tripo:H3.1");
|
||||
assert_eq!(f["steps"]["tripo"]["in"]["x_face_limit"], 150000);
|
||||
assert_eq!(f["steps"]["meshy"]["model"], "fal:meshy/v7.1/image-to-3d");
|
||||
assert_eq!(f["steps"]["meshy"]["in"]["image"], "@ref");
|
||||
let small = crate::kit::gen_flow(&m, &m.objects[1], std::path::Path::new("/r/clock.png"), crate::kit::TRIPO, crate::kit::MESHY);
|
||||
assert_eq!(small["steps"]["tripo"]["in"]["x_face_limit"], 60000);
|
||||
assert_eq!(crate::kit::gen_file(r#"{"out": {"out": "/g/out.png"}, "cents": 4}"#), Some(PathBuf::from("/g/out.png")));
|
||||
assert_eq!(crate::kit::gen_file(r#"{"out": {"out": ["/g/a.png", "/g/b.png"]}}"#), Some(PathBuf::from("/g/a.png")));
|
||||
assert_eq!(crate::kit::gen_file("not json"), None);
|
||||
}
|
||||
|
||||
// MK11: a pick names a model that exists and says why; it's kept by object
|
||||
#[test]
|
||||
fn a_pick_needs_its_model_and_a_reason() {
|
||||
let d = dir("pick");
|
||||
let m = kit();
|
||||
assert!(crate::kit::choose(&d, &m, "rotary_phone", "tripo", "sharper").unwrap_err().contains("raea make gen --only rotary_phone"));
|
||||
std::fs::create_dir_all(crate::kit::gen_dir(&d, "rotary_phone")).unwrap();
|
||||
std::fs::write(crate::kit::gen_dir(&d, "rotary_phone").join("meshy.glb"), "x").unwrap();
|
||||
assert!(crate::kit::choose(&d, &m, "rotary_phone", "meshy", " ").unwrap_err().contains("say why"));
|
||||
assert!(crate::kit::choose(&d, &m, "lamp", "meshy", "x").unwrap_err().contains("no object `lamp`"));
|
||||
crate::kit::choose(&d, &m, "rotary_phone", "meshy", "Tripo fused the handset to the cradle").unwrap();
|
||||
assert_eq!(crate::kit::picks(&d)["rotary_phone"]["generator"], "meshy");
|
||||
// prep names what isn't picked yet rather than skipping it
|
||||
let said = crate::kit::prep(&d, &m, &["clock".to_string()]).unwrap();
|
||||
assert!(said.contains("clock: no pick yet"), "{said}");
|
||||
}
|
||||
|
||||
// MK13: each object a component importing its own model and LOD beside it; the lineup imports them all with a 1 m bar
|
||||
#[test]
|
||||
fn the_kit_lands_as_components_and_a_lineup() {
|
||||
let m = kit();
|
||||
assert_eq!(crate::kitout::component_name("rotary_phone"), "RotaryPhone");
|
||||
let c = crate::kitout::component(&m.objects[0], "sharper numerals");
|
||||
assert!(c.starts_with("// raea make component add: Rotary phone, 0.12 m"), "{c}");
|
||||
assert!(c.contains("import full from \"./rotary_phone.glb\";") && c.contains("import far from \"./rotary_phone_lod1.glb\";"));
|
||||
assert!(c.contains("export default function RotaryPhone("));
|
||||
let l = crate::kitout::lineup(&m, "desk");
|
||||
assert!(l.contains("import RotaryPhone from \"./RotaryPhone\";") && l.contains("import Clock from \"./Clock\";"));
|
||||
assert!(l.contains("</Text3D>") && l.contains("registerRoot("));
|
||||
// the bar is the longest round length the set covers
|
||||
assert_eq!(crate::kitout::scale_bar(0.52), (0.5, "50 cm"));
|
||||
assert_eq!(crate::kitout::scale_bar(1.7), (1.0, "1 m"));
|
||||
assert_eq!(crate::kitout::scale_bar(0.02), (0.05, "5 cm"));
|
||||
// the viewer frames a model by its height
|
||||
let v = crate::kitout::viewer(std::path::Path::new("/k/tripo.fit.glb"), 0.12);
|
||||
assert!(v.contains("import model from \"./tripo.fit.glb\";") && v.contains("<Model src={model} />"));
|
||||
// where it lands: the workspace's shared/components, else the project's components
|
||||
let d = dir("land");
|
||||
let job = d.join("projects/p/kit");
|
||||
std::fs::create_dir_all(&job).unwrap();
|
||||
std::fs::create_dir_all(d.join("projects/p/.raea")).unwrap();
|
||||
std::fs::write(d.join("projects/p/.raea/project"), "{}").unwrap();
|
||||
let real = dunce::canonicalize(&d).unwrap();
|
||||
assert_eq!(crate::kitout::kit_dir(&job, "desk", None), real.join("projects/p/components/desk"));
|
||||
std::fs::create_dir_all(d.join(".raea")).unwrap();
|
||||
std::fs::write(d.join(".raea/workspace"), "{}").unwrap();
|
||||
std::fs::create_dir_all(d.join("shared")).unwrap();
|
||||
assert_eq!(crate::kitout::kit_dir(&job, "desk", None), real.join("shared/components/desk"));
|
||||
assert_eq!(crate::kitout::kit_dir(&job, "desk", Some("/x")), PathBuf::from("/x"));
|
||||
}
|
||||
|
||||
// MK15: a shot's frames are its first, middle and last (a still: its first); the lens chart's angles
|
||||
#[test]
|
||||
fn a_shot_frames_its_start_middle_and_end() {
|
||||
let m: Make = read("make", r#"{"kind": "shot", "shots": [{"name": "push", "seconds": 4, "composition": "push.tsx"}, {"name": "hold", "still": true}, {"name": "fast", "seconds": 2, "fps": 24}]}"#).unwrap();
|
||||
assert_eq!(crate::shots::frames_of(&m.shots[0]), vec![0, 59, 119]);
|
||||
assert_eq!(crate::shots::frames_of(&m.shots[1]), vec![0]);
|
||||
assert_eq!(crate::shots::frames_of(&m.shots[2]), vec![0, 23, 47]);
|
||||
assert!((raea_core_review::fov_of_lens(50.0) - 26.99).abs() < 0.01);
|
||||
// a shot with no composition can't be framed, and says what's needed
|
||||
let d = dir("framing");
|
||||
assert!(crate::shots::framing(&d, &m, &["hold".to_string()], &d).unwrap_err().contains("no composition"));
|
||||
assert!(raea_core_brief::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
|
||||
#[test]
|
||||
fn the_plan_draws_a_floor_plan_and_a_blockout() {
|
||||
let m: Make = read("make", r#"{"kind": "scene", "references": ["media/ref.png"], "objects": [
|
||||
{"id": "desk", "label": "Desk", "dims": [1.6, 0.8, 0.75], "at": [2, 0, 3], "rot": 90, "source": "reference", "hero": true},
|
||||
{"id": "plant", "label": "Plant", "h": 1.2, "at": [0.5, 0, 4], "source": "invented", "lod": 3},
|
||||
{"id": "pen", "label": "Pen", "max": 0.14}]}"#)
|
||||
.unwrap();
|
||||
let (placed, b) = crate::floor::extent(&m);
|
||||
assert_eq!(placed.len(), 2);
|
||||
assert!(b[0] < 0.0 && b[3] > 4.5, "{b:?}");
|
||||
let svg = crate::floor::floor_svg(&m).unwrap();
|
||||
assert_eq!(svg.matches("stroke-dasharray").count(), 1);
|
||||
assert!(svg.contains(">Desk<") && svg.contains(">Plant<") && !svg.contains(">Pen<"));
|
||||
// the entrance runs along the front edge (the plan's nearest z), where the blockout's camera stands
|
||||
assert!(svg.contains("entrance: the camera looks in from here"));
|
||||
let img = crate::sheet::svg_png(&svg).unwrap();
|
||||
assert!(img.width() > 400 && img.height() > 400);
|
||||
let t = crate::floor::blockout_tsx(&m);
|
||||
assert_eq!(t.matches("<Cuboid").count(), 3, "the floor and two boxes");
|
||||
assert!(t.contains("half_size={[0.800, 0.375, 0.400]}"), "{t}");
|
||||
assert!(t.contains("<Mesh3d name=\"plant\" lod={3} transform=") && svg.contains("1.20 m, LOD 3<"), "MK22, each box named with its planned detail: {t}");
|
||||
let none: Make = read("make", r#"{"kind": "scene", "objects": [{"id": "pen", "label": "Pen"}]}"#).unwrap();
|
||||
assert!(crate::floor::floor_svg(&none).unwrap_err().contains("no object has an `at`"));
|
||||
}
|
||||
|
||||
// the CLI's positional words skip flags and their values
|
||||
#[test]
|
||||
fn positional_words_skip_flags() {
|
||||
let a: Vec<String> = ["make", "pick", "phone", "--only", "a,b", "tripo", "--dry", "why not", "proj"].iter().map(|s| s.to_string()).collect();
|
||||
assert_eq!(crate::positional(&a, 2), ["phone", "tripo", "why not", "proj"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quote_reads_as_one_line() {
|
||||
let out = "raea: planning\n{\"steps\":[{\"op\":\"media.load\",\"runs_on\":\"load\",\"cents\":0},{\"op\":\"image\",\"runs_on\":\"made:nano_banana_2\",\"cents\":6}],\"cents\":6,\"cap_cents\":100}";
|
||||
assert_eq!(crate::kit::quote(out), "made:nano_banana_2 (about 6¢)");
|
||||
assert_eq!(crate::kit::quote("not json at all"), "not json at all");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_boxy_model_is_fitted_by_its_height_and_turned_to_lie_front_to_back() {
|
||||
use raea_core_brief::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"]);
|
||||
// already front to back, or about square: no turn
|
||||
assert_eq!(crate::kit::fit_args(&stapler, Some([0.27, 0.12, 0.84])), ["--dims", "0.05,0.17,0.07", "--h", "0.07"]);
|
||||
assert_eq!(crate::kit::fit_args(&stapler, None), ["--dims", "0.05,0.17,0.07", "--h", "0.07"]);
|
||||
let clock: Object = serde_json::from_value(serde_json::json!({"id": "clock", "label": "Clock", "h": 0.14})).unwrap();
|
||||
assert_eq!(crate::kit::fit_args(&clock, Some([1.0, 1.0, 0.5])), ["--h", "0.14"]);
|
||||
assert!((crate::kitout::frame_size(&stapler) - 0.17).abs() < 1e-9);
|
||||
}
|
||||
@@ -85,4 +85,14 @@ pub fn encode(srcs: &[(PathBuf, Option<f64>, Option<f64>)], height: Option<u32>,
|
||||
Ok(json!({"wrote": out, "frames": frames, "seconds": round3(frames as f64 / fps), "width": w, "height": h, "fps": round3(fps), "kbps": kbps, "bytes": stats.bytes, "sound": any_sound}))
|
||||
}
|
||||
|
||||
/// `media share`: a copy any phone, chat and upload form takes (H.264 and AAC in an MP4, its index first), held to
|
||||
/// `cap` kbit/s (2600: a 1080p minute in about 20 MB) and never given more than a full-size copy would get (#219).
|
||||
pub fn share(file: &Path, height: Option<u32>, out: &Path, cap: u32) -> R<Value> {
|
||||
std::fs::metadata(file).map_err(|e| format!("{}: {e}", file.display()))?; // the platform's decoder panics on no path
|
||||
let i = backend()?.open_video(file).map_err(|e| format!("{}: {e}", file.display()))?.info().clone();
|
||||
let k = height.map_or(1.0, |h| (h as f64 / i.height as f64).min(1.0));
|
||||
let full = (i.width as f64 * k * i.height as f64 * k * standard_fps(i.fps) * 0.1 / 1000.0).max(300.0) as u32;
|
||||
encode(&[(file.to_path_buf(), None, None)], height, out, Some(cap.min(full)))
|
||||
}
|
||||
|
||||
// ---- ffmpeg and ffprobe, read
|
||||
+15
-2
@@ -38,6 +38,8 @@ pub(crate) fn ffmpeg(args: &[String]) -> R<()> {
|
||||
let mut pending = FfInput::default();
|
||||
let (mut ss, mut t, mut to) = (None, None, None);
|
||||
let (mut vf, mut af): (Option<String>, Option<String>) = (None, None);
|
||||
// -maxrate: the rate the copy is held to, the one quality choice read (the skill's share copy, #219)
|
||||
let mut cap = None::<u32>;
|
||||
let (mut ar, mut ac, mut fmt, mut one_frame, mut outp) = (None, None, None, false, None::<String>);
|
||||
let mut i = 0;
|
||||
let next = |i: &mut usize| -> R<String> {
|
||||
@@ -76,11 +78,19 @@ pub(crate) fn ffmpeg(args: &[String]) -> R<()> {
|
||||
"-ar" => ar = Some(next(&mut i)?.parse::<u32>().map_err(|_| "-ar takes a rate")?),
|
||||
"-ac" => ac = Some(next(&mut i)?.parse::<u32>().map_err(|_| "-ac takes a channel count")?),
|
||||
"-frames:v" | "-vframes" => one_frame = next(&mut i)? == "1",
|
||||
"-maxrate" => {
|
||||
let v = next(&mut i)?.to_lowercase();
|
||||
let (n, k) = match v.strip_suffix('k').map(|n| (n, 1.0)).or(v.strip_suffix('m').map(|n| (n, 1000.0))) {
|
||||
Some(nk) => nk,
|
||||
None => (v.as_str(), 0.001),
|
||||
};
|
||||
cap = Some((n.parse::<f64>().map_err(|_| "-maxrate takes a rate (2600k)")? * k).round().max(1.0) as u32);
|
||||
}
|
||||
"-filter_complex" | "-lavfi" => {
|
||||
return Err(format!("-filter_complex isn't read here: overlays, wipes and layouts are a composition, rendered with raea render. Or {VERBS_HINT}"));
|
||||
}
|
||||
// codec, quality and container choices: the platform encoder decides (H.264 + AAC in MP4)
|
||||
"-c" | "-c:v" | "-c:a" | "-codec" | "-vcodec" | "-acodec" | "-crf" | "-preset" | "-b:v" | "-b:a" | "-q:v" | "-qscale:v" | "-pix_fmt" | "-movflags" | "-v" | "-loglevel" | "-r" | "-safe" | "-map" | "-tune" | "-profile:v" | "-g" | "-threads" => {
|
||||
"-c" | "-c:v" | "-c:a" | "-codec" | "-vcodec" | "-acodec" | "-crf" | "-preset" | "-b:v" | "-b:a" | "-q:v" | "-qscale:v" | "-pix_fmt" | "-movflags" | "-v" | "-loglevel" | "-r" | "-safe" | "-map" | "-tune" | "-profile:v" | "-g" | "-threads" | "-bufsize" => {
|
||||
next(&mut i)?;
|
||||
}
|
||||
"-y" | "-n" | "-hide_banner" | "-nostats" | "-nostdin" | "-an" | "-vn" | "-sn" | "-shortest" | "-accurate_seek" => {}
|
||||
@@ -194,7 +204,10 @@ pub(crate) fn ffmpeg(args: &[String]) -> R<()> {
|
||||
} else {
|
||||
vec![(path.clone(), from, until)]
|
||||
};
|
||||
encode(&srcs, height, Path::new(&out), None)?;
|
||||
match (cap, srcs.as_slice()) {
|
||||
(Some(cap), [(one, None, None)]) => share(one, height, Path::new(&out), cap)?,
|
||||
(cap, _) => encode(&srcs, height, Path::new(&out), cap)?,
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
+20
-4
@@ -11,6 +11,7 @@
|
||||
//! raea media cuts FILE [--threshold 0.08] shot changes (ffmpeg's scene score)
|
||||
//! raea media freezes FILE [--noise 0.001] [--min 2] held pictures (ffmpeg's freezedetect)
|
||||
//! raea media proxy FILE [--height 720] -o OUT.mp4 a smaller copy
|
||||
//! raea media share FILE [--kbps 2600] [--height H] -o OUT.mp4 a copy to send: any player takes it, held to a bitrate
|
||||
//! raea media lod MODEL.glb [--level 1] [--texture 1024] -o OUT.glb a model at a lower level of detail (triangles halved a level)
|
||||
//! raea media trim FILE --from S --to S -o OUT.mp4 a stretch, frame-exact (re-encoded)
|
||||
//! raea media concat A B ... -o OUT.mp4 one after another (same aspect)
|
||||
@@ -80,6 +81,17 @@ fn ext(p: &Path) -> String {
|
||||
p.extension().map(|e| e.to_string_lossy().to_lowercase()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// One argument as the files it names. A shell that doesn't split a variable (zsh's `$FILES`) hands every name over as
|
||||
/// one argument, which read as a single path fails as "No such file", or past 255 bytes as "File name too long" (#218):
|
||||
/// an argument that isn't a file, but whose words each are, is those files.
|
||||
fn names(a: &str) -> Vec<String> {
|
||||
let words: Vec<&str> = a.split_whitespace().collect();
|
||||
if words.len() > 1 && !Path::new(a).exists() && words.iter().all(|w| Path::new(w).exists()) {
|
||||
return words.into_iter().map(String::from).collect();
|
||||
}
|
||||
vec![a.to_string()]
|
||||
}
|
||||
|
||||
/// `--name value` flags (and `-o`), switches, and positional arguments.
|
||||
fn parse(args: &[String]) -> (Vec<String>, BTreeMap<String, String>) {
|
||||
let (mut pos, mut fl) = (Vec::new(), BTreeMap::new());
|
||||
@@ -95,7 +107,7 @@ fn parse(args: &[String]) -> (Vec<String>, BTreeMap<String, String>) {
|
||||
i += 1;
|
||||
}
|
||||
} else {
|
||||
pos.push(a.clone());
|
||||
pos.extend(names(a));
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
@@ -107,11 +119,11 @@ fn num(fl: &BTreeMap<String, String>, k: &str) -> R<Option<f64>> {
|
||||
}
|
||||
|
||||
/// The verbs `raea media` answers here.
|
||||
pub const VERBS: &[&str] = &["probe", "still", "sheet", "audio", "loudness", "motion", "cuts", "freezes", "proxy", "lod", "trim", "concat", "encode", "help"];
|
||||
pub const VERBS: &[&str] = &["probe", "still", "sheet", "audio", "loudness", "motion", "cuts", "freezes", "proxy", "share", "lod", "trim", "concat", "encode", "help"];
|
||||
|
||||
pub fn cli(args: &[String]) -> i32 {
|
||||
let Some(verb) = args.first() else {
|
||||
println!("usage: raea media <probe|still|sheet|audio|loudness|motion|cuts|proxy|lod|trim|concat|encode> FILE ... (raea media help)");
|
||||
println!("usage: raea media <probe|still|sheet|audio|loudness|motion|cuts|proxy|share|lod|trim|concat|encode> FILE ... (raea media help)");
|
||||
return 2;
|
||||
};
|
||||
let (pos, fl) = parse(&args[1..]);
|
||||
@@ -187,6 +199,10 @@ fn run(verb: &str, pos: &[String], fl: &BTreeMap<String, String>) -> R<Option<Va
|
||||
let h = fl.get("height").and_then(|h| h.parse().ok()).unwrap_or(720);
|
||||
encode(&[(file()?, None, None)], Some(h), &out()?, fl.get("kbps").and_then(|k| k.parse().ok())).map(Some)
|
||||
}
|
||||
"share" => {
|
||||
let cap = fl.get("kbps").and_then(|k| k.parse().ok()).unwrap_or(2600);
|
||||
share(&file()?, fl.get("height").and_then(|h| h.parse().ok()), &out()?, cap).map(Some)
|
||||
}
|
||||
"trim" => {
|
||||
let (from, to) = range()?;
|
||||
if from.is_none() && to.is_none() {
|
||||
@@ -210,6 +226,6 @@ fn run(verb: &str, pos: &[String], fl: &BTreeMap<String, String>) -> R<Option<Va
|
||||
println!("{}", include_str!("lib.rs").lines().take_while(|l| l.starts_with("//!")).map(|l| l.trim_start_matches("//!").strip_prefix(' ').unwrap_or("")).collect::<Vec<_>>().join("\n"));
|
||||
Ok(None)
|
||||
}
|
||||
v => Err(format!("no media verb {v:?}: probe, still, sheet, audio, loudness, motion, cuts, freezes, proxy, trim, concat, encode")),
|
||||
v => Err(format!("no media verb {v:?}: probe, still, sheet, audio, loudness, motion, cuts, freezes, proxy, share, trim, concat, encode")),
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,11 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "`raea motion` and `raea setup motion`: body motion made by Kimodo on this machine, on MLX on a Mac, on PyTorch elsewhere"
|
||||
description = "`raea make motion` and `raea setup motion`: body motion made by Kimodo on this machine, on MLX on a Mac, on PyTorch elsewhere"
|
||||
|
||||
[dependencies]
|
||||
# a take's joints as vectors (score.rs)
|
||||
glam = "0.33"
|
||||
# raea's models folder, where the models and the PyTorch environment go
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
serde_json = "1"
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
//! `raea make motion` without the rest of the CLI, for working on this crate while the workspace's other crates are mid-change:
|
||||
//! `lane build -- cargo run --release -p raea-app-motion --example motion -- "LINE" --seeds 4 -o CLIP.json`
|
||||
fn main() {
|
||||
let args: Vec<String> = std::iter::once("motion".to_string()).chain(std::env::args().skip(1)).collect();
|
||||
match raea_app_motion::motion(&args) {
|
||||
Ok(s) => println!("{s}"),
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
std::process::exit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
+67
-24
@@ -1,4 +1,4 @@
|
||||
//! `raea motion "LINE" [--keys KEYS.json] ...`: body motion made on this machine by Kimodo (raea-sys-kimodo): a SOMA clip
|
||||
//! `raea make motion "LINE" [--keys KEYS.json] ...`: body motion made on this machine by Kimodo (raea-sys-kimodo): a SOMA clip
|
||||
//! from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path:
|
||||
//! what sdk/body/tools/between.ts writes). The clip is the file sdk/body/tools/fromkimodo.ts reads, the same one the
|
||||
//! cloud runner wrote (docs/character.feature CH15b, CH15c).
|
||||
@@ -9,15 +9,17 @@
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
mod score;
|
||||
|
||||
use raea_runtime_bundle::flag;
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
pub const USAGE: &str = "raea motion \"LINE\" [--keys KEYS.json] [--seconds 5 | --frames N] [--seed 1] [--steps 100] [-o CLIP.json]";
|
||||
pub const ABOUT: &str = "body motion made on this machine by Kimodo (NVIDIA): a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads. On a Mac it runs on MLX (Apple silicon's GPU): the first use fetches the motion model (1.1 GB) into raea's models folder, and the first new line its text encoder (8.8 GB: Llama 3 8B in 8 bits with LLM2Vec's adapters). On Linux and Windows it runs upstream Kimodo on PyTorch, set up once by raea setup motion: on an NVIDIA GPU with CUDA (the text encoder, 16 GB in bf16, on the CPU unless the card has 18 GB or more), else on the CPU alone; reading a new line on the CPU takes about 18 GB of memory. A line's words are read once and kept. Licences: Kimodo's weights NVIDIA's Open Model License, Meta Llama 3 the Meta Llama 3 Community License, LLM2Vec's adapters MIT, Kimodo's code Apache-2.0";
|
||||
pub const USAGE: &str = "raea make motion \"LINE\" [--keys KEYS.json] [--seconds 5 | --frames N] [--seed 1] [--seeds 1] [--steps 100] [-o CLIP.json]";
|
||||
pub const ABOUT: &str = "body motion made on this machine by Kimodo (NVIDIA): a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads. On a Mac it runs on MLX (Apple silicon's GPU): the first use fetches the motion model (1.1 GB) into raea's models folder, and the first new line its text encoder (8.8 GB: Llama 3 8B in 8 bits with LLM2Vec's adapters). On Linux and Windows it runs upstream Kimodo on PyTorch, set up once by raea setup motion: on an NVIDIA GPU with CUDA (the text encoder, 16 GB in bf16, on the CPU unless the card has 18 GB or more), else on the CPU alone; reading a new line on the CPU takes about 18 GB of memory. A line's words are read once and kept. --seeds N makes N takes (seeds SEED to SEED+N-1) and keeps the one with the fewest faults: a foot sliding while planted, the shoulders shrugging, the hips sinking, a hand or forearm into the torso or head (a skeletal check; each take's score is printed and the kept one's written into the clip). Licences: Kimodo's weights NVIDIA's Open Model License, Meta Llama 3 the Meta Llama 3 Community License, LLM2Vec's adapters MIT, Kimodo's code Apache-2.0";
|
||||
|
||||
pub const SETUP_USAGE: &str = "raea setup motion [--check]";
|
||||
pub const SETUP_ABOUT: &str = "what raea motion runs on, made where missing (--check only says): on a Mac the MLX models in raea's models folder (the motion model 1.1 GB, the text encoder 8.8 GB); on Linux and Windows, in raea's models folder's kimodo-torch, a Python 3.11 environment made by uv (which it needs on PATH: https://docs.astral.sh/uv) with PyTorch (its CUDA build where there is an NVIDIA driver, about 8 GB, else CPU only, about 2 GB) and upstream Kimodo (nv-tlabs/kimodo at e1c219c, Apache-2.0), then the weights: Kimodo-SOMA-RP-v1 (1.1 GB, NVIDIA Open Model License), LLM2Vec's two adapters (0.3 GB, MIT) and Meta Llama 3 8B Instruct in bf16 (16 GB, Meta Llama 3 Community License, from NousResearch's ungated copy, checked file by file against Meta's SHA-256); about 26 GB in all. It says what this machine has and where each network runs: the denoiser on CUDA when there is an NVIDIA GPU, else the CPU; the text encoder beside it on a GPU of 18 GB or more, else the CPU";
|
||||
pub const SETUP_ABOUT: &str = "what raea make motion runs on, made where missing (--check only says): on a Mac the MLX models in raea's models folder (the motion model 1.1 GB, the text encoder 8.8 GB); on Linux and Windows, in raea's models folder's kimodo-torch, a Python 3.11 environment made by uv (which it needs on PATH: https://docs.astral.sh/uv) with PyTorch (its CUDA build where there is an NVIDIA driver, about 8 GB, else CPU only, about 2 GB) and upstream Kimodo (nv-tlabs/kimodo at e1c219c, Apache-2.0), then the weights: Kimodo-SOMA-RP-v1 (1.1 GB, NVIDIA Open Model License), LLM2Vec's two adapters (0.3 GB, MIT) and Meta Llama 3 8B Instruct in bf16 (16 GB, Meta Llama 3 Community License, from NousResearch's ungated copy, checked file by file against Meta's SHA-256); about 26 GB in all. It says what this machine has and where each network runs: the denoiser on CUDA when there is an NVIDIA GPU, else the CPU; the text encoder beside it on a GPU of 18 GB or more, else the CPU";
|
||||
|
||||
fn number(args: &[String], name: &str, default: f64) -> R<f64> {
|
||||
match flag(args, name) {
|
||||
@@ -27,7 +29,7 @@ fn number(args: &[String], name: &str, default: f64) -> R<f64> {
|
||||
}
|
||||
|
||||
fn line(args: &[String]) -> String {
|
||||
const WITH_VALUE: [&str; 6] = ["--keys", "--seconds", "--frames", "--seed", "--steps", "-o"];
|
||||
const WITH_VALUE: [&str; 7] = ["--keys", "--seconds", "--frames", "--seed", "--seeds", "--steps", "-o"];
|
||||
let mut out = Vec::new();
|
||||
let mut i = 1;
|
||||
while i < args.len() {
|
||||
@@ -50,6 +52,7 @@ struct Ask {
|
||||
constraints: Option<serde_json::Value>,
|
||||
frames: usize,
|
||||
seed: u64,
|
||||
seeds: usize,
|
||||
steps: usize,
|
||||
out: Option<String>,
|
||||
}
|
||||
@@ -64,15 +67,21 @@ pub fn motion(args: &[String]) -> R<String> {
|
||||
Some(_) => number(args, "--frames", 150.0)? as usize,
|
||||
None => (number(args, "--seconds", 5.0)? * 30.0).round() as usize,
|
||||
};
|
||||
if !(2..=600).contains(&frames) {
|
||||
return Err(format!("a clip is 2 to 600 frames (20 s at 30 a second), asked {frames}"));
|
||||
// Kimodo's own limit (its docs, key_concepts/limitations.md): past 10 s a clip drifts and breaks up (11-27: a
|
||||
// 12.3 s talk clip's feet spread 47 -> 69 cm, shoulders rose 9 cm, the last half second glitched)
|
||||
if !(2..=300).contains(&frames) {
|
||||
return Err(format!(
|
||||
"a clip is 2 to 300 frames (10 s at 30 a second, Kimodo's limit: longer clips drift and break up), asked {frames}; \
|
||||
for longer, make 10 s clips one after another, each from --keys holding the last frames of the one before"
|
||||
));
|
||||
}
|
||||
let constraints = match &keys {
|
||||
Some(p) => Some(serde_json::from_str::<serde_json::Value>(&std::fs::read_to_string(p).map_err(|e| format!("{p}: {e}"))?).map_err(|e| format!("{p}: {e}"))?),
|
||||
None => None,
|
||||
};
|
||||
let (seed, steps) = (number(args, "--seed", 1.0)? as u64, (number(args, "--steps", 100.0)? as usize).max(2));
|
||||
make(Ask { words, keys, constraints, frames, seed, steps, out: flag(args, "-o") })
|
||||
let seeds = (number(args, "--seeds", 1.0)? as usize).clamp(1, 32);
|
||||
make(Ask { words, keys, constraints, frames, seed, seeds, steps, out: flag(args, "-o") })
|
||||
}
|
||||
|
||||
/// -o, else a file named by the line's words in the working folder
|
||||
@@ -83,6 +92,25 @@ fn out_path(out: Option<String>, clean: &str) -> PathBuf {
|
||||
}))
|
||||
}
|
||||
|
||||
/// the take with the lowest score of those made, its seed, and a line per take ("" for a single take)
|
||||
fn keep_best(takes: Vec<(u64, raea_sys_kimodo::decode::Motion)>, sk: &raea_sys_kimodo::skeleton::Skeleton) -> (u64, raea_sys_kimodo::decode::Motion, Option<score::Score>, String) {
|
||||
let one = takes.len() == 1;
|
||||
let mut scored: Vec<(u64, raea_sys_kimodo::decode::Motion, score::Score)> = takes.into_iter().map(|(s, m)| { let sc = score::score(&m, sk); (s, m, sc) }).collect();
|
||||
let report = if one { String::new() } else { scored.iter().map(|(s, _, sc)| format!("\n seed {s}: {}", sc.line())).collect::<String>() };
|
||||
scored.sort_by(|a, b| a.2.total.total_cmp(&b.2.total));
|
||||
let (s, m, sc) = scored.remove(0);
|
||||
(s, m, Some(sc), report)
|
||||
}
|
||||
|
||||
/// the kept take's score, written into the clip
|
||||
fn with_score(mut clip: serde_json::Value, sc: &Option<score::Score>, tried: usize) -> serde_json::Value {
|
||||
if let Some(sc) = sc {
|
||||
clip["score"] = serde_json::json!({"total": sc.total, "foot_drift_cm": sc.foot_drift_cm, "shoulder_rise_cm": sc.shoulder_rise_cm,
|
||||
"hip_drop_cm": sc.hip_drop_cm, "collision_cm": sc.collision_cm, "takes": tried});
|
||||
}
|
||||
clip
|
||||
}
|
||||
|
||||
/// how far the hips end from where they start, on the ground
|
||||
fn travel(m: &raea_sys_kimodo::decode::Motion) -> f32 {
|
||||
let r = &m.root;
|
||||
@@ -103,16 +131,23 @@ fn make(ask: Ask) -> R<String> {
|
||||
let missing = t.missing();
|
||||
if !missing.is_empty() {
|
||||
return Err(format!(
|
||||
"raea motion runs Kimodo on PyTorch on this machine (MLX is Apple silicon's), and its {} isn't set up in {} yet: raea setup motion makes it (uv, then about 26 GB: PyTorch, Kimodo's code and weights, Llama 3 8B Instruct for the text encoder)",
|
||||
"raea make motion runs Kimodo on PyTorch on this machine (MLX is Apple silicon's), and its {} isn't set up in {} yet: raea setup motion makes it (uv, then about 26 GB: PyTorch, Kimodo's code and weights, Llama 3 8B Instruct for the text encoder)",
|
||||
missing.join(", the "),
|
||||
t.dir.display()
|
||||
));
|
||||
}
|
||||
let keys = ask.keys.as_ref().map(std::path::Path::new);
|
||||
let job = torch::Job { line: &ask.words, frames: ask.frames, seed: ask.seed, steps: ask.steps, keys, cfg: (2.0, 2.0) };
|
||||
let made = t.make(&job).map_err(|e| format!("raea motion: {e}"))?;
|
||||
let (stats, sk) = (Stats::load(&t.checkpoint).map_err(|e| format!("raea motion: {e}"))?, Skeleton::soma().map_err(|e| format!("raea motion: {e}"))?);
|
||||
let motion = decode::decode(&made.features, &stats, &sk);
|
||||
let mut takes = Vec::new();
|
||||
let mut last = None;
|
||||
for s in ask.seed..ask.seed + ask.seeds as u64 {
|
||||
let job = torch::Job { line: &ask.words, frames: ask.frames, seed: s, steps: ask.steps, keys, cfg: (2.0, 2.0) };
|
||||
let made = t.make(&job).map_err(|e| format!("raea motion: {e}"))?;
|
||||
takes.push((s, decode::decode(&made.features, &stats, &sk)));
|
||||
last = Some(made);
|
||||
}
|
||||
let made = last.ok_or("raea motion: no take")?;
|
||||
let (seed, motion, sc, report) = keep_best(takes, &sk);
|
||||
let info = &made.info;
|
||||
let clean = info["line"].as_str().unwrap_or(&ask.words).to_string();
|
||||
let (dev, text_dev) = (info["motion"].as_str().unwrap_or("?"), info["text"].as_str().unwrap_or("?"));
|
||||
@@ -120,26 +155,28 @@ fn make(ask: Ask) -> R<String> {
|
||||
Some(g) => format!("on PyTorch {} with CUDA ({g}; the text encoder on {text_dev}), upstream nv-tlabs/kimodo {}", info["torch"].as_str().unwrap_or("?"), &torch::KIMODO[..7]),
|
||||
None => format!("on PyTorch {} on the CPU, upstream nv-tlabs/kimodo {}", info["torch"].as_str().unwrap_or("?"), &torch::KIMODO[..7]),
|
||||
};
|
||||
let clip = decode::clip_json_on(&motion, &sk, ask.seed, ask.steps, &clean, ask.constraints.is_some(), &on);
|
||||
let clip = with_score(decode::clip_json_on(&motion, &sk, seed, ask.steps, &clean, ask.constraints.is_some(), &on), &sc, ask.seeds);
|
||||
let out = out_path(ask.out, &clean);
|
||||
std::fs::write(&out, serde_json::to_string(&clip).unwrap_or_default()).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
// the hips as PyTorch decoded them against decode.rs's: the features were read as Kimodo wrote them
|
||||
let ours: Vec<[f32; 3]> = motion.joints77.iter().map(|f| f[0]).collect();
|
||||
let gap = torch::root_gap(&info["root"], &ours).map(|g| format!(", decoded here within {:.3} mm of PyTorch's own", g * 1000.0)).unwrap_or_default();
|
||||
let gap = if ask.seeds > 1 { String::new() } else { torch::root_gap(&info["root"], &ours).map(|g| format!(", decoded here within {:.3} mm of PyTorch's own", g * 1000.0)).unwrap_or_default() };
|
||||
let f = |k: &str| info[k].as_f64().unwrap_or(0.0);
|
||||
let read = if f("read_s") > 0.0 { format!(", reading the line {:.1} s after {:.1} s loading its encoder", f("read_s"), f("text_load_s")) } else { String::new() };
|
||||
Ok(format!(
|
||||
"APPLIED motion {:?}{}, {} frames ({:.1} s), seed {}, {} steps -> {} (made {on} in {:.1} s after {:.1} s loading{read}; the hips end {:.2} m from where they start{gap})",
|
||||
"APPLIED motion {:?}{}, {} frames ({:.1} s), seed {}{}, {} steps -> {} (made {on} in {:.1} s after {:.1} s loading{read}; the hips end {:.2} m from where they start{gap}; {}){report}",
|
||||
clean,
|
||||
if ask.keys.is_some() { " with keys" } else { "" },
|
||||
ask.frames,
|
||||
ask.frames as f64 / 30.0,
|
||||
ask.seed,
|
||||
seed,
|
||||
if ask.seeds > 1 { format!(", the best of {} takes", ask.seeds) } else { String::new() },
|
||||
ask.steps,
|
||||
out.display(),
|
||||
f("gen_s"),
|
||||
f("load_s"),
|
||||
travel(&motion),
|
||||
sc.as_ref().map(|s| s.line()).unwrap_or_default(),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -154,23 +191,29 @@ fn make(ask: Ask) -> R<String> {
|
||||
let mut k = raea_sys_kimodo::Kimodo::fetch(&mut progress).map_err(|e| format!("raea motion: {e}"))?;
|
||||
let (clean, emb) = k.encode(&ask.words).map_err(|e| format!("raea motion: {e}"))?;
|
||||
let load_s = t0.elapsed().as_secs_f64();
|
||||
let made_from = raea_sys_kimodo::Ask { line: &ask.words, frames: ask.frames, seed: ask.seed, steps: ask.steps, constraints: ask.constraints.as_ref(), cfg: (2.0, 2.0) };
|
||||
let t1 = std::time::Instant::now();
|
||||
let made = k.make(&made_from, emb.as_deref(), None).map_err(|e| format!("raea motion: {e}"))?;
|
||||
let mut takes = Vec::new();
|
||||
for s in ask.seed..ask.seed + ask.seeds as u64 {
|
||||
let made_from = raea_sys_kimodo::Ask { line: &ask.words, frames: ask.frames, seed: s, steps: ask.steps, constraints: ask.constraints.as_ref(), cfg: (2.0, 2.0) };
|
||||
takes.push((s, k.make(&made_from, emb.as_deref(), None).map_err(|e| format!("raea motion: {e}"))?.motion));
|
||||
}
|
||||
let gen_s = t1.elapsed().as_secs_f64();
|
||||
let clip = raea_sys_kimodo::decode::clip_json(&made.motion, &k.skeleton, ask.seed, ask.steps, &clean, ask.constraints.is_some());
|
||||
let (seed, motion, sc, report) = keep_best(takes, &k.skeleton);
|
||||
let clip = with_score(raea_sys_kimodo::decode::clip_json(&motion, &k.skeleton, seed, ask.steps, &clean, ask.constraints.is_some()), &sc, ask.seeds);
|
||||
let out = out_path(ask.out, &clean);
|
||||
std::fs::write(&out, serde_json::to_string(&clip).unwrap_or_default()).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
Ok(format!(
|
||||
"APPLIED motion {:?}{}, {} frames ({:.1} s), seed {}, {} steps -> {} (made on this Mac in {gen_s:.1} s after {load_s:.1} s loading and reading the line; the hips end {:.2} m from where they start)",
|
||||
"APPLIED motion {:?}{}, {} frames ({:.1} s), seed {}{}, {} steps -> {} (made on this Mac in {gen_s:.1} s after {load_s:.1} s loading and reading the line; the hips end {:.2} m from where they start; {}){report}",
|
||||
clean,
|
||||
if ask.keys.is_some() { " with keys" } else { "" },
|
||||
ask.frames,
|
||||
ask.frames as f64 / 30.0,
|
||||
ask.seed,
|
||||
seed,
|
||||
if ask.seeds > 1 { format!(", the best of {} takes", ask.seeds) } else { String::new() },
|
||||
ask.steps,
|
||||
out.display(),
|
||||
travel(&made.motion)
|
||||
travel(&motion),
|
||||
sc.as_ref().map(|s| s.line()).unwrap_or_default(),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -190,7 +233,7 @@ fn disk(dir: &std::path::Path) -> String {
|
||||
raea_io_home::disk_use(dir, true)
|
||||
}
|
||||
|
||||
/// `raea setup motion [--check]`: what raea motion runs on here, made where missing (--check only says), and where it is.
|
||||
/// `raea setup motion [--check]`: what raea make motion runs on here, made where missing (--check only says), and where it is.
|
||||
pub fn setup(args: &[String]) -> R<String> {
|
||||
let check = args.iter().any(|a| a == "--check");
|
||||
if let Some(a) = args.iter().find(|a| *a != "--check") {
|
||||
@@ -214,7 +257,7 @@ fn setup_here(check: bool) -> R<String> {
|
||||
let state = match (had, has) {
|
||||
(true, _) => "installed",
|
||||
(false, true) => "installed now",
|
||||
(false, false) => "not installed: raea setup motion fetches it (raea motion does too, the first time it needs it)",
|
||||
(false, false) => "not installed: raea setup motion fetches it (raea make motion does too, the first time it needs it)",
|
||||
};
|
||||
lines.push(format!(" {name:<12} {state}; {what}\n {} ({})", dir.display(), if *has { disk(dir) } else { "-".into() }));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
//! A take scored for the faults a body shows (sheet3d plan E3), so `raea make motion --seeds N` can keep the best of N:
|
||||
//! a foot sliding while it's planted, the shoulders shrugging up, the hips sinking, and a hand or forearm inside the
|
||||
//! torso or head. Read from the take's own joints (Kimodo's SOMA skeleton, metres, Y up) and its foot contacts.
|
||||
//! Collision is a skeletal proxy: capsules round the spine and a sphere for the head, sized for SOMA's average adult;
|
||||
//! the mesh check on the body a clip drives is the join's (sheet3d's join.py: head-in-body frames).
|
||||
|
||||
use raea_sys_kimodo::decode::Motion;
|
||||
use raea_sys_kimodo::skeleton::Skeleton;
|
||||
|
||||
use glam::Vec3;
|
||||
|
||||
/// each fault in centimetres (collision: the deepest a hand or forearm point goes into the torso or head), and
|
||||
/// their sum, each over its own allowance: 1 cm of drift, 3 cm of shrug, 5 cm of sinking, 1 cm into the body
|
||||
pub struct Score {
|
||||
pub foot_drift_cm: f32,
|
||||
pub shoulder_rise_cm: f32,
|
||||
pub hip_drop_cm: f32,
|
||||
pub collision_cm: f32,
|
||||
pub total: f32,
|
||||
}
|
||||
|
||||
fn idx(sk: &Skeleton, n: &str) -> usize {
|
||||
sk.names77.iter().position(|x| x == n).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// how far p is inside the capsule a-b of radius r (0 outside)
|
||||
fn inside(p: [f32; 3], a: [f32; 3], b: [f32; 3], r: f32) -> f32 {
|
||||
let (p, a, b) = (Vec3::from(p), Vec3::from(a), Vec3::from(b));
|
||||
let ab = b - a;
|
||||
let t = ((p - a).dot(ab) / ab.length_squared().max(1e-9)).clamp(0.0, 1.0);
|
||||
(r - p.distance(a + t * ab)).max(0.0)
|
||||
}
|
||||
|
||||
fn median(mut v: Vec<f32>) -> f32 {
|
||||
if v.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
v.sort_by(|a, b| a.total_cmp(b));
|
||||
v[v.len() / 2]
|
||||
}
|
||||
|
||||
pub fn score(m: &Motion, sk: &Skeleton) -> Score {
|
||||
let j = &m.joints77;
|
||||
let n = j.len();
|
||||
// a foot planted: its horizontal travel over each run of contact frames, the worst run
|
||||
let feet = [("LeftFoot", 0), ("LeftToeBase", 1), ("RightFoot", 3), ("RightToeBase", 4)];
|
||||
let mut drift = 0f32;
|
||||
for (name, c) in feet {
|
||||
let k = idx(sk, name);
|
||||
let mut start: Option<usize> = None;
|
||||
for f in 0..=n {
|
||||
let on = f < n && m.contacts[f][c];
|
||||
match (on, start) {
|
||||
(true, None) => start = Some(f),
|
||||
(false, Some(s)) => {
|
||||
let mut far = 0f32;
|
||||
for g in s..f {
|
||||
let d = Vec3::from(j[g][k]) - Vec3::from(j[s][k]);
|
||||
far = far.max(d.x.hypot(d.z));
|
||||
}
|
||||
drift = drift.max(far);
|
||||
start = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
// shoulders above the chest: the highest against the take's own usual, both sides
|
||||
let chest = idx(sk, "Chest");
|
||||
let mut rise = 0f32;
|
||||
for s in ["LeftShoulder", "RightShoulder"] {
|
||||
let k = idx(sk, s);
|
||||
let h: Vec<f32> = j.iter().map(|f| f[k][1] - f[chest][1]).collect();
|
||||
let med = median(h.clone());
|
||||
rise = rise.max(h.iter().fold(f32::MIN, |a, &b| a.max(b)) - med);
|
||||
}
|
||||
// hips below where they stand: the lowest against the first second's median
|
||||
let hips = idx(sk, "Hips");
|
||||
let stand = median(j.iter().take(30).map(|f| f[hips][1]).collect());
|
||||
let drop = (stand - j.iter().fold(f32::MAX, |a, f| a.min(f[hips][1]))).max(0.0);
|
||||
// hands and forearms against the torso (hips to chest, chest to neck) and the head
|
||||
let (spine1, neck, head) = (idx(sk, "Spine1"), idx(sk, "Neck1"), idx(sk, "Head"));
|
||||
let limbs: Vec<usize> = ["LeftHand", "RightHand", "LeftHandMiddle1", "RightHandMiddle1"].iter().map(|x| idx(sk, x)).collect();
|
||||
let fore = [("LeftArm", "LeftForeArm", "LeftHand"), ("RightArm", "RightForeArm", "RightHand")];
|
||||
let mut deep = 0f32;
|
||||
for f in j {
|
||||
let mut pts: Vec<[f32; 3]> = limbs.iter().map(|&k| f[k]).collect();
|
||||
for (_, e, h) in fore {
|
||||
let (a, b) = (f[idx(sk, e)], f[idx(sk, h)]);
|
||||
pts.push([(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0, (a[2] + b[2]) / 2.0]);
|
||||
}
|
||||
for p in pts {
|
||||
let d = inside(p, f[hips], f[spine1], 0.12)
|
||||
.max(inside(p, f[spine1], f[chest], 0.13))
|
||||
.max(inside(p, f[chest], f[neck], 0.11))
|
||||
.max(inside(p, f[head], f[head], 0.09));
|
||||
deep = deep.max(d);
|
||||
}
|
||||
}
|
||||
let (d, r, h, c) = (drift * 100.0, rise * 100.0, drop * 100.0, deep * 100.0);
|
||||
Score { foot_drift_cm: d, shoulder_rise_cm: r, hip_drop_cm: h, collision_cm: c, total: d / 1.0 + r / 3.0 + h / 5.0 + c / 1.0 }
|
||||
}
|
||||
|
||||
impl Score {
|
||||
pub fn line(&self) -> String {
|
||||
format!(
|
||||
"score {:.2} (foot drift {:.1} cm, shoulder rise {:.1} cm, hip drop {:.1} cm, hand into body {:.1} cm)",
|
||||
self.total, self.foot_drift_cm, self.shoulder_rise_cm, self.hip_drop_cm, self.collision_cm
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "raea-app-playable"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "`raea playable`: a raea game exported as a playable ad, one page or ZIP per ad network (docs/playables.feature)"
|
||||
|
||||
[dependencies]
|
||||
dunce = "1"
|
||||
# the game and sdk/playable's host bundled into one page by raea's own bundler (Rolldown, in process)
|
||||
raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
# where raea's files are: an install's share/raea, else this checkout
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
regex = "1"
|
||||
serde_json = "1"
|
||||
# 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"] }
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
//! `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; 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 [--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
|
||||
pub(crate) use raea_runtime_bundle::spec;
|
||||
|
||||
fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
|
||||
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
|
||||
}
|
||||
|
||||
/// The folder whose node_modules holds 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 has(dir) {
|
||||
return Ok(dir.to_path_buf());
|
||||
}
|
||||
d = dir.parent();
|
||||
}
|
||||
["sdk/playable", "sdk/r3f"]
|
||||
.iter()
|
||||
.map(|p| home.join(p))
|
||||
.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, 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 out = std::env::temp_dir().join(format!("raea-playable-{}.js", std::process::id()));
|
||||
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
|
||||
}
|
||||
|
||||
pub fn cli(args: &[String]) -> R<String> {
|
||||
let game = args.get(1).filter(|a| !a.starts_with('-')).ok_or(USAGE)?;
|
||||
let game = dunce::canonicalize(game).map_err(|e| format!("{game}: {e}"))?;
|
||||
let out = PathBuf::from(flag(args, "-o").ok_or(format!("-o DIR is required: {USAGE}"))?);
|
||||
let networks: Vec<&str> = flag(args, "--networks").map(|n| n.split(',').filter(|s| !s.is_empty()).collect()).unwrap_or_else(|| pages::NETWORKS.to_vec());
|
||||
if let Some(bad) = networks.iter().find(|n| !pages::NETWORKS.contains(n)) {
|
||||
return Err(format!("raea playable: no network {bad} (one of {})", pages::NETWORKS.join(", ")));
|
||||
}
|
||||
let orientation = flag(args, "--orientation").unwrap_or("both");
|
||||
if !["portrait", "landscape", "both"].contains(&orientation) {
|
||||
return Err("--orientation is portrait, landscape or both".into());
|
||||
}
|
||||
let store = serde_json::json!({"ios": flag(args, "--ios").unwrap_or(""), "android": flag(args, "--android").unwrap_or("")}).to_string();
|
||||
let card = serde_json::json!({"title": flag(args, "--title").unwrap_or(""), "cta": flag(args, "--cta").unwrap_or("Play now")}).to_string();
|
||||
// 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)?;
|
||||
report.push(format!("3D kinds: {}", if found.kinds.is_empty() { "none".into() } else { found.kinds.join(", ") }));
|
||||
for c in &found.comps {
|
||||
let shape = if c.height > c.width { "portrait" } else { "landscape" };
|
||||
report.push(format!("composition {}: {}x{} {shape}, {} fps, {:.0} s", c.id, c.width, c.height, c.fps, c.frames as f64 / c.fps.max(1.0)));
|
||||
}
|
||||
report.extend(found.notes.iter().map(|n| format!("note: {n}")));
|
||||
if !found.refusals.is_empty() {
|
||||
// the reasons first: the CLI marks an error's first line REFUSED
|
||||
let mut why = found.refusals.clone();
|
||||
why.extend(report);
|
||||
return Err(why.join("\n"));
|
||||
}
|
||||
|
||||
let 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, &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"));
|
||||
}
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
//! What a playable can't have, refused before it is bundled (docs/playables.feature PA4): the source read for files
|
||||
//! from disk, the network and the native engine's modules; the compositions rendered (sdk/playable/src/export/walk.ts,
|
||||
//! through `raea run` in a process of its own) for their shapes and the 3D kinds the host doesn't draw.
|
||||
use super::R;
|
||||
use serde_json::Value;
|
||||
use std::path::Path;
|
||||
|
||||
/// One composition the game registers
|
||||
pub struct Comp {
|
||||
pub id: String,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub fps: f64,
|
||||
pub frames: u64,
|
||||
}
|
||||
|
||||
/// What the lint found: refusals stop the export, notes don't
|
||||
pub struct Found {
|
||||
pub comps: Vec<Comp>,
|
||||
pub kinds: Vec<String>,
|
||||
pub notes: Vec<String>,
|
||||
pub refusals: Vec<String>,
|
||||
/// 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)] = &[
|
||||
(r"\bstaticFile\s*\(", "staticFile() reads the edit's folder at render time; import the file instead (`import icon from \"./icon.png\"`), which the export carries in the page"),
|
||||
(r"https?://", "a URL in the source: a playable makes no network requests (every network refuses one)"),
|
||||
(r"\bfetch\s*\(|XMLHttpRequest|WebSocket", "fetch/XHR/WebSocket: a playable makes no network requests"),
|
||||
(r#"from\s+["']raea/(native|ml|character|physics|media|matchmove|modelling)["']"#, "a module that needs the native engine (native calls, models, physics, footage)"),
|
||||
(r"<(Video|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
|
||||
pub fn lint(game: &Path) -> R<Found> {
|
||||
let src = std::fs::read_to_string(game).map_err(|e| format!("{}: {e}", game.display()))?;
|
||||
let mut refusals = Vec::new();
|
||||
let mut notes = Vec::new();
|
||||
// a URL the SVG namespace names is a name, not a request
|
||||
let src_no_ns = src.replace("http://www.w3.org", "");
|
||||
for (re, why) in SOURCE_RULES {
|
||||
if regex::Regex::new(re).map_err(|e| e.to_string())?.is_match(&src_no_ns) {
|
||||
refusals.push(why.to_string());
|
||||
}
|
||||
}
|
||||
if !src.contains("raea/playable") {
|
||||
notes.push("no raea/playable import: the game never opens the store itself (add an <EndCard> or <InstallButton>); the host's own end card shows at the last frame".into());
|
||||
}
|
||||
let walked = match walk(game) {
|
||||
Ok(w) => w,
|
||||
// what the source can't have (a fetch, a URL) often stops the render too: the refusal says why, the render's end doesn't
|
||||
Err(_) if !refusals.is_empty() => return Ok(Found { comps: vec![], kinds: vec![], notes, refusals, sound: Value::Null, ecs: false }),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let comps: Vec<Comp> = walked["comps"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|c| Comp {
|
||||
id: c["id"].as_str().unwrap_or("").into(),
|
||||
width: c["width"].as_u64().unwrap_or(0) as u32,
|
||||
height: c["height"].as_u64().unwrap_or(0) as u32,
|
||||
fps: c["fps"].as_f64().unwrap_or(30.0),
|
||||
frames: c["frames"].as_u64().unwrap_or(0),
|
||||
})
|
||||
.collect();
|
||||
let strings = |k: &str| walked[k].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(String::from)).collect::<Vec<_>>();
|
||||
if comps.is_empty() {
|
||||
refusals.push("no composition registered (registerRoot)".into());
|
||||
}
|
||||
if comps.len() == 1 {
|
||||
notes.push("one composition: the other orientation is letterboxed (Unity, AppLovin, Moloco and Mintegral want both; register a second one at the other shape)".into());
|
||||
}
|
||||
for k in strings("refused") {
|
||||
refusals.push(format!("3D kind {k} isn't drawn in a playable"));
|
||||
}
|
||||
Ok(Found { comps, kinds: strings("kinds"), notes, refusals, 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
|
||||
/// out of this one; its answer is the JSON it prints
|
||||
fn walk(game: &Path) -> R<Value> {
|
||||
let walk = raea_io_home::home().join("sdk/playable/src/export/walk.ts");
|
||||
if !walk.is_file() {
|
||||
return Err(format!("{}: raea's playable SDK isn't there", walk.display()));
|
||||
}
|
||||
let work = std::env::temp_dir().join(format!("raea-playable-lint-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&work).map_err(|e| e.to_string())?;
|
||||
let entry = work.join("lint.ts");
|
||||
std::fs::write(&entry, format!("import {:?};\nexport {{ default }} from {:?};\n", super::spec(game), super::spec(&walk))).map_err(|e| e.to_string())?;
|
||||
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
let run = std::process::Command::new(exe).arg("run").arg(&entry).output().map_err(|e| format!("raea run: {e}"));
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
let run = run?;
|
||||
let out = String::from_utf8_lossy(&run.stdout);
|
||||
if !run.status.success() {
|
||||
let err = String::from_utf8_lossy(&run.stderr);
|
||||
let said: Vec<&str> = err.lines().chain(out.lines()).filter(|l| !l.trim().is_empty()).collect();
|
||||
// the line that names the error, else the last one ("… ended with exit 1" says nothing)
|
||||
let why = said.iter().find(|l| l.contains("Error") || l.contains("error:")).or(said.last()).unwrap_or(&"").trim().to_string();
|
||||
return Err(format!("the game didn't render for the lint: {why}"));
|
||||
}
|
||||
let at = out.find('{').ok_or("the lint's walk printed no answer")?;
|
||||
serde_json::from_str(&out[at..]).map_err(|e| format!("the lint's walk: {e}"))
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
//! Each network's package around the one script (docs/playables.feature, the Background's table): the page every
|
||||
//! network gets, with that network's own tags, as one HTML file or a ZIP, checked against its cap.
|
||||
use super::R;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub const NETWORKS: &[&str] = &["applovin", "unity", "google", "meta", "moloco", "mintegral", "tiktok", "liftoff", "preview"];
|
||||
|
||||
/// Every network's cap, 5 MB (TikTok's counted zipped, which is what's written)
|
||||
pub const CAP: u64 = 5 * 1024 * 1024;
|
||||
|
||||
/// What one network got: the file and its size
|
||||
pub struct Written {
|
||||
pub network: String,
|
||||
pub file: PathBuf,
|
||||
pub bytes: u64,
|
||||
}
|
||||
|
||||
/// The settings a page starts with, as the globals the host reads (sdk/playable network.ts, host/main.tsx): the network,
|
||||
/// the store links, the end card's words
|
||||
pub fn preamble(network: &str, store: &str, card: &str) -> String {
|
||||
format!("var __RAEA_NETWORK__={},__RAEA_STORE__={store},__RAEA_PLAYABLE__={card};", serde_json::to_string(network).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The page: the network's head and body tags, then the script (a page's inline script ends at the first "</script")
|
||||
pub fn page(title: &str, head: &str, body: &str, script: &str) -> String {
|
||||
let title = title.replace('&', "&").replace('<', "<");
|
||||
format!(
|
||||
"<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover\">\n<title>{title}</title>\n{head}\n</head>\n<body>\n{body}\n<script>\n{}\n</script>\n</body>\n</html>\n",
|
||||
script.replace("</script", "<\\/script")
|
||||
)
|
||||
}
|
||||
|
||||
fn zip(file: &Path, entries: &[(String, String)]) -> R<()> {
|
||||
let f = std::fs::File::create(file).map_err(|e| format!("{}: {e}", file.display()))?;
|
||||
let mut w = zip::ZipWriter::new(f);
|
||||
let o = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||
for (name, text) in entries {
|
||||
w.start_file(name.as_str(), o).map_err(|e| e.to_string())?;
|
||||
w.write_all(text.as_bytes()).map_err(|e| e.to_string())?;
|
||||
}
|
||||
w.finish().map_err(|e| e.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `network`'s package of `script` (its preamble already first) written into `out` as NAME-NETWORK.html or .zip, 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" => {
|
||||
let o = if orientation == "both" { "portrait,landscape" } else { orientation };
|
||||
let head = format!("<meta name=\"ad.orientation\" content=\"{o}\">\n<script type=\"text/javascript\" src=\"https://tpc.googlesyndication.com/pagead/gadgets/html5/api/exitapi.js\"></script>");
|
||||
let f = out.join(format!("{name}-google.zip"));
|
||||
zip(&f, &[("index.html".into(), html(&head, ""))])?;
|
||||
f
|
||||
}
|
||||
// a ZIP with index.html and config.json; TikTok's playable SDK before the game's script (TikTok Ads help)
|
||||
"tiktok" => {
|
||||
let o = match orientation {
|
||||
"portrait" => 1,
|
||||
"landscape" => 2,
|
||||
_ => 0,
|
||||
};
|
||||
let body = "<script src=\"https://sf16-muse-va.ibytedtos.com/obj/union-fe-nc-i18n/playable/sdk/playable-sdk.js\"></script>";
|
||||
let f = out.join(format!("{name}-tiktok.zip"));
|
||||
zip(&f, &[("index.html".into(), html("", body)), ("config.json".into(), format!("{{\"playable_orientation\": {o}}}\n"))])?;
|
||||
f
|
||||
}
|
||||
// a ZIP holding a folder and a page of the same name
|
||||
"mintegral" => {
|
||||
let f = out.join(format!("{name}-mintegral.zip"));
|
||||
zip(&f, &[(format!("{name}/{name}.html"), html("", ""))])?;
|
||||
f
|
||||
}
|
||||
// one HTML file, everything inlined; MRAID is injected by the network's webview (Meta: data URIs only)
|
||||
"applovin" | "unity" | "meta" | "moloco" | "liftoff" | "preview" => {
|
||||
let f = out.join(format!("{name}-{network}.html"));
|
||||
std::fs::write(&f, html("", "")).map_err(|e| format!("{}: {e}", f.display()))?;
|
||||
f
|
||||
}
|
||||
other => return Err(format!("raea playable: no network {other} (one of {})", NETWORKS.join(", "))),
|
||||
};
|
||||
let bytes = std::fs::metadata(&file).map(|m| m.len()).unwrap_or(0);
|
||||
Ok(Written { network: network.into(), file, bytes })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn a_script_cannot_end_its_page_early() {
|
||||
let p = super::page("t", "", "", "a('</script>')");
|
||||
assert_eq!(p.matches("</script").count(), 1, "{p}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_preamble_names_the_network_as_a_string() {
|
||||
assert_eq!(super::preamble("applovin", "{}", "{}"), "var __RAEA_NETWORK__=\"applovin\",__RAEA_STORE__={},__RAEA_PLAYABLE__={};");
|
||||
}
|
||||
}
|
||||
@@ -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",
|
||||
}
|
||||
}
|
||||
+11
-1
@@ -4,7 +4,7 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "raea scene lint|explain|light|stage: a composition's frames stepped without drawing and held to the contact, light and stage checks"
|
||||
description = "raea scene lint|explain|faults|light|stage|lod: a composition's frames stepped without drawing and held to the contact, light and stage checks"
|
||||
|
||||
[dependencies]
|
||||
raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
@@ -12,7 +12,17 @@ raea-runtime-export = { path = "../../runtime/export" }
|
||||
raea-sys-contact = { path = "../../systems/contact" }
|
||||
raea-sys-light-meter = { path = "../../systems/light-meter" }
|
||||
raea-sys-stage = { path = "../../systems/stage" }
|
||||
# raea scene faults: whether a viewer would notice each lint finding, and the judge learning from verdicts
|
||||
raea-sys-notice = { path = "../../systems/notice" }
|
||||
# raea scene faults --clip: a character's motion held to what a body does
|
||||
raea-sys-motionfaults = { path = "../../systems/motionfaults" }
|
||||
raea-sys-body = { path = "../../systems/body" }
|
||||
# each part's planned detail beside how large the frames show it (MK21, MK23)
|
||||
raea-runtime-lod-plan = { path = "../../runtime/lod-plan" }
|
||||
# its results as Findings (docs/direction.feature DR3)
|
||||
raea-core-facts = { path = "../../core/facts" }
|
||||
# camera clearance (MK16): the parts, their models' triangles, and the camera's point in space
|
||||
raea-core-scene = { path = "../../core/scene" }
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
|
||||
dunce = "1"
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,164 @@
|
||||
//! `raea scene faults EDIT.tsx --composition ID --motion`: the composition's characters held to what a body does
|
||||
//! (raea-sys-motionfaults), read from the scene itself, with no clip written out. raea/character's `<Character>` draws
|
||||
//! each joint as a marker part named `<name>-<joint>` (its joint.glb) at the joint's place and turn, and every joint's
|
||||
//! rest frame is the world's, so a joint's turn from rest against its parent is its parent's world turn undone from its
|
||||
//! own: each frame's pose comes back exactly. The skeleton is the body's skeleton.json beside its joint.glb.
|
||||
//!
|
||||
//! And the hands against the scene: each finger bone, the thumb's too, as a segment from its joint toward its tip,
|
||||
//! tested against every other part's real triangles (raea-sys-notice's BVH). A bone that crosses a surface has gone in
|
||||
//! at least a finger's half thickness: a thumb through a grip, fingers through a mug's wall. And the other way: while
|
||||
//! two or more fingertips rest on a surface (the hand holds something), a tip left 3 cm or more off it hasn't closed:
|
||||
//! the thumb not wrapping round a post.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use bevy::math::{Quat, Vec3};
|
||||
use raea_core_scene::Item;
|
||||
use raea_sys_body::rig::{FINGERS, Pose, Side, Skeleton};
|
||||
use raea_sys_motionfaults::{Clip, Fault, Hit, grip, stretches};
|
||||
use serde_json::Value;
|
||||
|
||||
/// A distal bone is tested this far toward its tip (its tip is the skin's end, which rests on what it touches).
|
||||
const ALONG: f32 = 0.85;
|
||||
|
||||
fn name(it: &Item) -> Option<&str> {
|
||||
it.props.get("name").and_then(Value::as_str)
|
||||
}
|
||||
|
||||
/// The characters on a frame: each one's name and the folder its joint.glb is in.
|
||||
fn characters(its: &[Item]) -> Vec<(String, String)> {
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
for it in its {
|
||||
let (Some(n), Some(src)) = (name(it), it.props.get("src").and_then(Value::as_str)) else { continue };
|
||||
if let (Some(body), true) = (n.strip_suffix("-body"), src.ends_with("/body.glb")) {
|
||||
let folder = src.trim_end_matches("/body.glb").to_string();
|
||||
if !out.iter().any(|o| o.0 == body) {
|
||||
out.push((body.to_string(), folder));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The body's skeleton.json, its folder as the scene names it found from the composition's folder up.
|
||||
fn skeleton(dir: &Path, folder: &str) -> Option<(PathBuf, Skeleton)> {
|
||||
let rel = folder.trim_start_matches('/');
|
||||
for up in dir.ancestors().take(4) {
|
||||
for sub in ["", "media", "assets", "public", "compositions/media"] {
|
||||
let p = up.join(sub).join(rel).join("skeleton.json");
|
||||
if let Ok(t) = std::fs::read_to_string(&p) {
|
||||
return Skeleton::from_json(&t).ok().map(|s| (p, s));
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// A part's place and turn (its scale taken out).
|
||||
fn placed(it: &Item) -> (Vec3, Quat) {
|
||||
let (_, r, t) = it.world.to_scale_rotation_translation();
|
||||
(t, r)
|
||||
}
|
||||
|
||||
/// One character's frames as a clip, and each frame's joint places in the scene (for the hands against it).
|
||||
fn clip_of(skel: &Skeleton, who: &str, frames: &[Vec<Item>], fps: f32) -> (Clip, Vec<Vec<Option<(Vec3, Quat)>>>) {
|
||||
let (mut poses, mut places) = (Vec::new(), Vec::new());
|
||||
for its in frames {
|
||||
let at: Vec<Option<(Vec3, Quat)>> = skel.joints.iter().map(|j| its.iter().find(|it| name(it) == Some(&format!("{who}-{}", j.name))).map(placed)).collect();
|
||||
let mut p: Pose = skel.rest();
|
||||
for (i, j) in skel.joints.iter().enumerate() {
|
||||
let Some((pos, rot)) = at[i] else { continue };
|
||||
match j.parent.and_then(|q| at[q]) {
|
||||
Some((_, prot)) => p.turns[i] = (prot.inverse() * rot).normalize(),
|
||||
None if j.parent.is_none() => {
|
||||
p.turns[i] = rot;
|
||||
p.root = pos;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
poses.push(p);
|
||||
places.push(at);
|
||||
}
|
||||
(Clip { skel: skel.clone(), fps, poses, held: None }, places)
|
||||
}
|
||||
|
||||
/// The hands against the scene's other parts, frame by frame: finger bones through a surface (`through`), and tips
|
||||
/// left off what the hand holds (`grip`), as faults over the stretches they last.
|
||||
fn hands(skel: &Skeleton, who: &str, frames: &[Vec<Item>], places: &[Vec<Option<(Vec3, Quat)>>], numbers: &[i64]) -> Vec<Fault> {
|
||||
let mut hits: Vec<Hit> = Vec::new();
|
||||
let bones: Vec<usize> = Side::BOTH.iter().flat_map(|&s| FINGERS.iter().filter_map(move |f| skel.finger(f, s))).flatten().collect();
|
||||
let tips: Vec<Vec<usize>> = Side::BOTH.iter().map(|&s| FINGERS.iter().filter_map(|f| skel.finger(f, s).map(|b| b[2])).collect()).collect();
|
||||
for (k, its) in frames.iter().enumerate() {
|
||||
// the scene but the character itself (its skin is drawn at its bind pose in the parts, its markers are specks)
|
||||
let mine = format!("{who}-");
|
||||
let others: Vec<Item> = its.iter().filter(|it| !name(it).is_some_and(|n| n.starts_with(&mine))).cloned().collect();
|
||||
// every part: a mesh's place is often in its own vertices, its transform the world's origin (gambit's ladder lab),
|
||||
// so nothing can be left out by where its transform sits
|
||||
if bones.iter().all(|&i| places[k][i].is_none()) {
|
||||
continue;
|
||||
}
|
||||
let near: Vec<Item> = others.into_iter().filter(|it| it.kind != "camera").collect();
|
||||
let scene = raea_sys_notice::Scene::of(&near);
|
||||
let bone = |i: usize, along: f32| places[k][i].map(|(a, rot)| (a, a + rot * ((skel.joints[i].tail - skel.joints[i].head) * along)));
|
||||
for &i in &bones {
|
||||
if let Some((a, b)) = bone(i, ALONG)
|
||||
&& scene.blocked(a, b, 0.0)
|
||||
{
|
||||
hits.push(Hit { check: "through", joint: skel.joints[i].name.clone(), f: k, value: 0.0, unit: "m", what: String::new() });
|
||||
}
|
||||
}
|
||||
for side in &tips {
|
||||
let off: Vec<(usize, f32)> = side.iter().filter_map(|&i| bone(i, 1.0).map(|(_, tip)| (i, scene.reach(tip, grip::LOOK)))).collect();
|
||||
for o in grip::open(&off.iter().map(|o| o.1).collect::<Vec<_>>()) {
|
||||
hits.push(Hit { check: "grip", joint: skel.joints[off[o].0].name.clone(), f: k, value: off[o].1, unit: "m", what: String::new() });
|
||||
}
|
||||
}
|
||||
}
|
||||
// one fault per check and joint while the frames run on, as a clip's are (motionfaults' stretches)
|
||||
let mut out = stretches(hits);
|
||||
for f in &mut out {
|
||||
(f.from, f.to, f.peak) = (numbers[f.from] as usize, numbers[f.to] as usize, numbers[f.peak] as usize);
|
||||
f.says = match f.check {
|
||||
"grip" => format!("{} is {:.0} mm off what the hand holds (it hasn't closed on it), frames {}-{}", f.joint, f.value * 1000.0, f.from, f.to),
|
||||
_ => format!("{} passes through a part of the scene, frames {}-{}", f.joint, f.from, f.to),
|
||||
};
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One character's findings over the composition's frames.
|
||||
pub struct Found {
|
||||
pub who: String,
|
||||
pub skeleton: PathBuf,
|
||||
pub frames: usize,
|
||||
pub faults: Vec<Fault>,
|
||||
}
|
||||
|
||||
/// Every character's motion faults over the frames given (their numbers alongside); a character whose skeleton.json
|
||||
/// can't be found is said in the second list.
|
||||
pub fn run(dir: &Path, frames: &[(i64, Vec<Item>)], fps: f32) -> Result<(Vec<Found>, Vec<String>), String> {
|
||||
let Some((_, first)) = frames.first() else { return Err("no frames".into()) };
|
||||
let found = characters(first);
|
||||
if found.is_empty() {
|
||||
return Err("no characters in the composition (a <Character> draws <name>-body and <name>-<joint> parts)".into());
|
||||
}
|
||||
let numbers: Vec<i64> = frames.iter().map(|f| f.0).collect();
|
||||
let items: Vec<Vec<Item>> = frames.iter().map(|f| f.1.clone()).collect();
|
||||
let (mut out, mut missing) = (Vec::new(), Vec::new());
|
||||
for (who, folder) in found {
|
||||
let Some((path, skel)) = skeleton(dir, &folder) else {
|
||||
missing.push(format!("{who}: no skeleton.json for {folder}, not checked"));
|
||||
continue;
|
||||
};
|
||||
let (clip, places) = clip_of(&skel, &who, &items, fps);
|
||||
let mut faults = raea_sys_motionfaults::check(&clip);
|
||||
// the clip's frames are the composition's from its first
|
||||
for f in &mut faults {
|
||||
(f.from, f.to, f.peak) = (numbers[f.from] as usize, numbers[f.to.min(numbers.len() - 1)] as usize, numbers[f.peak] as usize);
|
||||
}
|
||||
faults.extend(hands(&skel, &who, &items, &places, &numbers));
|
||||
out.push(Found { who, skeleton: path, frames: clip.poses.len(), faults });
|
||||
}
|
||||
Ok((out, missing))
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
//! Camera clearance (docs/goal.feature MK16, from AnyShot's clearance pass): every frame, how near the camera passes to
|
||||
//! each solid part, and where it comes closer than a person carrying it could (0.45 m by default). A camera that
|
||||
//! grazes a door frame or pushes into a desk draws the inside of the part, or a wall filling the frame; the boxes the
|
||||
//! stage keeps say it without drawing. Only solids count: volumes, decals, footage, 2D, see-through parts (glass) and
|
||||
//! anything under 5 cm across are passed over. A part's box answers first; a model whose box comes close is measured
|
||||
//! on its triangles (a room model round the camera, a tree's box that's mostly air).
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use bevy::math::{Mat4, Vec3};
|
||||
use raea_core_facts::{Finding, Level};
|
||||
use raea_core_scene::Item;
|
||||
use serde_json::Value;
|
||||
|
||||
use raea_sys_stage::{View, called, model_box, own_box};
|
||||
|
||||
/// Parts smaller than this across (metres) are passed over: a pen the camera brushes isn't a collision.
|
||||
const SMALL: f32 = 0.05;
|
||||
/// Clearance the shot language asks of a carried camera, metres.
|
||||
pub const DEFAULT: f32 = 0.45;
|
||||
|
||||
fn see_through(it: &Item) -> bool {
|
||||
let props = it.material.as_ref().map(|m| &m.props);
|
||||
let n = |k: &str| props.and_then(|p| p.get(k)).or(it.props.get(k)).and_then(Value::as_f64);
|
||||
n("specular_transmission").or(n("transmission")).is_some_and(|t| t > 0.3) || n("opacity").is_some_and(|o| o < 0.5)
|
||||
}
|
||||
|
||||
/// The nearest distance from `p` (world) to a box [lo, hi] in a part's own space under `world`, in world metres.
|
||||
pub fn to_box(world: &Mat4, lo: Vec3, hi: Vec3, p: Vec3) -> f32 {
|
||||
let local = world.inverse().transform_point3(p);
|
||||
let near = local.clamp(lo, hi);
|
||||
world.transform_point3(near).distance(p)
|
||||
}
|
||||
|
||||
/// The nearest distance from `p` to a triangle.
|
||||
pub fn to_tri(p: Vec3, t: &[Vec3; 3]) -> f32 {
|
||||
let (a, b, c) = (t[0], t[1], t[2]);
|
||||
let (ab, ac, ap) = (b - a, c - a, p - a);
|
||||
let (d1, d2) = (ab.dot(ap), ac.dot(ap));
|
||||
if d1 <= 0.0 && d2 <= 0.0 {
|
||||
return p.distance(a);
|
||||
}
|
||||
let bp = p - b;
|
||||
let (d3, d4) = (ab.dot(bp), ac.dot(bp));
|
||||
if d3 >= 0.0 && d4 <= d3 {
|
||||
return p.distance(b);
|
||||
}
|
||||
let vc = d1 * d4 - d3 * d2;
|
||||
if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 {
|
||||
return p.distance(a + ab * (d1 / (d1 - d3)));
|
||||
}
|
||||
let cp = p - c;
|
||||
let (d5, d6) = (ab.dot(cp), ac.dot(cp));
|
||||
if d6 >= 0.0 && d5 <= d6 {
|
||||
return p.distance(c);
|
||||
}
|
||||
let vb = d5 * d2 - d1 * d6;
|
||||
if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 {
|
||||
return p.distance(a + ac * (d2 / (d2 - d6)));
|
||||
}
|
||||
let va = d3 * d6 - d5 * d4;
|
||||
if va <= 0.0 && (d4 - d3) >= 0.0 && (d5 - d6) >= 0.0 {
|
||||
return p.distance(b + (c - b) * ((d4 - d3) / ((d4 - d3) + (d5 - d6))));
|
||||
}
|
||||
let denom = 1.0 / (va + vb + vc);
|
||||
p.distance(a + ab * (vb * denom) + ac * (vc * denom))
|
||||
}
|
||||
|
||||
/// A frame's nearest solid parts to its camera: (part, distance) for each closer than `min`.
|
||||
pub fn near_parts(its: &[Item], eye: Vec3, min: f32, boxes: &mut HashMap<String, Option<(Vec3, Vec3)>>, tris: &mut HashMap<String, Option<Vec<[Vec3; 3]>>>) -> Vec<(String, f32)> {
|
||||
let mut out = Vec::new();
|
||||
for it in its {
|
||||
if !matches!(it.kind, "mesh" | "model") || it.at.is_some() || see_through(it) {
|
||||
continue;
|
||||
}
|
||||
let bx = if it.kind == "mesh" { own_box(it, boxes) } else { model_box(it, boxes) };
|
||||
let Some((lo, hi)) = bx else { continue };
|
||||
let ext = (hi - lo) * it.world.to_scale_rotation_translation().0.abs();
|
||||
if ext.max_element() < SMALL {
|
||||
continue;
|
||||
}
|
||||
let mut d = to_box(&it.world, lo, hi, eye);
|
||||
if d >= min {
|
||||
continue;
|
||||
}
|
||||
if it.kind == "model" {
|
||||
let Some(src) = it.props.get("src").and_then(Value::as_str).map(raea_core_scene::src_path) else { continue };
|
||||
let t = tris.entry(src.clone()).or_insert_with(|| raea_core_scene::gltf_tris(&src).ok().map(|(g, _)| g.into_iter().flat_map(|(_, t)| t).collect()));
|
||||
if let Some(t) = t {
|
||||
let local = it.world.inverse().transform_point3(eye);
|
||||
// nearest in the model's own space, then measured in the world's (a scaled model's metres)
|
||||
if let Some(best) = t.iter().min_by(|a, b| to_tri(local, a).total_cmp(&to_tri(local, b))) {
|
||||
let near = nearest_on(local, best);
|
||||
d = it.world.transform_point3(near).distance(eye);
|
||||
}
|
||||
}
|
||||
}
|
||||
if d < min {
|
||||
out.push((called(it), d));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The point on a triangle nearest `p` (by projecting and clamping through `to_tri`'s regions, sampled finely enough
|
||||
/// to measure a clearance to the millimetre).
|
||||
fn nearest_on(p: Vec3, t: &[Vec3; 3]) -> Vec3 {
|
||||
let (a, b, c) = (t[0], t[1], t[2]);
|
||||
let n = (b - a).cross(c - a);
|
||||
let l2 = n.length_squared();
|
||||
if l2 > 1e-14 {
|
||||
let q = p - n * ((p - a).dot(n) / l2);
|
||||
// barycentric: inside, the projection is the nearest point
|
||||
let (v0, v1, v2) = (b - a, c - a, q - a);
|
||||
let (d00, d01, d11, d20, d21) = (v0.dot(v0), v0.dot(v1), v1.dot(v1), v2.dot(v0), v2.dot(v1));
|
||||
let den = d00 * d11 - d01 * d01;
|
||||
if den.abs() > 1e-14 {
|
||||
let v = (d11 * d20 - d01 * d21) / den;
|
||||
let w = (d00 * d21 - d01 * d20) / den;
|
||||
if v >= 0.0 && w >= 0.0 && v + w <= 1.0 {
|
||||
return q;
|
||||
}
|
||||
}
|
||||
}
|
||||
// outside: the nearest point of the three edges
|
||||
let seg = |x: Vec3, y: Vec3| {
|
||||
let d = y - x;
|
||||
x + d * ((p - x).dot(d) / d.length_squared().max(1e-14)).clamp(0.0, 1.0)
|
||||
};
|
||||
[seg(a, b), seg(b, c), seg(c, a)].into_iter().min_by(|u, v| u.distance(p).total_cmp(&v.distance(p))).unwrap_or(a)
|
||||
}
|
||||
|
||||
/// Every frame's camera held `min` metres off every solid part: a finding for each part and run of frames it comes
|
||||
/// closer, with the nearest it gets.
|
||||
pub fn clearance(all: &[Vec<Item>], frames: &[i64], w: u32, h: u32, fps: f64, min: f32, by: &str) -> Vec<Finding> {
|
||||
let (mut boxes, mut tris) = (HashMap::new(), HashMap::new());
|
||||
// part -> runs of (first frame index, last, nearest)
|
||||
let mut runs: Vec<(String, usize, usize, f32)> = Vec::new();
|
||||
let mut open: HashMap<String, usize> = HashMap::new();
|
||||
for (k, its) in all.iter().enumerate() {
|
||||
let Some(v) = View::of(its, w, h) else { continue };
|
||||
let near = near_parts(its, v.eye, min, &mut boxes, &mut tris);
|
||||
let names: Vec<&String> = near.iter().map(|n| &n.0).collect();
|
||||
open.retain(|name, _| names.contains(&name));
|
||||
for (name, d) in near {
|
||||
match open.get(&name).copied() {
|
||||
Some(r) if runs[r].2 + 1 == k && frames[k] == frames[runs[r].2] + 1 => {
|
||||
runs[r].2 = k;
|
||||
runs[r].3 = runs[r].3.min(d);
|
||||
}
|
||||
_ => {
|
||||
runs.push((name.clone(), k, k, d));
|
||||
open.insert(name, runs.len() - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
runs.into_iter()
|
||||
.map(|(name, a, b, d)| {
|
||||
let (fa, fb) = (frames[a], frames[b]);
|
||||
let when = if a == b { format!("at frame {fa} ({:.2} s)", fa as f64 / fps) } else { format!("over frames {fa}-{fb} ({:.2}-{:.2} s)", fa as f64 / fps, fb as f64 / fps) };
|
||||
let says = if d < 1e-3 {
|
||||
format!("the camera is inside `{name}` {when}: move the path out of it, or the part")
|
||||
} else {
|
||||
format!("the camera passes {d:.2} m from `{name}` {when}, under the {min:.2} m a carried camera keeps: move the path or the part, or pass a smaller --clearance for a camera on a rig")
|
||||
};
|
||||
Finding::new("camera-clearance", Level::Error, says, by).frames(fa, fb + 1)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn item(kind: &'static str, props: Value, world: Mat4) -> Item {
|
||||
Item { kind, props: Arc::new(props.as_object().cloned().unwrap_or_default()), shape: None, at: None, material: None, world }
|
||||
}
|
||||
|
||||
/// A camera at `eye` looking at `at`, 50 degrees.
|
||||
fn cam(eye: [f32; 3], at: [f32; 3]) -> Item {
|
||||
item("camera", json!({"position": eye, "lookAt": at, "fov": 50}), Mat4::IDENTITY)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distances_to_a_box_and_a_triangle() {
|
||||
let w = Mat4::from_translation(Vec3::new(0.0, 0.5, 0.0));
|
||||
let (lo, hi) = (Vec3::splat(-0.5), Vec3::splat(0.5));
|
||||
assert!((to_box(&w, lo, hi, Vec3::new(0.0, 0.5, 1.5)) - 1.0).abs() < 1e-5);
|
||||
assert_eq!(to_box(&w, lo, hi, Vec3::new(0.0, 0.5, 0.0)), 0.0);
|
||||
let t = [Vec3::ZERO, Vec3::X, Vec3::Z];
|
||||
assert!((to_tri(Vec3::new(0.25, 0.3, 0.25), &t) - 0.3).abs() < 1e-5);
|
||||
assert!((to_tri(Vec3::new(-1.0, 0.0, 0.0), &t) - 1.0).abs() < 1e-5);
|
||||
assert!((nearest_on(Vec3::new(0.25, 0.3, 0.25), &t) - Vec3::new(0.25, 0.0, 0.25)).length() < 1e-5);
|
||||
}
|
||||
|
||||
fn solid(name: &str, size: [f32; 3], at: [f32; 3]) -> Item {
|
||||
let mut it = item("mesh", json!({"name": name}), Mat4::from_translation(Vec3::from(at)));
|
||||
it.shape = Some(format!("box({}, {}, {})", size[0], size[1], size[2]).into());
|
||||
it
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_camera_pushing_into_a_desk_is_found_and_a_small_or_glass_part_is_not() {
|
||||
// a desk 1.6 x 0.75 x 0.8 m standing at the origin; the camera pushes in from 2 m to 0.1 m off its front face
|
||||
let desk = solid("desk", [1.6, 0.75, 0.8], [0.0, 0.375, 0.0]);
|
||||
let pen = solid("pen", [0.04, 0.01, 0.01], [0.0, 1.0, 0.45]);
|
||||
let mut glass = solid("pane", [1.0, 1.0, 0.01], [0.0, 1.0, 0.3]);
|
||||
glass.props = Arc::new(json!({"name": "pane", "specular_transmission": 0.9}).as_object().cloned().unwrap());
|
||||
let zs = [2.4, 1.6, 1.0, 0.7, 0.5, 2.4];
|
||||
let all: Vec<Vec<Item>> = zs.iter().map(|z| vec![cam([0.0, 0.6, *z], [0.0, 0.4, 0.0]), desk.clone(), pen.clone(), glass.clone()]).collect();
|
||||
let frames: Vec<i64> = (0..zs.len() as i64).collect();
|
||||
let f = clearance(&all, &frames, 640, 360, 30.0, DEFAULT, "t");
|
||||
// the desk's face is at z 0.4: frames 3 and 4 come within 0.3 and 0.1 m; one run, its nearest said
|
||||
assert_eq!(f.len(), 1, "{f:?}");
|
||||
assert!(f[0].says.contains("0.10 m from `desk` over frames 3-4"), "{}", f[0].says);
|
||||
assert_eq!(f[0].level, Level::Error);
|
||||
// a rig's camera may come closer
|
||||
assert!(clearance(&all, &frames, 640, 360, 30.0, 0.05, "t").is_empty());
|
||||
// inside it, said so
|
||||
let inside = vec![vec![cam([0.0, 0.3, 0.0], [0.0, 0.3, -1.0]), desk.clone()]];
|
||||
assert!(clearance(&inside, &[0], 640, 360, 30.0, DEFAULT, "t")[0].says.contains("inside `desk`"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
//! `raea scene faults EDIT.tsx`: the lint's findings judged as a viewer of the shot would see them (raea-sys-notice):
|
||||
//! every frame's camera asked where each one shows and how large, a small model saying how likely it is to read as a
|
||||
//! fault, the likeliest first. Hidden ones (walls meeting the ceiling inside the slab) are counted, not listed.
|
||||
//!
|
||||
//! It learns: `--real KEY` and `--fine KEY` keep a verdict on a finding beside the project (review/
|
||||
//! faults.labels.jsonl), and a finding the last run said that's gone while both its parts remain is kept as fixed,
|
||||
//! so real. `raea scene faults train [FOLDER]` fits the model to every project's verdicts under FOLDER.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use raea_runtime_bundle::{bundle_composition, comp_opts};
|
||||
use raea_runtime_export::{frame_of, items};
|
||||
use raea_sys_notice::{FAULT, Judged, Model, labels};
|
||||
|
||||
/// The most frames whose cameras are asked (evenly over the shot).
|
||||
const CAMERAS: usize = 48;
|
||||
|
||||
pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
let Some(edit) = args.get(2) else { return Err(crate::USAGE.into()) };
|
||||
if edit == "train" {
|
||||
return train(args.get(3).map(String::as_str));
|
||||
}
|
||||
if edit == "--clip" {
|
||||
return crate::motion::cli(args);
|
||||
}
|
||||
let tsx = dunce::canonicalize(std::path::PathBuf::from(edit)).map_err(|e| format!("{edit}: {e}"))?;
|
||||
let dir = tsx.parent().unwrap().to_path_buf();
|
||||
let frame = frame_of(args)?;
|
||||
let opts = comp_opts(args)?;
|
||||
let shot = opts.composition.clone().unwrap_or_default();
|
||||
let js = std::env::temp_dir().join(format!("raea-faults-{}.js", std::process::id()));
|
||||
bundle_composition(&tsx, &js, &opts, None)?;
|
||||
let got = raea_runtime_export::scene_frames(&js, &dir, 0, true, &[]);
|
||||
let _ = std::fs::remove_file(&js);
|
||||
let (frames, w, h, fps) = got?.ok_or("the composition has no 3D")?;
|
||||
// the composition's characters held to what a body does, read from the scene (chars.rs)
|
||||
if args.iter().any(|a| a == "--motion") {
|
||||
let all: Vec<(i64, Vec<raea_core_scene::Item>)> = frames.iter().map(|fr| (fr.0, items(&fr.1))).collect();
|
||||
let (text, v, n) = crate::motion::composition(&tsx, &shot, &dir, &all, fps as f32, args)?;
|
||||
return finish(if args.iter().any(|a| a == "--json") { serde_json::to_string_pretty(&v).unwrap_or_default() } else { text }, n);
|
||||
}
|
||||
let k = frames.iter().position(|(f, _)| *f == frame).ok_or_else(|| format!("no frame {frame}"))?;
|
||||
let other = if k + 1 < frames.len() { k + 1 } else { k.saturating_sub(1) };
|
||||
let (now, next) = (items(&frames[k].1), items(&frames[other].1));
|
||||
let (found, _) = raea_sys_contact::lint(&now, &next);
|
||||
// the cameras: the frame's own and evenly over the rest of the shot
|
||||
let step = frames.len().div_ceil(CAMERAS).max(1);
|
||||
let mut views = vec![now.clone()];
|
||||
for (i, (_, fr)) in frames.iter().enumerate() {
|
||||
if i != k && i % step == 0 {
|
||||
views.push(items(fr));
|
||||
}
|
||||
}
|
||||
let model = Model::load();
|
||||
let judged = raea_sys_notice::judge(&found, &views, w, h, &model);
|
||||
// faults of known size planted and judged: the judge measured, nothing kept (seed.rs)
|
||||
if let Some(n) = raea_runtime_bundle::flag(args, "--seed") {
|
||||
let n = n.parse::<usize>().map_err(|_| "--seed takes how many faults to plant")?;
|
||||
return Ok(crate::seed::run(&now, &next, &views, &found, w, h, &model, n));
|
||||
}
|
||||
|
||||
// what it learns from: this run against the last, and any verdict given now
|
||||
let project = labels::project_of(&tsx);
|
||||
let keys: Vec<String> = judged.iter().map(|j| j.fault.key.clone()).collect();
|
||||
let parts: Vec<String> = found.iter().flat_map(|v| ["part", "on", "into"].into_iter().filter_map(move |n| v[n].as_str())).map(String::from).collect();
|
||||
let mut rows = labels::fixed(&labels::last(&project, &shot), &keys, &parts);
|
||||
let fixed = rows.len();
|
||||
for (name, real) in [("--real", true), ("--fine", false)] {
|
||||
for key in raea_runtime_bundle::flags(args, name) {
|
||||
let j = judged.iter().find(|j| j.fault.key == key).ok_or_else(|| format!("{name} {key}: no finding by that key on this shot (keys are listed with --json, or after each line)"))?;
|
||||
rows.push(labels::row(&key, real, "marked", &shot, &j.x, &j.toks));
|
||||
}
|
||||
}
|
||||
labels::append(&project, &rows)?;
|
||||
let last: Vec<Value> = judged.iter().map(|j| json!({"key": j.fault.key, "part": j.fault.part, "into": j.fault.into, "x": j.x, "toks": j.toks, "shot": shot})).collect();
|
||||
labels::keep_last(&project, &shot, last)?;
|
||||
|
||||
let faults: Vec<&Judged> = judged.iter().filter(|j| j.p >= FAULT).collect();
|
||||
let hidden = judged.iter().filter(|j| j.seen.shown == 0).count();
|
||||
if args.iter().any(|a| a == "--json") {
|
||||
let rows: Vec<Value> = judged
|
||||
.iter()
|
||||
.map(|j| json!({"key": j.fault.key, "check": j.fault.check, "part": j.fault.part, "into": j.fault.into, "p": (j.p * 1e3).round() / 1e3, "fault": j.p >= FAULT,
|
||||
"seen": {"frames": j.seen.frames, "shown": j.seen.shown, "px": (j.seen.px * 10.0).round() / 10.0, "near": (j.seen.near * 1e3).round() / 1e3}, "says": j.fault.says}))
|
||||
.collect();
|
||||
let text = serde_json::to_string_pretty(&json!({"frame": frame, "model": model.from, "labels": model.labels, "findings": rows, "faults": faults.len(), "hidden": hidden, "fixed": fixed})).unwrap_or_default();
|
||||
return finish(text, faults.len());
|
||||
}
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for j in &judged {
|
||||
if j.seen.shown == 0 && j.p < FAULT {
|
||||
continue;
|
||||
}
|
||||
let tag = if j.p >= FAULT { "FAULT" } else { "maybe" };
|
||||
out.push(format!("{:.2} {tag} {} (seen on {}/{} frames, {:.1} px, {:.2} m off) key: {}", j.p, j.fault.says, j.seen.shown, j.seen.frames, j.seen.px, j.seen.near, j.fault.key));
|
||||
}
|
||||
out.push(format!(
|
||||
"frame {frame}: {} findings, {} likely faults, {} seen but likely fine, {hidden} no camera sees; judged by {} ({} labels){}",
|
||||
judged.len(),
|
||||
faults.len(),
|
||||
judged.len() - faults.len() - judged.iter().filter(|j| j.seen.shown == 0 && j.p < FAULT).count(),
|
||||
model.from,
|
||||
model.labels,
|
||||
if fixed > 0 { format!("; {fixed} fixed since the last run, kept as real") } else { String::new() }
|
||||
));
|
||||
finish(out.join("\n"), faults.len())
|
||||
}
|
||||
|
||||
/// Faults fail it, as the lint's errors do.
|
||||
fn finish(text: String, faults: usize) -> Result<String, String> {
|
||||
if faults > 0 {
|
||||
println!("{text}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
/// `raea scene faults train [FOLDER]`: every project's verdicts under FOLDER (default: here) fitted, the model kept in
|
||||
/// raea's models folder for every run after.
|
||||
fn train(root: Option<&str>) -> Result<String, String> {
|
||||
let root = std::path::PathBuf::from(root.unwrap_or("."));
|
||||
let files = labels::files(&root, 4);
|
||||
let ex: Vec<_> = files.iter().flat_map(|f| labels::examples(f)).collect();
|
||||
if ex.is_empty() {
|
||||
return Err(format!("no verdicts under {} (review/faults.labels.jsonl: --real KEY, --fine KEY, and fixes)", root.display()));
|
||||
}
|
||||
let m = Model::fit(&ex);
|
||||
let right = ex.iter().filter(|(x, t, y)| (m.score(x, t) >= FAULT) == (*y >= 0.5)).count();
|
||||
let before = ex.iter().filter(|(x, t, y)| (Model::prior().score(x, t) >= FAULT) == (*y >= 0.5)).count();
|
||||
let p = raea_sys_notice::model::path();
|
||||
std::fs::create_dir_all(p.parent().unwrap()).map_err(|e| e.to_string())?;
|
||||
std::fs::write(&p, serde_json::to_string_pretty(&m.to_json()).unwrap_or_default()).map_err(|e| format!("{}: {e}", p.display()))?;
|
||||
let real = ex.iter().filter(|e| e.2 >= 0.5).count();
|
||||
// held out: each finding (one finding judged on two shots shares its words) fitted without, then asked
|
||||
let (held, finds) = held_out(&ex.iter().map(|e| (e.1.clone(), e.0.clone(), e.1.clone(), e.2)).collect::<Vec<_>>());
|
||||
// and a shot at a time (each project's own shot names, so a shot is a project's view): a scene it has never seen
|
||||
let by_shot: Vec<_> = files.iter().enumerate().flat_map(|(n, f)| labels::shots(f).into_iter().map(move |(s, x, t, y)| (format!("{n}/{s}"), x, t, y))).collect();
|
||||
let (unseen, names) = held_out(&by_shot);
|
||||
Ok(format!(
|
||||
"{} verdicts on {} findings from {} projects ({real} real, {} fine): the prior agreed with {before}, the fitted judge with {right}, with {held} each fitted without its own finding (held out), and with {unseen} each fitted without its whole shot ({} shots, a scene it hasn't seen); kept in {}\n{}",
|
||||
ex.len(),
|
||||
finds,
|
||||
files.len(),
|
||||
ex.len() - real,
|
||||
names,
|
||||
p.display(),
|
||||
crate::motion::train()?
|
||||
))
|
||||
}
|
||||
|
||||
/// Verdicts a judge gets right fitted without their own group (a finding's words, a shot): each group left out in
|
||||
/// turn, fitted on the rest, then asked. With how many groups there were.
|
||||
fn held_out<K: Ord>(rows: &[(K, Vec<f32>, Vec<String>, f32)]) -> (usize, usize) {
|
||||
let mut groups: Vec<&K> = rows.iter().map(|r| &r.0).collect();
|
||||
groups.sort();
|
||||
groups.dedup();
|
||||
let (mut right, n) = (0, groups.len());
|
||||
for g in groups {
|
||||
let rest: Vec<_> = rows.iter().filter(|r| &r.0 != g).map(|r| (r.1.clone(), r.2.clone(), r.3)).collect();
|
||||
let m = Model::fit(&rest);
|
||||
right += rows.iter().filter(|r| &r.0 == g && (m.score(&r.1, &r.2) >= FAULT) == (r.3 >= 0.5)).count();
|
||||
}
|
||||
(right, n)
|
||||
}
|
||||
+16
-3
@@ -1,16 +1,27 @@
|
||||
//! `raea scene lint|explain|light|stage`: a composition's frames stepped without drawing and handed to raea-sys-contact
|
||||
//! `raea scene lint|explain|light|stage|lod`: a composition's frames stepped without drawing and handed to raea-sys-contact
|
||||
//! (what each part rests on, and parts that clip), raea-sys-light-meter (the light on a subject) and raea-sys-stage (3D
|
||||
//! type that can't be read, parts that snap, a camera that lurches, empty frames: docs/stage-guards.feature).
|
||||
//! type that can't be read, parts that snap, a camera that lurches, empty frames: docs/stage-guards.feature). `lod` is
|
||||
//! each part's planned detail beside how large the frames show it (docs/goal.feature MK23).
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use raea_runtime_bundle::{bundle_composition, comp_opts};
|
||||
use raea_runtime_export::{frame_of, items};
|
||||
|
||||
// how near the camera passes to each solid part, every frame (`--clearance M`, MK16)
|
||||
pub mod clearance;
|
||||
// the lint's findings judged as a viewer of the shot would see them, learning from verdicts (raea-sys-notice)
|
||||
mod chars;
|
||||
mod faults;
|
||||
mod motion;
|
||||
// faults of known size planted, to measure the judge (`faults --seed N`)
|
||||
mod seed;
|
||||
mod light;
|
||||
// each part's planned detail beside how large the frames show it (MK23)
|
||||
pub mod lod;
|
||||
mod stage;
|
||||
|
||||
pub const USAGE: &str = "raea scene lint|explain|light|stage EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--json]";
|
||||
pub const USAGE: &str = "raea scene lint|explain|faults|light|stage|lod EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--real KEY] [--fine KEY] [--seed N] [--motion] [--json] | raea scene faults train [FOLDER] | raea scene faults --clip CLIP.json|FOLDER [--real KEY] [--fine KEY] [--fine-from N] [--fine-upto N] [--real-from N] [--real-upto N] [--by NAME] [--seed N] [--json]";
|
||||
|
||||
/// `raea scene lint|explain EDIT.tsx [--composition ID] [--frame N] [--json]`: the frame's parts measured
|
||||
/// (frame 0 by default). `lint` says the faults (errors fail it: floating, sunk, clipping; warnings: in the air,
|
||||
@@ -22,6 +33,8 @@ pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
match mode {
|
||||
"light" => return light::cli(args),
|
||||
"stage" => return stage::cli(args),
|
||||
"lod" => return lod::cli(args),
|
||||
"faults" => return faults::cli(args),
|
||||
"lint" | "explain" => {}
|
||||
_ => return Err(usage.into()),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
//! `raea scene lod EDIT.tsx [--composition ID] [--from N] [--to N] [--json]` (docs/goal.feature MK23): every part's
|
||||
//! planned detail beside how large the frames show it. A part's plan is its own `lod` (0 the hero to 4 far), else its
|
||||
//! name's on the job's plan (`lod` on brief.ts's make objects); what a frame shows is how much of it the part's box
|
||||
//! spans (raea-runtime-lod-plan). The table lists the planned parts first, the ones seen closer than planned on top,
|
||||
//! then the parts nobody planned by how large they get, so a part forgotten since the plan was written is found by
|
||||
//! reading down it. A part seen two or more levels finer than planned fails it, as it fails a render.
|
||||
|
||||
use raea_core_facts::{Finding, Level, finding};
|
||||
use raea_runtime_lod_plan::{ordered, table};
|
||||
use serde_json::json;
|
||||
|
||||
pub(crate) fn cli(args: &[String]) -> Result<String, String> {
|
||||
let crate::stage::Stepped { items, nums, size: (w, h, fps), dir } = crate::stage::stepped(args, "raea scene lod EDIT.tsx [--composition ID] [--from N] [--to N] [--json]")?;
|
||||
let (first, last) = (nums[0], nums[nums.len() - 1]);
|
||||
let plan = raea_runtime_lod_plan::plan::lods(&dir);
|
||||
let mut unseen: Vec<String> = plan.keys().cloned().collect();
|
||||
let (seen, fs) = raea_runtime_lod_plan::lods(&items, &nums, w, h, fps, "raea scene lod", plan);
|
||||
let seen = ordered(seen);
|
||||
// a level the plan gives a name no part in these frames goes by holds nothing: said, so the part gets its name
|
||||
unseen.retain(|n| !seen.iter().any(|s| s.planned.is_some() && (s.name == *n || s.name.starts_with(&format!("{n} (lod ")))));
|
||||
unseen.sort();
|
||||
let text = if args.iter().any(|a| a == "--json") {
|
||||
let parts: Vec<_> = seen.iter().map(|s| json!({"part": s.name, "planned": s.planned, "seen": s.level(), "largest": s.finest.map(|f| f.1), "at": s.finest.map(|f| f.0), "frames": s.frames, "closer": s.closer})).collect();
|
||||
serde_json::to_string_pretty(&json!({"frames": [first, last], "parts": parts, "unseen": unseen, "findings": fs})).unwrap_or_default()
|
||||
} else {
|
||||
let levels = "levels, by how much of the frame a part spans: 0 hero 50%+, 1 featured 20%+, 2 dressing 8%+, 3 background 2%+, 4 far";
|
||||
let none = seen.iter().filter(|s| s.planned.is_none()).count();
|
||||
let missing = (!unseen.is_empty()).then(|| format!("planned in brief.ts, but no part of that name is in these frames (name the part as its object's id, or its plan holds nothing): {}", unseen.join(", ")));
|
||||
let sum = format!("frames {first} to {last}: {} parts, {none} with no plan; {}", seen.len(), finding::count(&fs));
|
||||
table(&seen).into_iter().chain(fs.iter().map(Finding::line)).chain(missing).chain([levels.to_string(), sum]).collect::<Vec<_>>().join("\n")
|
||||
};
|
||||
if fs.iter().any(|f| f.level == Level::Error) {
|
||||
println!("{text}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
//! `raea scene faults --clip CLIP.json|FOLDER [--clip ...]`: a character's motion held to what a body does, frame by frame
|
||||
//! (raea-sys-motionfaults): knees that buckle while the foot stands, feet that skate, joints past their range, fingers
|
||||
//! twisted or bent back, jolts, and fingers through what the hand holds. A clip is the skeleton's `joints` (and its
|
||||
//! `surface`, for the palm), `fps`, and `frames` of `{ root, turns }` (with `thing` for what the hand holds).
|
||||
//!
|
||||
//! It learns: `--fine KEY` and `--real KEY` on a clip's finding (each line ends with its key: check and joint role)
|
||||
//! move that key's line for every run after (raea-sys-motionfaults' verdicts, kept beside the scene judge's model).
|
||||
|
||||
use raea_sys_motionfaults::critic;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
// each --clip a clip's JSON, or a folder of them
|
||||
let mut files: Vec<String> = Vec::new();
|
||||
for given in args.windows(2).filter(|w| w[0] == "--clip").map(|w| &w[1]) {
|
||||
match std::fs::read_dir(given) {
|
||||
Ok(dir) => {
|
||||
let mut v: Vec<String> = dir.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "json")).map(|p| p.to_string_lossy().into()).collect();
|
||||
v.sort();
|
||||
files.extend(v);
|
||||
}
|
||||
Err(_) => files.push(given.clone()),
|
||||
}
|
||||
}
|
||||
if let Some(n) = args.windows(2).find(|w| w[0] == "--seed").map(|w| &w[1]) {
|
||||
let n = n.parse::<usize>().map_err(|_| "--seed takes how many faults of each kind to plant in each clip")?;
|
||||
return seed(&files, n);
|
||||
}
|
||||
let as_json = args.iter().any(|a| a == "--json");
|
||||
let (mut text, mut out, mut faults) = (String::new(), Vec::new(), 0);
|
||||
let store = verdicts_path();
|
||||
let mut verdicts = raea_sys_motionfaults::verdicts::Verdicts::load(&store);
|
||||
let (cpath, epath) = critic::paths(&store);
|
||||
let judge = critic::Critic::load(&cpath);
|
||||
let mut examples = Vec::new();
|
||||
let (mut given, mut held) = (0usize, 0usize);
|
||||
for file in &files {
|
||||
let v: Value = serde_json::from_str(&std::fs::read_to_string(file).map_err(|e| format!("{file}: {e}"))?).map_err(|e| format!("{file}: {e}"))?;
|
||||
let clip = raea_sys_motionfaults::clip_of(&v).map_err(|e| format!("{file}: {e}"))?;
|
||||
let mut found = raea_sys_motionfaults::check(&clip);
|
||||
// verdicts given now, on this clip's findings by key, then every verdict's lines applied
|
||||
for (flag, real) in [("--real", true), ("--fine", false)] {
|
||||
for k in args.windows(2).filter(|w| w[0] == flag).map(|w| &w[1]) {
|
||||
let hit: Vec<_> = found.iter().filter(|f| raea_sys_motionfaults::verdicts::key(f) == *k).collect();
|
||||
if hit.is_empty() {
|
||||
return Err(format!("{file}: no finding has the key {k} (each line ends with its key)"));
|
||||
}
|
||||
let (from, upto) = sizes(args, real);
|
||||
for f in hit {
|
||||
if f.value < from || f.value > upto {
|
||||
continue;
|
||||
}
|
||||
verdicts.give(f, real);
|
||||
examples.push(critic::row(f, real, by(args)));
|
||||
given += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let before = found.len();
|
||||
found.retain(|f| stands(f, &verdicts, &judge));
|
||||
held += before - found.len();
|
||||
faults += found.len();
|
||||
let name = std::path::Path::new(file).file_stem().map_or(file.to_string(), |s| s.to_string_lossy().into());
|
||||
text += &format!("{name}: {} frames, {} fault{}\n", clip.poses.len(), found.len(), if found.len() == 1 { "" } else { "s" });
|
||||
for f in &found {
|
||||
text += &format!(" {:<8} {} key: {}\n", f.check, f.says, raea_sys_motionfaults::verdicts::key(f));
|
||||
}
|
||||
out.push(json!({"clip": file, "frames": clip.poses.len(), "faults": found.iter().map(|f| f.to_json()).collect::<Vec<_>>()}));
|
||||
}
|
||||
if out.is_empty() {
|
||||
return Err("--clip takes a clip's JSON (joints, fps, frames of root and turns)".into());
|
||||
}
|
||||
if given > 0 {
|
||||
if let Some(dir) = store.parent() {
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
}
|
||||
std::fs::write(&store, serde_json::to_string_pretty(&verdicts.to_json()).unwrap()).map_err(|e| format!("{}: {e}", store.display()))?;
|
||||
critic::append(&epath, &examples)?;
|
||||
text += &format!("{given} verdict{} kept in {}\n", if given == 1 { "" } else { "s" }, store.display());
|
||||
}
|
||||
if held > 0 {
|
||||
text += &format!("{held} finding{} held back by earlier verdicts (fine at that size)\n", if held == 1 { " is" } else { "s are" });
|
||||
}
|
||||
if as_json {
|
||||
return Ok(serde_json::to_string_pretty(&json!({"clips": out, "faults": faults, "held": held})).unwrap());
|
||||
}
|
||||
if faults > 0 {
|
||||
eprint!("{text}");
|
||||
return Err(format!("{faults} motion fault{} in {} clip{}", if faults == 1 { "" } else { "s" }, out.len(), if out.len() == 1 { "" } else { "s" }));
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
/// Faults of each kind planted in every clip (raea-sys-motionfaults' plant), and how many `check` finds: one that is
|
||||
/// new against the clip's own faults, of its kind, on its joint (any joint for a grip), over its frame.
|
||||
fn seed(files: &[String], n: usize) -> Result<String, String> {
|
||||
use raea_sys_motionfaults::plant::{KINDS, Rng, plant};
|
||||
use std::collections::BTreeMap;
|
||||
let mut tally: BTreeMap<&str, (usize, usize, Vec<f32>, Vec<f32>)> = BTreeMap::new();
|
||||
let mut text = String::new();
|
||||
for (k, file) in files.iter().enumerate() {
|
||||
let v: Value = serde_json::from_str(&std::fs::read_to_string(file).map_err(|e| format!("{file}: {e}"))?).map_err(|e| format!("{file}: {e}"))?;
|
||||
let clip = raea_sys_motionfaults::clip_of(&v).map_err(|e| format!("{file}: {e}"))?;
|
||||
let own = raea_sys_motionfaults::check(&clip);
|
||||
let mut rng = Rng(0x9e37_79b9_7f4a_7c15 ^ (k as u64 + 1) * 0x1000_0001);
|
||||
for kind in KINDS {
|
||||
for _ in 0..n {
|
||||
let Some((moved, p)) = plant(&clip, kind, &mut rng) else { continue };
|
||||
let near = |f: &raea_sys_motionfaults::Fault| f.check == p.check && (p.check == "through" || p.check == "skate" || f.joint == p.joint) && f.from <= p.frame + 2 && p.frame <= f.to + 2;
|
||||
let found = raea_sys_motionfaults::check(&moved);
|
||||
let caught = found.iter().any(|f| near(f) && !own.iter().any(|o| o.check == f.check && o.joint == f.joint && o.from <= f.to && f.from <= o.to));
|
||||
let t = tally.entry(p.check).or_default();
|
||||
t.0 += 1;
|
||||
if caught {
|
||||
t.1 += 1;
|
||||
t.2.push(p.size);
|
||||
} else {
|
||||
t.3.push(p.size);
|
||||
let name = std::path::Path::new(file).file_stem().map_or(String::new(), |s| s.to_string_lossy().into());
|
||||
text += &format!(" missed in {name}: {}\n", p.says);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = format!("planted in {} clips:\n", files.len());
|
||||
for (kind, (planted, caught, got, missed)) in &tally {
|
||||
out += &format!(" {kind:<8} {caught}/{planted} caught{}{}\n", if got.is_empty() { String::new() } else { format!(", smallest caught {:.3}", raea_sys_motionfaults::bounds(got).0) }, if missed.is_empty() { String::new() } else { format!(", smallest missed {:.3}", raea_sys_motionfaults::bounds(missed).0) });
|
||||
}
|
||||
Ok(out + text.as_str())
|
||||
}
|
||||
|
||||
/// Where the motion verdicts are kept: beside the scene judge's model (notice/motion.json), or RAEA_NOTICE_MOTION.
|
||||
/// `raea scene faults EDIT.tsx --composition ID --motion`: the composition's characters (chars.rs) held to the motion
|
||||
/// checks, verdicts given (`--real`/`--fine KEY`) and applied as `--clip`'s are. And what a change shows: each run's
|
||||
/// findings are kept (review/motion.last/<shot>.json), and one the last run reported that's gone now, the character
|
||||
/// and its frames the same, was fixed, so it's kept as a real verdict at its size (raea-sys-motionfaults `fixed`).
|
||||
pub fn composition(tsx: &std::path::Path, shot: &str, dir: &std::path::Path, frames: &[(i64, Vec<raea_core_scene::Item>)], fps: f32, args: &[String]) -> Result<(String, Value, usize), String> {
|
||||
use raea_sys_motionfaults::verdicts::{fixed, key, record};
|
||||
let (found, missing) = crate::chars::run(dir, frames, fps)?;
|
||||
let store = verdicts_path();
|
||||
let mut verdicts = raea_sys_motionfaults::verdicts::Verdicts::load(&store);
|
||||
let (cpath, epath) = critic::paths(&store);
|
||||
let judge = critic::Critic::load(&cpath);
|
||||
let mut examples = Vec::new();
|
||||
let lastp = raea_sys_notice::labels::project_of(tsx).join("review").join("motion.last").join(format!("{shot}.json"));
|
||||
let last: Value = std::fs::read_to_string(&lastp).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(Value::Null);
|
||||
let (mut text, mut rows, mut total, mut given, mut fixes, mut held) = (missing.join("\n"), Vec::new(), 0, 0, 0, 0);
|
||||
let mut keep = serde_json::Map::new();
|
||||
for c in &found {
|
||||
for (flag, real) in [("--real", true), ("--fine", false)] {
|
||||
for k in args.windows(2).filter(|w| w[0] == flag).map(|w| &w[1]) {
|
||||
let (from, upto) = sizes(args, real);
|
||||
for f in c.faults.iter().filter(|f| key(f) == *k && f.value >= from && f.value <= upto) {
|
||||
verdicts.give(f, real);
|
||||
examples.push(critic::row(f, real, by(args)));
|
||||
given += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut lines = String::new();
|
||||
let was = &last["characters"][&c.who];
|
||||
if was["frames"].as_u64() == Some(c.frames as u64) && last["checks"] == raea_sys_motionfaults::CHECKS {
|
||||
for (k, v, n) in fixed(was["faults"].as_array().map(Vec::as_slice).unwrap_or(&[]), &c.faults) {
|
||||
verdicts.give_at(&k, v, true);
|
||||
let (check, joint) = k.split_once(':').unwrap_or((&k, ""));
|
||||
examples.push(critic::row_of(check, joint, v, n, true, "fixed"));
|
||||
fixes += 1;
|
||||
lines += &format!(" fixed {k} at {v:.3}: gone since the last run, kept as real\n");
|
||||
}
|
||||
}
|
||||
keep.insert(c.who.clone(), json!({"frames": c.frames, "faults": c.faults.iter().map(record).collect::<Vec<_>>()}));
|
||||
let mut stand: Vec<&raea_sys_motionfaults::Fault> = Vec::new();
|
||||
for f in &c.faults {
|
||||
if stands(f, &verdicts, &judge) {
|
||||
stand.push(f);
|
||||
}
|
||||
}
|
||||
held += c.faults.len() - stand.len();
|
||||
total += stand.len();
|
||||
for f in &stand {
|
||||
lines += &format!(" {:<8} {} key: {}\n", f.check, f.says, key(f));
|
||||
}
|
||||
text += &format!("{} ({}): {} frames, {} fault{}\n{lines}", c.who, c.skeleton.display(), c.frames, stand.len(), if stand.len() == 1 { "" } else { "s" });
|
||||
rows.push(json!({"character": c.who, "skeleton": c.skeleton, "frames": c.frames, "faults": stand.iter().map(|f| f.to_json()).collect::<Vec<_>>()}));
|
||||
}
|
||||
if given + fixes > 0 {
|
||||
std::fs::create_dir_all(store.parent().unwrap_or(std::path::Path::new("."))).map_err(|e| e.to_string())?;
|
||||
std::fs::write(&store, serde_json::to_string_pretty(&verdicts.to_json()).unwrap_or_default()).map_err(|e| format!("{}: {e}", store.display()))?;
|
||||
}
|
||||
critic::append(&epath, &examples)?;
|
||||
if let Some(dir) = lastp.parent() {
|
||||
std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
|
||||
}
|
||||
std::fs::write(&lastp, serde_json::to_string_pretty(&json!({"checks": raea_sys_motionfaults::CHECKS, "characters": keep})).unwrap_or_default()).map_err(|e| format!("{}: {e}", lastp.display()))?;
|
||||
text += &format!("{held} held back by verdicts and the critic ({} labels), {given} verdicts given, {fixes} fixed since the last run (kept as real) in {}", judge.labels, store.display());
|
||||
Ok((text, json!({"characters": rows, "faults": total, "held": held, "fixed": fixes}), total))
|
||||
}
|
||||
|
||||
/// `--fine-upto N` / `--fine-from N` (`--real-upto`, `--real-from`): that call's verdicts only on findings of the key
|
||||
/// within those sizes, in the finding's own units (degrees past the range for a finger or a limit): a pinky's small
|
||||
/// bends fine, its big one real.
|
||||
/// A fault that stands: marked real, or not marked fine and scored a fault by the judge.
|
||||
fn stands(f: &raea_sys_motionfaults::Fault, verdicts: &raea_sys_motionfaults::verdicts::Verdicts, judge: &critic::Critic) -> bool {
|
||||
verdicts.real_at(f) || (verdicts.stands(f) && judge.score(f) >= critic::SAY)
|
||||
}
|
||||
|
||||
fn sizes(args: &[String], real: bool) -> (f32, f32) {
|
||||
let (a, b) = if real { ("--real-from", "--real-upto") } else { ("--fine-from", "--fine-upto") };
|
||||
let get = |flag: &str, or: f32| args.windows(2).find(|w| w[0] == flag).and_then(|w| w[1].parse().ok()).unwrap_or(or);
|
||||
(get(a, f32::NEG_INFINITY), get(b, f32::INFINITY))
|
||||
}
|
||||
|
||||
/// Who a verdict is by: `--by NAME` (an agent that looked: claude), else a person (marked).
|
||||
fn by(args: &[String]) -> &str {
|
||||
args.windows(2).find(|w| w[0] == "--by").map_or("marked", |w| w[1].as_str())
|
||||
}
|
||||
|
||||
/// The motion critic fitted to every example kept, held out by key, written beside the verdicts.
|
||||
pub fn train() -> Result<String, String> {
|
||||
let (cpath, epath) = critic::paths(&verdicts_path());
|
||||
let ex = critic::examples(&std::fs::read_to_string(&epath).unwrap_or_default());
|
||||
if ex.is_empty() {
|
||||
return Ok(format!("motion critic: no examples yet ({})", epath.display()));
|
||||
}
|
||||
let c = critic::Critic::fit(&ex);
|
||||
let right = ex.iter().filter(|e| (c.score_x(&e.0, &e.1) >= critic::SAY) == (e.2 >= 0.5)).count();
|
||||
let prior = ex.iter().filter(|e| (critic::Critic::prior().score_x(&e.0, &e.1) >= critic::SAY) == (e.2 >= 0.5)).count();
|
||||
let mut keys: Vec<&String> = ex.iter().map(|e| &e.1[2]).collect();
|
||||
keys.sort();
|
||||
keys.dedup();
|
||||
let held = keys.iter().map(|k| {
|
||||
let m = critic::Critic::fit(&ex.iter().filter(|e| &e.1[2] != *k).cloned().collect::<Vec<_>>());
|
||||
ex.iter().filter(|e| &e.1[2] == *k && (m.score_x(&e.0, &e.1) >= critic::SAY) == (e.2 >= 0.5)).count()
|
||||
}).sum::<usize>();
|
||||
std::fs::write(&cpath, serde_json::to_string_pretty(&c.to_json()).unwrap_or_default()).map_err(|e| format!("{}: {e}", cpath.display()))?;
|
||||
let real = ex.iter().filter(|e| e.2 >= 0.5).count();
|
||||
Ok(format!("motion critic: {} examples on {} keys ({real} real, {} fine): the prior agreed with {prior}, the fitted critic with {right}, and with {held} each fitted without its own key (held out); kept in {}", ex.len(), keys.len(), ex.len() - real, cpath.display()))
|
||||
}
|
||||
|
||||
fn verdicts_path() -> std::path::PathBuf {
|
||||
match std::env::var_os("RAEA_NOTICE_MOTION").filter(|v| !v.is_empty()) {
|
||||
Some(p) => p.into(),
|
||||
None => raea_sys_notice::model::path().with_file_name("motion.json"),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//! `raea scene faults EDIT.tsx --seed N`: the judge measured on faults of known size. N props that rest as they should
|
||||
//! are each moved once (sunk into what they stand on, lifted a few millimetres off it, or lifted into the air), the
|
||||
//! lint run again, and the planted fault's finding judged. What it says: how many the lint found, and of those a camera
|
||||
//! sees at two pixels or more, how many the judge calls faults; of those no camera sees, how many it still calls one.
|
||||
//! Nothing is written: a planted fault's truth is its size, which the judge's own features already carry, so it
|
||||
//! measures the judge rather than teaching it.
|
||||
|
||||
use bevy::math::{Mat4, Vec3};
|
||||
use serde_json::Value;
|
||||
|
||||
use raea_core_scene::{Item, label};
|
||||
use raea_sys_motionfaults::plant::Rng;
|
||||
use raea_sys_notice::{Cam, FAULT, Model, Scene, camera};
|
||||
|
||||
/// Props this big across or smaller are moved.
|
||||
const PROP: f32 = 1.2;
|
||||
/// Pixels a planted fault covers at the least to count as plain to see.
|
||||
const PLAIN: f32 = 2.0;
|
||||
|
||||
|
||||
fn moved(its: &[Item], name: &str, by: Vec3) -> Vec<Item> {
|
||||
its.iter().cloned().map(|mut it| {
|
||||
if (it.kind == "mesh" || it.kind == "model") && label(&it, "") == name {
|
||||
it.world = Mat4::from_translation(by) * it.world;
|
||||
}
|
||||
it
|
||||
}).collect()
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn run(now: &[Item], next: &[Item], views: &[Vec<Item>], found: &[Value], w: u32, h: u32, model: &Model, n: usize) -> String {
|
||||
let count = |name: &str| now.iter().filter(|it| (it.kind == "mesh" || it.kind == "model") && label(it, "") == name).count();
|
||||
let props: Vec<&str> = found
|
||||
.iter()
|
||||
.filter(|v| v["check"] == "rests")
|
||||
.filter(|v| {
|
||||
let (lo, hi) = (&v["box"]["min"], &v["box"]["max"]);
|
||||
(0..3).all(|k| hi[k].as_f64().unwrap_or(9.0) - lo[k].as_f64().unwrap_or(0.0) <= PROP as f64)
|
||||
})
|
||||
.filter_map(|v| v["part"].as_str())
|
||||
.filter(|p| count(p) == 1)
|
||||
.collect();
|
||||
let cams: Vec<Cam> = views.iter().filter_map(|f| camera(f)).collect();
|
||||
// only props some camera of the shot sees (the middle of the box's top): a fault planted out of view tells
|
||||
// nothing of how the judge weighs one in it
|
||||
let scene = Scene::of(now);
|
||||
let in_view = |p: &str| {
|
||||
let Some(v) = found.iter().find(|v| v["part"] == p) else { return false };
|
||||
let at = |k: usize, e: &str| v["box"][e][k].as_f64().unwrap_or(0.0) as f32;
|
||||
let top = Vec3::new((at(0, "min") + at(0, "max")) / 2.0, at(1, "max") + 0.01, (at(2, "min") + at(2, "max")) / 2.0);
|
||||
raea_sys_notice::seen(&[raea_sys_notice::sight::Spot { at: top, facing: None, size: 0.0 }], false, &cams, &scene, w as f32, h as f32).shown > 0
|
||||
};
|
||||
let props: Vec<&str> = props.into_iter().filter(|p| in_view(p)).collect();
|
||||
if props.is_empty() {
|
||||
return "no prop the shot sees rests on anything to plant a fault in".into();
|
||||
}
|
||||
let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
|
||||
let (mut lines, mut lint_found, mut plain, mut plain_flagged, mut hidden, mut hidden_flagged, mut small, mut small_flagged) = (Vec::new(), 0, 0, 0, 0, 0, 0, 0);
|
||||
for i in 0..n {
|
||||
let part = props[(rng.next() * props.len() as f32) as usize % props.len()];
|
||||
let r = rng.next();
|
||||
let (kind, d) = if r < 0.4 { ("floats", 0.002 + rng.next() * 0.028) } else if r < 0.8 { ("sunk", 0.005 + rng.next() * 0.035) } else { ("air", 0.08 + rng.next() * 0.22) };
|
||||
let by = Vec3::new(0.0, if kind == "sunk" { -d } else { d }, 0.0);
|
||||
let (a, b) = (moved(now, part, by), moved(next, part, by));
|
||||
let (again, _) = raea_sys_contact::lint(&a, &b);
|
||||
let want = |c: &str| c == kind || (kind == "sunk" && c == "seated") || (kind == "air" && c == "floats") || (kind != "sunk" && c == "mounted");
|
||||
let Some(f) = again.iter().find(|v| v["part"] == part && v["check"].as_str().is_some_and(want)) else {
|
||||
// what it said of the part instead (a prop lifted against a wall reads as mounted on it)
|
||||
let said: Vec<&str> = again.iter().filter(|v| v["part"] == part).filter_map(|v| v["check"].as_str()).collect();
|
||||
lines.push(format!("{i:>3} {kind:<6} {:>6.1} mm {part}: not found as {kind} (the lint said {})", d * 1000.0, said.join(", ")));
|
||||
eprintln!("{}", lines.last().unwrap());
|
||||
continue;
|
||||
};
|
||||
lint_found += 1;
|
||||
let scene = Scene::of(&a);
|
||||
let j = raea_sys_notice::judge_in(std::slice::from_ref(f), &scene, &cams, w, h, model);
|
||||
let Some(j) = j.first() else { continue };
|
||||
let flagged = j.p >= FAULT;
|
||||
if j.seen.shown == 0 {
|
||||
hidden += 1;
|
||||
hidden_flagged += flagged as usize;
|
||||
} else if j.seen.px >= PLAIN {
|
||||
plain += 1;
|
||||
plain_flagged += flagged as usize;
|
||||
} else {
|
||||
small += 1;
|
||||
small_flagged += flagged as usize;
|
||||
}
|
||||
lines.push(format!("{i:>3} {kind:<6} {:>6.1} mm {part}: seen {}/{} frames, {:.1} px -> {:.2}{}", d * 1000.0, j.seen.shown, j.seen.frames, j.seen.px, j.p, if flagged { " FAULT" } else { "" }));
|
||||
// each trial lints the scene again (half a minute on a furnished room): said as it goes
|
||||
eprintln!("{}", lines.last().unwrap());
|
||||
}
|
||||
lines.push(format!(
|
||||
"planted {n} in {} props: the lint found {lint_found}; plain to see (>= {PLAIN} px) {plain}, judged faults {plain_flagged}; seen under {PLAIN} px {small}, judged faults {small_flagged}; no camera sees {hidden}, judged faults {hidden_flagged}",
|
||||
props.len()
|
||||
));
|
||||
lines.join("\n")
|
||||
}
|
||||
+40
-7
@@ -1,7 +1,10 @@
|
||||
//! `raea scene stage EDIT.tsx [--composition ID] [--from N] [--to N] [--json]`: every frame's scene stepped without
|
||||
//! drawing and held to the stage checks a render runs at its end (raea-sys-stage, docs/stage-guards.feature SG10-SG14):
|
||||
//! 3D type that can't be read, parts that snap, a camera that lurches or reverses, frames with nothing composed in
|
||||
//! them. Errors fail it, as they fail a render, so it's the cheap look before one.
|
||||
//! them, a part shown closer than its planned detail (MK21). Errors fail it, as they fail a render, so it's the cheap look before one. It lays out no page, so what the
|
||||
//! page holds waits for a render: its words over the parts (type-over-part), a Label's part as the shot's subject, and
|
||||
//! a frame its words or pictures fill, which reads empty here and is said as a warning, not failed (SG11).
|
||||
//! `--clearance M` holds the camera M metres off every solid part on every frame (0.45 for a carried camera, MK16).
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
@@ -9,8 +12,16 @@ use raea_core_facts::{Level, finding};
|
||||
use raea_runtime_bundle::{bundle_composition, comp_opts, flag};
|
||||
use raea_runtime_export::{all_items, scene_frames_to};
|
||||
|
||||
pub(crate) fn cli(args: &[String]) -> Result<String, String> {
|
||||
let usage = "raea scene stage EDIT.tsx [--composition ID] [--from N] [--to N] [--json]";
|
||||
/// A composition's frames stepped without drawing, for `stage` and `lod`: each frame's parts from --from to --to (every
|
||||
/// frame before is still stepped), their numbers, the frame's size and rate, and the composition's folder.
|
||||
pub(crate) struct Stepped {
|
||||
pub items: Vec<Vec<raea_core_scene::Item>>,
|
||||
pub nums: Vec<i64>,
|
||||
pub size: (u32, u32, f64),
|
||||
pub dir: std::path::PathBuf,
|
||||
}
|
||||
|
||||
pub(crate) fn stepped(args: &[String], usage: &str) -> Result<Stepped, String> {
|
||||
let Some(edit) = args.get(2) else { return Err(usage.into()) };
|
||||
let tsx = dunce::canonicalize(&std::path::PathBuf::from(edit)).map_err(|e| format!("{edit}: {e}"))?;
|
||||
let dir = tsx.parent().unwrap().to_path_buf();
|
||||
@@ -22,13 +33,35 @@ pub(crate) fn cli(args: &[String]) -> Result<String, String> {
|
||||
let _ = std::fs::remove_file(&js);
|
||||
let (frames, w, h, fps) = got?.ok_or("the composition has no 3D")?;
|
||||
let frames: Vec<_> = frames.into_iter().filter(|(f, _)| *f >= from && to.is_none_or(|t| *f <= t)).collect();
|
||||
let (Some(first), Some(last)) = (frames.first().map(|f| f.0), frames.last().map(|f| f.0)) else { return Err(format!("no frames from {from}")) };
|
||||
let nums: Vec<i64> = frames.iter().map(|(f, _)| *f).collect();
|
||||
let fs = raea_sys_stage::check(&all_items(&frames), &nums, w, h, fps, "raea scene stage");
|
||||
if frames.is_empty() {
|
||||
return Err(format!("no frames from {from}"));
|
||||
}
|
||||
Ok(Stepped { nums: frames.iter().map(|(f, _)| *f).collect(), items: all_items(&frames), size: (w, h, fps), dir })
|
||||
}
|
||||
|
||||
pub(crate) fn cli(args: &[String]) -> Result<String, String> {
|
||||
let Stepped { items, nums, size: (w, h, fps), dir } = stepped(args, "raea scene stage EDIT.tsx [--composition ID] [--from N] [--to N] [--clearance M] [--json]")?;
|
||||
let (first, last) = (nums[0], nums[nums.len() - 1]);
|
||||
let mut fs = raea_sys_stage::check(&items, &nums, w, h, fps, "raea scene stage");
|
||||
// and each part held to its planned detail (its own `lod`, or its name's on the plan above it: MK21), as a render does
|
||||
fs.extend(raea_runtime_lod_plan::lods(&items, &nums, w, h, fps, "raea scene stage", raea_runtime_lod_plan::plan::lods(&dir)).1.into_iter().filter(|f| f.check == "lod-closer"));
|
||||
fs = raea_core_facts::finding::ranked(fs);
|
||||
// the camera held off every solid part, when asked: the number after the flag, else a carried camera's 0.45 m
|
||||
if let Some(v) = flag(args, "--clearance") {
|
||||
let min = v.parse::<f32>().ok().filter(|m| *m >= 0.0).ok_or_else(|| format!("--clearance takes metres (0.45 for a carried camera), got {v:?}"))?;
|
||||
let mut c = crate::clearance::clearance(&items, &nums, w, h, fps, min, "raea scene stage");
|
||||
c.append(&mut fs);
|
||||
fs = c;
|
||||
}
|
||||
for f in fs.iter_mut().filter(|f| f.check == "frame-empty" && f.level == Level::Error) {
|
||||
f.level = Level::Warn;
|
||||
f.says.push_str(" (no page is laid out here: if its words or pictures fill these frames, a render passes them)");
|
||||
}
|
||||
let text = if args.iter().any(|a| a == "--json") {
|
||||
serde_json::to_string_pretty(&json!({"frames": [first, last], "findings": fs})).unwrap_or_default()
|
||||
} else {
|
||||
fs.iter().map(raea_core_facts::Finding::line).chain([format!("frames {first} to {last}: {}", finding::count(&fs))]).collect::<Vec<_>>().join("\n")
|
||||
let note = "the page's checks (its words over parts, a Label's subject) run in raea render";
|
||||
fs.iter().map(raea_core_facts::Finding::line).chain([format!("frames {first} to {last}: {} ({note})", finding::count(&fs))]).collect::<Vec<_>>().join("\n")
|
||||
};
|
||||
if fs.iter().any(|f| f.level == Level::Error) {
|
||||
println!("{text}");
|
||||
|
||||
@@ -4,7 +4,7 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "raea solid info and raea solid view: a solid file run, its parts measured (raea-core-solidinfo), and its review sheets in colour and clay"
|
||||
description = "raea make solid info and raea make solid view: a solid file run, its parts measured (raea-core-solidinfo), and its review sheets in colour and clay"
|
||||
|
||||
[dependencies]
|
||||
dunce = "1"
|
||||
@@ -14,9 +14,8 @@ 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-app-judge = { path = "../judge" }
|
||||
raea-app-ask = { path = "../ask" }
|
||||
# `raea solid export`: the solid built, written as .glb and read back (core/shape), named and coloured (core/meshcheck)
|
||||
# a scene, kit or shot held to its plan (docs/goal.feature)
|
||||
raea-app-make = { path = "../make" }
|
||||
# `raea make solid export`: the solid built, written as .glb and read back (core/shape), named and coloured (core/meshcheck)
|
||||
raea-core-shape = { path = "../../core/shape" }
|
||||
raea-core-meshcheck = { path = "../../core/meshcheck" }
|
||||
@@ -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!(
|
||||
|
||||
+10
-11
@@ -1,11 +1,11 @@
|
||||
//! `raea solid info FILE.ts [--json] [--set k=v,...] [--expect E.json] [--walk]`: the file's solid measured
|
||||
//! `raea make solid info FILE.ts [--json] [--set k=v,...] [--expect E.json] [--walk]`: the file's solid measured
|
||||
//! (raea-core-solidinfo). FILE.ts exports `default`: a Solid, an object of named Solids (the parts), or a function
|
||||
//! of the params returning either; and optionally `params`, each a number, a boolean, or `[low, high, default]`. The
|
||||
//! file is run by `raea run` (a wrapper that prints each part's shape expression), then measured natively. --set
|
||||
//! builds it at other params and says what moved from the defaults; --walk moves each ranged param alone to each end
|
||||
//! and says which break it (more pieces, empty) and which reach no geometry. FILE.expect.json beside it is read when
|
||||
//! --expect isn't given. Errors exit 1, as scene lint. A part's `role` comes from the file's `roles` export ({body:
|
||||
//! "contain"}), its `at` from the line that names it. `raea solid view` takes its pictures (view.rs); `raea solid export`
|
||||
//! "contain"}), its `at` from the line that names it. `raea make solid view` takes its pictures (view.rs); `raea make solid export`
|
||||
//! writes it as a .glb for a Blender step (export.rs). Its `needs` export ({textured: true}) asks for what solids can't
|
||||
//! give yet: real UVs and baked maps name bake.py (docs/blender.feature BL14).
|
||||
|
||||
@@ -18,7 +18,7 @@ use serde_json::{Map, Value, json};
|
||||
mod export;
|
||||
mod view;
|
||||
|
||||
pub const USAGE: &str = "raea solid info FILE.ts [--json] [--set k=v,...] [--expect E.json] [--walk] (volume, box, pieces, genus per part; joints; predictions and mutants)\n raea solid view FILE.ts -o DIR [--set k=v,...] [--json] (the solid's parts in colour and clay from fixed cameras)\n raea solid export FILE.ts -o OUT.glb [--set k=v,...] [--part NAME] [--colour #RRGGBB] (the solid as one .glb for a Blender step, read back and checked)";
|
||||
pub const USAGE: &str = "raea make solid info FILE.ts [--json] [--set k=v,...] [--expect E.json] [--walk] (volume, box, pieces, genus per part; joints; predictions and mutants)\n raea make solid view FILE.ts -o DIR [--set k=v,...] [--json] (the solid's parts in colour and clay from fixed cameras)\n raea make solid export FILE.ts -o OUT.glb [--set k=v,...] [--part NAME] [--colour #RRGGBB] (the solid as one .glb for a Blender step, read back and checked)";
|
||||
|
||||
thread_local! {
|
||||
/// the last run file's `roles` and `needs` exports
|
||||
@@ -68,7 +68,7 @@ print("RAEA_SOLID_INFO " + JSON.stringify({{ params: p, spec, parts: exprs, role
|
||||
fn textured(out: &mut Value, file: &Path) {
|
||||
let stem = file.file_stem().and_then(|s| s.to_str()).unwrap_or("solid");
|
||||
let f = raea_core_meshcheck::blender::fix("bake.py", &format!("media/{stem}.glb media/{stem}-baked.glb --into-colour"));
|
||||
let run = format!("raea solid export {} -o media/{stem}.glb --colour #RRGGBB && {}", file.display(), f["run"].as_str().unwrap_or(""));
|
||||
let run = format!("raea make solid export {} -o media/{stem}.glb --colour #RRGGBB && {}", file.display(), f["run"].as_str().unwrap_or(""));
|
||||
let says = format!("its file asks for textures (needs.textured), and a solid's UVs are box projections: export it and bake real UVs and maps; fix: {run}");
|
||||
if let Some(a) = out["found"].as_array_mut() {
|
||||
a.push(json!({"check": "textures", "level": "warning", "says": says, "fix": {"blender": "bake.py", "run": run}}));
|
||||
@@ -91,13 +91,12 @@ fn parse_set(s: &str) -> Result<Map<String, Value>, String> {
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
/// `raea solid ...`, `raea judge ...` and `raea ask ...` (docs/ask.feature AK3, which prints as it goes and exits with
|
||||
/// its own code), the verbs that build and judge a piece (engine/cli hands them over), or None for another verb.
|
||||
/// `raea make solid ...` and `raea make ...` (docs/goal.feature), the verbs that build a piece (engine/cli hands them
|
||||
/// over), or None for another verb.
|
||||
pub fn verb(args: &[String]) -> Option<Result<String, String>> {
|
||||
match args.first().map(String::as_str) {
|
||||
Some("solid") => Some(cli(args)),
|
||||
Some("judge") => Some(raea_app_judge::cli(args)),
|
||||
Some("ask") => std::process::exit(raea_app_ask::cli(&args[1..])),
|
||||
Some("make") => Some(raea_app_make::cli(args)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -133,7 +132,7 @@ pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
return export::export(&file, &parts, &out, args);
|
||||
}
|
||||
if verb == "view" {
|
||||
let dir = crate::view::out_dir(args).ok_or("raea solid view FILE.ts -o DIR: give the folder for the sheets")?;
|
||||
let dir = crate::view::out_dir(args).ok_or("raea make solid view FILE.ts -o DIR: give the folder for the sheets")?;
|
||||
return crate::view::view(&file, &set, &out, &dir, json_out);
|
||||
}
|
||||
out["params"] = params;
|
||||
@@ -178,7 +177,7 @@ pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
}
|
||||
// what it found as raea's one Finding (docs/direction.feature DR3), about the part, or the solid's file
|
||||
let name = file.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
|
||||
let found = finding::ranked(out["found"].as_array().into_iter().flatten().filter_map(|v| Finding::of_value(v, "raea solid info")).map(|f| if f.about.is_empty() { f.about(&name, None) } else { f }).collect());
|
||||
let found = finding::ranked(out["found"].as_array().into_iter().flatten().filter_map(|v| Finding::of_value(v, "raea make solid info")).map(|f| if f.about.is_empty() { f.about(&name, None) } else { f }).collect());
|
||||
let errors = found.iter().any(|f| f.level == Level::Error);
|
||||
if let Some(o) = out.as_object_mut() {
|
||||
for k in ["found", "errors", "warnings"] {
|
||||
@@ -199,7 +198,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,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
|
||||
|
||||
@@ -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" }
|
||||
@@ -55,7 +55,7 @@ pub fn with_preface(text: &str, dir: &Path) -> String {
|
||||
return text.to_string();
|
||||
}
|
||||
let p = format!(
|
||||
"> **On Grok Bot.** raea runs on the person's Mac, not on your computer. Run every `raea` command there, and read\n> every file this skill links (3d.md, reference/cli.md and the rest) from its copy there, in {}, both\n> with Run a command on your local computer (the person turns on Settings → Computer → Execution on this computer).\n> No raea MCP server or hook is set up for you: after saving a composition run `raea check EDIT.tsx --quick` yourself,\n> and `raea show FILE` puts media in front of the person.\n",
|
||||
"> **On Grok Bot.** raea runs on the person's Mac, not on your computer. Run every `raea` command there, and read\n> every file this skill links (3d.md, reference/cli.md and the rest) from its copy there, in {}, both\n> with Run a command on your local computer (the person turns on Settings → Computer → Execution on this computer).\n> No raea MCP server or hook is set up for you: a render checks its own output at its end (`raea check OUT.mp4`\n> checks one again), and `raea show FILE` puts media in front of the person.\n",
|
||||
dir.join("raea").display()
|
||||
);
|
||||
let Some(rest) = text.strip_prefix("---\n") else { return format!("{p}\n{text}") };
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! The hooks `raea skills install` adds an agent (docs/agents.feature A5d, A5e; docs/skills.feature SK10), the same two
|
||||
//! for every harness, each written where and how that harness reads hooks: before a shell command, `raea hook AGENT`
|
||||
//! steers media opened in the Mac's viewer to `raea show`; after a file is saved, it runs the quick check on a
|
||||
//! composition. Claude Code's run after every tool and as a turn ends too, to hand the session what the person sent from
|
||||
//! the raea app (apps/check/src/inbox.rs). An event that already has a `raea hook` entry keeps it, its matcher widened
|
||||
//! steers media opened in the Mac's viewer to `raea show`; after a file is saved, it checks nothing (a render checks its
|
||||
//! own output, docs/check.feature CK1) and only hands the session what the person sent from the raea app
|
||||
//! (apps/check/src/inbox.rs). Claude Code's run after every tool, and Claude Code's and Codex's as a turn ends too, where
|
||||
//! `raea check --at done` holds the brief's goals. An event that already has a `raea hook` entry keeps it, its matcher widened
|
||||
//! to this raea's when an older raea wrote a narrower one.
|
||||
use crate::agent_mcp::user_home;
|
||||
use serde_json::{Value, json};
|
||||
@@ -21,8 +22,10 @@ struct Hook {
|
||||
fn hooks(agent: &str) -> R<Vec<Hook>> {
|
||||
let h = |event, matcher, secs| Hook { event, matcher, secs };
|
||||
Ok(match agent {
|
||||
"claude" => vec![h("PreToolUse", "Bash", 30), h("PostToolUse", "*", 60), h("Stop", "", 10)],
|
||||
"codex" => vec![h("PreToolUse", "^(Bash|shell|shell_command|exec_command)$", 30), h("PostToolUse", "^(apply_patch|Edit|Write)$", 60)],
|
||||
// SessionStart and UserPromptSubmit: notes sent from raea while the session was closed or idle reach it when it
|
||||
// starts again or is next written to (Shane 11-28: "notes reach closed sessions")
|
||||
"claude" => vec![h("PreToolUse", "Bash", 30), h("PostToolUse", "*", 60), h("Stop", "", 30), h("SessionStart", "", 10), h("UserPromptSubmit", "", 10)],
|
||||
"codex" => vec![h("PreToolUse", "^(Bash|shell|shell_command|exec_command)$", 30), h("PostToolUse", "^(apply_patch|Edit|Write)$", 60), h("Stop", "", 30), h("SessionStart", "", 10), h("UserPromptSubmit", "", 10)],
|
||||
"gemini" => vec![h("BeforeTool", "run_shell_command", 30), h("AfterTool", "write_file|replace", 60)],
|
||||
"kimi" => vec![h("PreToolUse", "Bash|Shell", 30), h("PostToolUse", "Write|Edit|WriteFile|StrReplaceFile", 60)],
|
||||
a => return Err(format!("no agent {a:?}: claude, codex, kimi or gemini")),
|
||||
@@ -124,7 +127,8 @@ mod tests {
|
||||
let c = d.join("claude/settings.json");
|
||||
std::fs::create_dir_all(c.parent().unwrap()).unwrap();
|
||||
std::fs::write(&c, r#"{"model":"x","hooks":{"PostToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"other"}]},{"matcher":"Write","hooks":[{"type":"command","command":"raea hook claude"}]}]}}"#).unwrap();
|
||||
let [pre, post, stop] = <[Hook; 3]>::try_from(hooks("claude").unwrap()).ok().unwrap();
|
||||
let [pre, post, stop, start, prompt] = <[Hook; 5]>::try_from(hooks("claude").unwrap()).ok().unwrap();
|
||||
assert!(add_json(&c, "claude", &start).unwrap() && add_json(&c, "claude", &prompt).unwrap() && !add_json(&c, "claude", &start).unwrap());
|
||||
assert!(add_json(&c, "claude", &pre).unwrap() && !add_json(&c, "claude", &pre).unwrap());
|
||||
assert!(add_json(&c, "claude", &post).unwrap() && !add_json(&c, "claude", &post).unwrap(), "an older raea's after-save hook is widened to every tool, once");
|
||||
assert!(add_json(&c, "claude", &stop).unwrap() && !add_json(&c, "claude", &stop).unwrap());
|
||||
@@ -133,6 +137,9 @@ mod tests {
|
||||
assert_eq!((v["hooks"]["PostToolUse"][0]["matcher"].as_str(), v["hooks"]["PostToolUse"][1]["matcher"].as_str()), (Some("Bash"), Some("*")));
|
||||
assert_eq!(v["hooks"]["PreToolUse"][0]["hooks"][0]["command"], "raea hook claude");
|
||||
assert_eq!(v["hooks"]["Stop"][0]["hooks"][0]["command"], "raea hook claude");
|
||||
assert_eq!(v["hooks"]["SessionStart"][0]["hooks"][0]["command"], "raea hook claude");
|
||||
assert_eq!(v["hooks"]["UserPromptSubmit"][0]["hooks"][0]["command"], "raea hook claude");
|
||||
assert_eq!(hooks("codex").unwrap().iter().map(|h| h.event).collect::<Vec<_>>(), ["PreToolUse", "PostToolUse", "Stop", "SessionStart", "UserPromptSubmit"]);
|
||||
let g = d.join("gemini/settings.json");
|
||||
let [before, _] = <[Hook; 2]>::try_from(hooks("gemini").unwrap()).ok().unwrap();
|
||||
assert!(add_json(&g, "gemini", &before).unwrap());
|
||||
|
||||
@@ -1,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;
|
||||
|
||||
@@ -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(" ");
|
||||
|
||||
@@ -24,7 +24,7 @@ pub(crate) fn synonyms(word: &str) -> Vec<&str> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `raea sounds [WORDS...]`: the instruments whose names hold every word (all of them with no words, by pack).
|
||||
/// `raea make sounds [WORDS...]`: the instruments whose names hold every word (all of them with no words, by pack).
|
||||
pub fn sounds(args: &[String]) -> R<String> {
|
||||
if args.get(1).map(String::as_str) == Some("get") {
|
||||
return sounds_get(args);
|
||||
@@ -70,7 +70,7 @@ pub fn sounds(args: &[String]) -> R<String> {
|
||||
if out.is_empty() {
|
||||
return Ok(format!("no instrument in the sample libraries matches {:?}: try one word (piano, snare, strings, marimba)", words.join(" ")));
|
||||
}
|
||||
Ok(format!("{}\n\nraea sounds get PACK/INSTRUMENT [--notes C2,C4] copies one into media/sounds/ and prints the Sampler for it", out.join("\n\n")))
|
||||
Ok(format!("{}\n\nraea make sounds get PACK/INSTRUMENT [--notes C2,C4] copies one into media/sounds/ and prints the Sampler for it", out.join("\n\n")))
|
||||
}
|
||||
|
||||
/// Percent-encode a URL path (spaces, commas and `#` in VCSL's names), keeping its slashes.
|
||||
@@ -106,16 +106,16 @@ pub(crate) fn static_path(p: &Path) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// `raea sounds get PACK/INSTRUMENT [--notes ..|--all] [-o DIR]`: an instrument's samples into the edit's
|
||||
/// `raea make sounds get PACK/INSTRUMENT [--notes ..|--all] [-o DIR]`: an instrument's samples into the edit's
|
||||
/// media (default media/sounds/PACK-INSTRUMENT/), its licence beside them, and the TSX that plays them.
|
||||
pub(crate) fn sounds_get(args: &[String]) -> R<String> {
|
||||
const USAGE: &str = "raea sounds get PACK/INSTRUMENT [--notes C2,C4 | --all] [--dir EDIT_DIR] [-o OUT_DIR] (raea sounds WORDS finds one)";
|
||||
const USAGE: &str = "raea make sounds get PACK/INSTRUMENT [--notes C2,C4 | --all] [--dir EDIT_DIR] [-o OUT_DIR] (raea make sounds WORDS finds one)";
|
||||
let id = *positional(&args[2..], &["--notes", "--dir", "-o"]).first().ok_or(USAGE)?;
|
||||
let (pid, iid) = id.split_once('/').ok_or(USAGE)?;
|
||||
let c = catalog()?;
|
||||
let pack = c["packs"].as_array().into_iter().flatten().find(|p| p["id"] == pid).ok_or(format!("no sample library `{pid}`: raea sounds lists them"))?;
|
||||
let pack = c["packs"].as_array().into_iter().flatten().find(|p| p["id"] == pid).ok_or(format!("no sample library `{pid}`: raea make sounds lists them"))?;
|
||||
let inst = pack["instruments"].as_array().into_iter().flatten().find(|i| i["id"] == iid)
|
||||
.ok_or(format!("{pid} has no instrument `{iid}`: raea sounds {iid} searches for it"))?;
|
||||
.ok_or(format!("{pid} has no instrument `{iid}`: raea make sounds {iid} searches for it"))?;
|
||||
let files = files_of(pack, inst);
|
||||
let pitched_files: Vec<_> = files.iter().filter(|f| f.0.is_some()).cloned().collect();
|
||||
let pitched = pitched_files.iter().map(|f| f.0).collect::<std::collections::BTreeSet<_>>().len() >= 3;
|
||||
@@ -185,7 +185,21 @@ pub(crate) fn sounds_get(args: &[String]) -> R<String> {
|
||||
}
|
||||
}
|
||||
let base = PathBuf::from(flag(args, "--dir").unwrap_or_else(|| ".".into()));
|
||||
let out = flag(args, "-o").map(PathBuf::from).unwrap_or_else(|| base.join("media/sounds").join(format!("{pid}-{iid}")));
|
||||
let mut out = flag(args, "-o").map(PathBuf::from).unwrap_or_else(|| base.join("media/sounds").join(format!("{pid}-{iid}")));
|
||||
let licence = format!(
|
||||
"{}\n{}\nlicence: {}\nsource: {}\n{}\n",
|
||||
pack["name"].as_str().unwrap_or_default(),
|
||||
inst["name"].as_str().unwrap_or_default(),
|
||||
pack["licence"].as_str().unwrap_or_default(),
|
||||
pack["source"].as_str().unwrap_or_default(),
|
||||
pack["attribution"].as_str().unwrap_or_default()
|
||||
);
|
||||
// a folder that already holds another instrument keeps it: two instruments' notes share names (C4.mp3), and the
|
||||
// second one's replaced the first's and its licence (#217). This one goes in a folder of its own inside it
|
||||
if std::fs::read_to_string(out.join("LICENCE.txt")).is_ok_and(|held| held != licence) {
|
||||
out = out.join(format!("{pid}-{iid}"));
|
||||
said.push(format!("the folder given already holds another instrument, so this one is in {}", out.display()));
|
||||
}
|
||||
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
let cache = raea_io_home::user_home().unwrap_or_default().join(".cache/raea-sounds").join(pid).join(iid);
|
||||
let template = pack["url"].as_str().unwrap_or_default();
|
||||
@@ -201,14 +215,6 @@ pub(crate) fn sounds_get(args: &[String]) -> R<String> {
|
||||
std::fs::copy(&cached, &to).map_err(|e| format!("{}: {e}", to.display()))?;
|
||||
bytes += std::fs::metadata(&to).map(|m| m.len()).unwrap_or(0);
|
||||
}
|
||||
let licence = format!(
|
||||
"{}\n{}\nlicence: {}\nsource: {}\n{}\n",
|
||||
pack["name"].as_str().unwrap_or_default(),
|
||||
inst["name"].as_str().unwrap_or_default(),
|
||||
pack["licence"].as_str().unwrap_or_default(),
|
||||
pack["source"].as_str().unwrap_or_default(),
|
||||
pack["attribution"].as_str().unwrap_or_default()
|
||||
);
|
||||
std::fs::write(out.join("LICENCE.txt"), &licence).map_err(|e| e.to_string())?;
|
||||
let var = iid.replace(|c: char| !c.is_ascii_alphanumeric(), "_");
|
||||
let tsx = if pitched {
|
||||
|
||||
@@ -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") => {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "raea-app-voice"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "raea voice: speech to speech on this computer (Silero's turns, Parakeet's words, Pocket TTS's voice) as lines of JSON, for an agent that talks"
|
||||
|
||||
[[bin]]
|
||||
name = "raea-voice"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
# Pocket TTS and its word clock
|
||||
raea-io-trace = { path = "../../io/trace" }
|
||||
raea-sys-speech = { path = "../../systems/speech" }
|
||||
# ort sessions the way raea builds them, and the model cache
|
||||
raea-sys-ml = { path = "../../systems/ml" }
|
||||
ort = { version = "=2.0.0-rc.13", features = ["half"] }
|
||||
# the microphone and the speakers: the cpal the mixer uses
|
||||
cpal = "0.15"
|
||||
anyhow = "1"
|
||||
serde_json = "1"
|
||||
|
||||
[target.'cfg(all(windows, target_arch = "x86_64"))'.dependencies]
|
||||
ort = { version = "=2.0.0-rc.13", features = ["load-dynamic"] }
|
||||
@@ -0,0 +1,118 @@
|
||||
//! Parakeet TDT 0.6b v3 (NVIDIA, CC-BY-4.0) on ONNX: what was said. The export is istupakov/parakeet-tdt-0.6b-v3-onnx
|
||||
//! (int8 encoder and decoder, NeMo's 128-bin front end as a model of its own), decoded as onnx-asr's
|
||||
//! NemoConformerTdt decodes it: greedy, each step's token and how many encoder frames to skip.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{anyhow, Context};
|
||||
use ort::session::Session;
|
||||
use ort::value::Tensor;
|
||||
use raea_sys_ml::models::Spec;
|
||||
|
||||
const REPO: &str = "istupakov/parakeet-tdt-0.6b-v3-onnx";
|
||||
pub const SPEC: Spec = Spec {
|
||||
name: "parakeet-tdt-0.6b-v3",
|
||||
files: &[
|
||||
(REPO, "nemo128.onnx", "nemo128.onnx"),
|
||||
(REPO, "encoder-model.int8.onnx", "encoder-model.int8.onnx"),
|
||||
(REPO, "decoder_joint-model.int8.onnx", "decoder_joint-model.int8.onnx"),
|
||||
(REPO, "vocab.txt", "vocab.txt"),
|
||||
],
|
||||
};
|
||||
|
||||
/// The prediction network's state: two layers of 640.
|
||||
const STATE: usize = 2 * 640;
|
||||
/// Tokens one encoder frame may give before the decoder moves on (onnx-asr's max_tokens_per_step).
|
||||
const PER_STEP: usize = 10;
|
||||
|
||||
pub struct Asr {
|
||||
front: Session,
|
||||
encoder: Session,
|
||||
decoder: Session,
|
||||
vocab: Vec<String>,
|
||||
}
|
||||
|
||||
fn err(e: ort::Error) -> anyhow::Error {
|
||||
anyhow!("parakeet: {e}")
|
||||
}
|
||||
|
||||
impl Asr {
|
||||
pub fn load(dir: &Path) -> anyhow::Result<Asr> {
|
||||
let vocab = std::fs::read_to_string(dir.join("vocab.txt")).context("parakeet's vocab.txt")?;
|
||||
// "token id" a line; the token itself can hold a space's mark but never a plain space
|
||||
let vocab: Vec<String> = vocab.lines().filter_map(|l| l.rsplit_once(' ').map(|(t, _)| t.to_string())).collect();
|
||||
anyhow::ensure!(vocab.last().map(String::as_str) == Some("<blk>"), "parakeet's vocab.txt doesn't end in its blank");
|
||||
Ok(Asr {
|
||||
front: raea_sys_ml::session(&dir.join("nemo128.onnx"))?,
|
||||
encoder: raea_sys_ml::session(&dir.join("encoder-model.int8.onnx"))?,
|
||||
decoder: raea_sys_ml::session(&dir.join("decoder_joint-model.int8.onnx"))?,
|
||||
vocab,
|
||||
})
|
||||
}
|
||||
|
||||
/// The words in `x` (16 kHz mono), as one line.
|
||||
pub fn hear(&mut self, x: &[f32]) -> anyhow::Result<String> {
|
||||
if x.len() < 1600 {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let wave = Tensor::from_array(([1usize, x.len()], x.to_vec())).map_err(err)?;
|
||||
let len = Tensor::from_array(([1usize], vec![x.len() as i64])).map_err(err)?;
|
||||
let (shape, feats, flen) = {
|
||||
let o = self.front.run(ort::inputs!["waveforms" => wave, "waveforms_lens" => len]).map_err(err)?;
|
||||
let (shape, f) = o["features"].try_extract_tensor::<f32>().map_err(err)?;
|
||||
let (_, l) = o["features_lens"].try_extract_tensor::<i64>().map_err(err)?;
|
||||
(shape.iter().map(|d| *d as usize).collect::<Vec<_>>(), f.to_vec(), l[0])
|
||||
};
|
||||
let feats = Tensor::from_array((shape, feats)).map_err(err)?;
|
||||
let flen = Tensor::from_array(([1usize], vec![flen])).map_err(err)?;
|
||||
let (dim, frames, enc) = {
|
||||
let o = self.encoder.run(ort::inputs!["audio_signal" => feats, "length" => flen]).map_err(err)?;
|
||||
let (shape, e) = o["outputs"].try_extract_tensor::<f32>().map_err(err)?;
|
||||
let (_, l) = o["encoded_lengths"].try_extract_tensor::<i64>().map_err(err)?;
|
||||
(shape[1] as usize, (shape[2] as usize, l[0] as usize), e.to_vec())
|
||||
};
|
||||
let (width, frames) = frames;
|
||||
let blank = self.vocab.len() - 1;
|
||||
let (mut s1, mut s2) = (vec![0f32; STATE], vec![0f32; STATE]);
|
||||
let mut tokens: Vec<usize> = Vec::new();
|
||||
let (mut t, mut emitted) = (0usize, 0usize);
|
||||
while t < frames.min(width) {
|
||||
let frame: Vec<f32> = (0..dim).map(|d| enc[d * width + t]).collect();
|
||||
let last = tokens.last().copied().unwrap_or(blank) as i32;
|
||||
let o = self
|
||||
.decoder
|
||||
.run(ort::inputs![
|
||||
"encoder_outputs" => Tensor::from_array(([1usize, dim, 1], frame)).map_err(err)?,
|
||||
"targets" => Tensor::from_array(([1usize, 1], vec![last])).map_err(err)?,
|
||||
"target_length" => Tensor::from_array(([1usize], vec![1i32])).map_err(err)?,
|
||||
"input_states_1" => Tensor::from_array(([2usize, 1, 640], s1.clone())).map_err(err)?,
|
||||
"input_states_2" => Tensor::from_array(([2usize, 1, 640], s2.clone())).map_err(err)?,
|
||||
])
|
||||
.map_err(err)?;
|
||||
let (_, logits) = o["outputs"].try_extract_tensor::<f32>().map_err(err)?;
|
||||
let best = |v: &[f32]| v.iter().enumerate().fold((0usize, f32::NEG_INFINITY), |b, (i, x)| if *x > b.1 { (i, *x) } else { b }).0;
|
||||
let token = best(&logits[..self.vocab.len()]);
|
||||
let skip = best(&logits[self.vocab.len()..]);
|
||||
if token != blank {
|
||||
s1.copy_from_slice(&o["output_states_1"].try_extract_tensor::<f32>().map_err(err)?.1[..STATE]);
|
||||
s2.copy_from_slice(&o["output_states_2"].try_extract_tensor::<f32>().map_err(err)?.1[..STATE]);
|
||||
tokens.push(token);
|
||||
emitted += 1;
|
||||
}
|
||||
if skip > 0 {
|
||||
t += skip;
|
||||
emitted = 0;
|
||||
} else if token == blank || emitted == PER_STEP {
|
||||
t += 1;
|
||||
emitted = 0;
|
||||
}
|
||||
}
|
||||
Ok(self.text(&tokens))
|
||||
}
|
||||
|
||||
/// Tokens as a line: a token's leading mark is the space before a word.
|
||||
fn text(&self, tokens: &[usize]) -> String {
|
||||
let joined: String = tokens.iter().map(|t| self.vocab[*t].as_str()).filter(|t| !t.starts_with("<|")).collect();
|
||||
joined.replace('\u{2581}', " ").split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
//! The microphone and the speakers (cpal), or files in their place (`--from`, `--to`: a session with no devices, for
|
||||
//! checks and for measuring).
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::mpsc::Sender;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{anyhow, bail, Context};
|
||||
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
|
||||
|
||||
/// A stream's rate changed as it comes, by linear interpolation: speech in, and Pocket's 24 kHz out.
|
||||
pub struct Resample {
|
||||
/// input samples per output sample
|
||||
step: f64,
|
||||
/// where the next output sample falls, in input samples from the start of the next piece (-1 is `last`)
|
||||
pos: f64,
|
||||
last: f32,
|
||||
}
|
||||
|
||||
impl Resample {
|
||||
pub fn new(from: u32, to: u32) -> Resample {
|
||||
Resample { step: from as f64 / to as f64, pos: 0.0, last: 0.0 }
|
||||
}
|
||||
|
||||
pub fn push(&mut self, x: &[f32], out: &mut Vec<f32>) {
|
||||
let Some(&end) = x.last() else { return };
|
||||
while self.pos + 1.0 < x.len() as f64 {
|
||||
let i = self.pos.floor();
|
||||
let a = if i < 0.0 { self.last } else { x[i as usize] };
|
||||
let b = x[(i + 1.0) as usize];
|
||||
out.push(a + (b - a) * (self.pos - i) as f32);
|
||||
self.pos += self.step;
|
||||
}
|
||||
self.pos -= x.len() as f64;
|
||||
self.last = end;
|
||||
}
|
||||
}
|
||||
|
||||
/// Interleaved channels as one: each frame's mean.
|
||||
fn mono(x: &[f32], ch: usize) -> Vec<f32> {
|
||||
let mut out = Vec::with_capacity(x.len() / ch + 1);
|
||||
for frame in x.chunks(ch) {
|
||||
let mut sum = 0.0;
|
||||
for s in frame {
|
||||
sum += s;
|
||||
}
|
||||
out.push(sum / frame.len() as f32);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A WAV's sound as mono samples and its rate: 16-bit PCM or 32-bit float, any channels.
|
||||
pub fn read_wav(path: &Path) -> anyhow::Result<(Vec<f32>, u32)> {
|
||||
let b = std::fs::read(path).with_context(|| format!("{}", path.display()))?;
|
||||
anyhow::ensure!(b.len() > 12 && &b[..4] == b"RIFF" && &b[8..12] == b"WAVE", "{}: not a WAV file", path.display());
|
||||
let u16_at = |i: usize| u16::from_le_bytes([b[i], b[i + 1]]);
|
||||
let u32_at = |i: usize| u32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]);
|
||||
let (mut at, mut fmt) = (12usize, None);
|
||||
while at + 8 <= b.len() {
|
||||
let (id, len) = (&b[at..at + 4], u32_at(at + 4) as usize);
|
||||
let body = at + 8;
|
||||
if id == b"fmt " && body + 16 <= b.len() {
|
||||
fmt = Some((u16_at(body), u16_at(body + 2) as usize, u32_at(body + 4), u16_at(body + 14)));
|
||||
} else if id == b"data" {
|
||||
let (kind, ch, rate, bits) = fmt.ok_or_else(|| anyhow!("{}: its sound comes before its format", path.display()))?;
|
||||
let data = &b[body..(body + len).min(b.len())];
|
||||
let one: Vec<f32> = match (kind, bits) {
|
||||
(1, 16) => data.chunks_exact(2).map(|s| i16::from_le_bytes([s[0], s[1]]) as f32 / 32768.0).collect(),
|
||||
(3, 32) => data.chunks_exact(4).map(|s| f32::from_le_bytes([s[0], s[1], s[2], s[3]])).collect(),
|
||||
_ => bail!("{}: a {bits}-bit WAV of kind {kind}; 16-bit PCM and 32-bit float are read", path.display()),
|
||||
};
|
||||
return Ok((mono(&one, ch.max(1)), rate));
|
||||
}
|
||||
at = body + len + (len & 1);
|
||||
}
|
||||
bail!("{}: a WAV with no sound in it", path.display())
|
||||
}
|
||||
|
||||
/// Mono samples as a 16-bit WAV.
|
||||
pub fn write_wav(path: &Path, x: &[f32], rate: u32) -> anyhow::Result<()> {
|
||||
let mut b = Vec::with_capacity(44 + x.len() * 2);
|
||||
let len = (x.len() * 2) as u32;
|
||||
b.extend_from_slice(b"RIFF");
|
||||
b.extend_from_slice(&(36 + len).to_le_bytes());
|
||||
b.extend_from_slice(b"WAVEfmt ");
|
||||
for v in [16u32, 1 | (1 << 16), rate, rate * 2, 2 | (16 << 16)] {
|
||||
b.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
b.extend_from_slice(b"data");
|
||||
b.extend_from_slice(&len.to_le_bytes());
|
||||
for s in x {
|
||||
b.extend_from_slice(&((s.clamp(-1.0, 1.0) * 32767.0) as i16).to_le_bytes());
|
||||
}
|
||||
std::fs::write(path, b).with_context(|| format!("{}", path.display()))
|
||||
}
|
||||
|
||||
/// The microphone: 16 kHz mono in pieces down `tx` for as long as the stream it returns is kept.
|
||||
pub fn microphone(tx: Sender<Vec<f32>>) -> anyhow::Result<cpal::Stream> {
|
||||
let dev = cpal::default_host().default_input_device().ok_or_else(|| anyhow!("this computer has no microphone to listen on"))?;
|
||||
let cfg = dev.default_input_config().map_err(|e| anyhow!("the microphone: {e}"))?;
|
||||
let ch = cfg.channels().max(1) as usize;
|
||||
let mut rs = Resample::new(cfg.sample_rate().0, crate::turns::RATE as u32);
|
||||
let mut take = move |mono: Vec<f32>| {
|
||||
let mut out = Vec::with_capacity(mono.len());
|
||||
rs.push(&mono, &mut out);
|
||||
let _ = tx.send(out);
|
||||
};
|
||||
let bad = raea_io_trace::once::said_once::<cpal::StreamError>("raea voice: the microphone");
|
||||
let stream = match cfg.sample_format() {
|
||||
cpal::SampleFormat::F32 => {
|
||||
dev.build_input_stream(&cfg.config(), move |d: &[f32], _: &cpal::InputCallbackInfo| take(mono(d, ch)), bad, None)
|
||||
}
|
||||
cpal::SampleFormat::I16 => dev.build_input_stream(
|
||||
&cfg.config(),
|
||||
move |d: &[i16], _: &cpal::InputCallbackInfo| {
|
||||
let x: Vec<f32> = d.iter().map(|s| *s as f32 / 32768.0).collect();
|
||||
take(mono(&x, ch))
|
||||
},
|
||||
bad,
|
||||
None,
|
||||
),
|
||||
f => bail!("the microphone gives {f:?} samples, which raea voice doesn't read"),
|
||||
}
|
||||
.map_err(|e| anyhow!("the microphone didn't open (is raea allowed to use it? System Settings > Privacy & Security > Microphone): {e}"))?;
|
||||
stream.play().map_err(|e| anyhow!("the microphone didn't start: {e}"))?;
|
||||
Ok(stream)
|
||||
}
|
||||
|
||||
/// A WAV in the microphone's place: its sound at the pace it was recorded (at once with `fast`), a second and a half
|
||||
/// of quiet after it so its last turn ends, and then the channel closes.
|
||||
pub fn microphone_file(path: &Path, fast: bool, tx: Sender<Vec<f32>>) -> anyhow::Result<()> {
|
||||
let (x, rate) = read_wav(path)?;
|
||||
let mut heard = Vec::with_capacity(x.len());
|
||||
Resample::new(rate, crate::turns::RATE as u32).push(&x, &mut heard);
|
||||
heard.extend(std::iter::repeat_n(0.0, crate::turns::RATE * 3 / 2));
|
||||
std::thread::spawn(move || {
|
||||
// by the clock from its start, so a late wake-up is made up and it keeps a microphone's pace
|
||||
let (began, mut sent) = (Instant::now(), 0u64);
|
||||
for piece in heard.chunks(crate::turns::WIN) {
|
||||
if tx.send(piece.to_vec()).is_err() {
|
||||
return;
|
||||
}
|
||||
sent += piece.len() as u64;
|
||||
if !fast {
|
||||
std::thread::sleep((began + Duration::from_micros(1_000_000 * sent / crate::turns::RATE as u64)).saturating_duration_since(Instant::now()));
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What is waiting to be played, shared with whoever makes the sound.
|
||||
pub struct Line {
|
||||
pub queue: Mutex<VecDeque<f32>>,
|
||||
/// samples played so far, at the voice's rate
|
||||
pub played: AtomicU64,
|
||||
/// everything played, when it goes to a file
|
||||
kept: Mutex<Vec<f32>>,
|
||||
keep: AtomicBool,
|
||||
/// what went to the speakers, quiet included, for the echo to be taken out of the microphone (echo.rs): kept
|
||||
/// while `tap` is on, and taken by the session
|
||||
pub far: Mutex<Vec<f32>>,
|
||||
pub tap: AtomicBool,
|
||||
}
|
||||
|
||||
impl Line {
|
||||
/// Drops what hasn't been played yet (the person spoke over it, or it was stopped).
|
||||
pub fn clear(&self) {
|
||||
self.queue.lock().unwrap().clear();
|
||||
}
|
||||
|
||||
/// (samples played so far, samples still waiting to be)
|
||||
pub fn at(&self) -> (u64, usize) {
|
||||
(self.played.load(Ordering::Relaxed), self.queue.lock().unwrap().len())
|
||||
}
|
||||
|
||||
/// The next `n` samples (fewer when the queue runs out), counted as played.
|
||||
fn take(&self, want: usize) -> Vec<f32> {
|
||||
let mut q = self.queue.lock().unwrap();
|
||||
let n = want.min(q.len());
|
||||
let got: Vec<f32> = q.drain(..n).collect();
|
||||
self.played.fetch_add(n as u64, Ordering::Relaxed);
|
||||
if self.keep.load(Ordering::Relaxed) {
|
||||
self.kept.lock().unwrap().extend(&got);
|
||||
}
|
||||
if self.tap.load(Ordering::Relaxed) && want < 1 << 20 {
|
||||
let mut far = self.far.lock().unwrap();
|
||||
far.extend(&got);
|
||||
far.extend(std::iter::repeat_n(0.0, want - n));
|
||||
}
|
||||
got
|
||||
}
|
||||
}
|
||||
|
||||
/// A file in the speakers' place: what is waiting is taken at the pace it would play (all of it at once with `fast`).
|
||||
fn drain(line: Arc<Line>, each: usize) {
|
||||
std::thread::spawn(move || {
|
||||
let (began, mut ticks) = (Instant::now(), 0u32);
|
||||
while Arc::strong_count(&line) > 1 {
|
||||
ticks += 1;
|
||||
std::thread::sleep((began + Duration::from_millis(20) * ticks).saturating_duration_since(Instant::now()));
|
||||
line.take(each);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The speakers, or a file in their place.
|
||||
pub struct Speaker {
|
||||
pub line: Arc<Line>,
|
||||
rate: u32,
|
||||
to: Option<PathBuf>,
|
||||
_stream: Option<cpal::Stream>,
|
||||
}
|
||||
|
||||
impl Speaker {
|
||||
/// `rate`: the voice's. With `to`, nothing sounds: what would have played is written there when the session ends.
|
||||
pub fn open(rate: u32, to: Option<PathBuf>, fast: bool) -> anyhow::Result<Speaker> {
|
||||
let line = Arc::new(Line { queue: Mutex::new(VecDeque::new()), played: AtomicU64::new(0), kept: Mutex::new(Vec::new()), keep: AtomicBool::new(to.is_some()), far: Mutex::new(Vec::new()), tap: AtomicBool::new(false) });
|
||||
if to.is_some() {
|
||||
drain(line.clone(), if fast { usize::MAX } else { rate as usize / 50 });
|
||||
return Ok(Speaker { line, rate, to, _stream: None });
|
||||
}
|
||||
let dev = cpal::default_host().default_output_device().ok_or_else(|| anyhow!("this computer has nothing to play sound on"))?;
|
||||
let cfg = dev.default_output_config().map_err(|e| anyhow!("the speakers: {e}"))?;
|
||||
anyhow::ensure!(cfg.sample_format() == cpal::SampleFormat::F32, "the speakers take {:?} samples, which raea voice doesn't write", cfg.sample_format());
|
||||
let ch = cfg.channels().max(1) as usize;
|
||||
let mut rs = Resample::new(rate, cfg.sample_rate().0);
|
||||
let need = rate as f64 / cfg.sample_rate().0 as f64;
|
||||
let l = line.clone();
|
||||
let mut ready: VecDeque<f32> = VecDeque::new();
|
||||
let play = move |out: &mut [f32], _: &cpal::OutputCallbackInfo| {
|
||||
let frames = out.len() / ch;
|
||||
if ready.len() < frames {
|
||||
let mut made = Vec::new();
|
||||
rs.push(&l.take(((frames - ready.len()) as f64 * need).ceil() as usize + 2), &mut made);
|
||||
ready.extend(made);
|
||||
}
|
||||
for f in out.chunks_mut(ch) {
|
||||
f.fill(ready.pop_front().unwrap_or(0.0));
|
||||
}
|
||||
};
|
||||
let stream = dev.build_output_stream(&cfg.config(), play, raea_io_trace::once::said_once::<cpal::StreamError>("raea voice: the speakers"), None).map_err(|e| anyhow!("the speakers didn't open: {e}"))?;
|
||||
stream.play().map_err(|e| anyhow!("the speakers didn't start: {e}"))?;
|
||||
Ok(Speaker { line, rate, to, _stream: Some(stream) })
|
||||
}
|
||||
|
||||
/// Writes the file, when the session's sound went to one.
|
||||
pub fn close(&self) -> anyhow::Result<()> {
|
||||
match &self.to {
|
||||
Some(p) => write_wav(p, &self.line.kept.lock().unwrap(), self.rate),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_rate_changes_piece_by_piece_as_it_would_whole() {
|
||||
let x: Vec<f32> = (0..4800).map(|i| (i as f32 * 0.01).sin()).collect();
|
||||
let mut whole = Vec::new();
|
||||
Resample::new(48_000, 16_000).push(&x, &mut whole);
|
||||
let mut pieces = Vec::new();
|
||||
let mut rs = Resample::new(48_000, 16_000);
|
||||
for p in x.chunks(477) {
|
||||
rs.push(p, &mut pieces);
|
||||
}
|
||||
assert!((whole.len() as i64 - 1600).abs() <= 1, "a third as many samples: {}", whole.len());
|
||||
assert_eq!(whole.len(), pieces.len());
|
||||
assert!(whole.iter().zip(&pieces).all(|(a, b)| (a - b).abs() < 1e-5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wav_written_reads_back() {
|
||||
let f = std::env::temp_dir().join(format!("raea-voice-{}.wav", std::process::id()));
|
||||
let x: Vec<f32> = (0..2400).map(|i| (i as f32 * 0.05).sin() * 0.5).collect();
|
||||
write_wav(&f, &x, 24_000).unwrap();
|
||||
let (y, rate) = read_wav(&f).unwrap();
|
||||
std::fs::remove_file(&f).unwrap();
|
||||
assert_eq!((rate, y.len()), (24_000, x.len()));
|
||||
assert!(x.iter().zip(&y).all(|(a, b)| (a - b).abs() < 1e-3));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
//! raea's own voice taken out of what the microphone hears, so the person can talk over it.
|
||||
//!
|
||||
//! A computer's microphone hears its speakers. While raea speaks, what was sent to the speakers (the far side) is
|
||||
//! passed through a filter that learns the way from speaker to microphone (an NLMS adaptive filter, 128 ms long, at
|
||||
//! the hearing rate), and what the filter makes of it is taken from the microphone's sound. What is left is the
|
||||
//! person, when they speak. Where in time the echo sits (the sound card's and the room's delay) is found first, by
|
||||
//! lining up the two sides' loudness over the last second.
|
||||
//!
|
||||
//! Until the filter has learned the room (`sure`: a second of its voice, the echo down by 10 dB or more) nothing
|
||||
//! left over counts as the person, so raea is never stopped by its own voice. Once it has, sound that stands clear
|
||||
//! of the echo is the person (`near`). Two filters do it (the two-path way): the one in use never learns, the one
|
||||
//! behind it always does and replaces it when it leaves less, so the person's voice is never learned as echo.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::audio::Resample;
|
||||
use crate::turns::WIN;
|
||||
|
||||
/// The filter's length: 128 ms of the way from speaker to microphone.
|
||||
const TAPS: usize = 2048;
|
||||
/// Loudness is compared in blocks of 4 ms.
|
||||
const BLOCK: usize = 64;
|
||||
/// The echo is looked for up to 480 ms late.
|
||||
const LAGS: usize = 120;
|
||||
/// A second of loudness is lined up.
|
||||
const ENV: usize = 250;
|
||||
/// How much of the far side is kept: the latest echo the filter can be asked about.
|
||||
const HIST: usize = LAGS * BLOCK + TAPS + WIN;
|
||||
/// The far side counts as sounding above this mean square (about -60 dBFS).
|
||||
const SOUNDING: f32 = 1e-6;
|
||||
/// How fast the filter learns.
|
||||
const MU: f32 = 0.3;
|
||||
|
||||
/// What a window turned out to hold.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct Heard {
|
||||
/// raea's own voice was sounding in it
|
||||
pub far: bool,
|
||||
/// something stands clear of raea's own voice (always, when raea is quiet)
|
||||
pub near: bool,
|
||||
/// the filter has learned the room: what's left can be trusted
|
||||
pub sure: bool,
|
||||
}
|
||||
|
||||
pub struct Echo {
|
||||
far: Vec<f32>,
|
||||
w: Vec<f32>,
|
||||
/// the filter behind it, always learning; and for how many windows it has done better, or worse
|
||||
behind: Vec<f32>,
|
||||
better: usize,
|
||||
worse: usize,
|
||||
pub delay: usize,
|
||||
mic_env: Vec<f32>,
|
||||
far_env: Vec<f32>,
|
||||
/// a delay seen, and how many times in a row
|
||||
vote: (usize, usize),
|
||||
/// how much quieter the echo leaves than it came, smoothed
|
||||
pub erle: f32,
|
||||
/// windows learned on since the delay was last set
|
||||
learned: usize,
|
||||
sure: bool,
|
||||
windows: usize,
|
||||
}
|
||||
|
||||
impl Default for Echo {
|
||||
fn default() -> Echo {
|
||||
Echo { far: vec![0.0; HIST], w: vec![0.0; TAPS], behind: vec![0.0; TAPS], better: 0, worse: 0, delay: 0, mic_env: Vec::new(), far_env: Vec::new(), vote: (0, 0), erle: 1.0, learned: 0, sure: false, windows: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
fn power(x: &[f32]) -> f32 {
|
||||
let mut p = 0.0;
|
||||
for s in x {
|
||||
p += s * s;
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
impl Echo {
|
||||
/// The filter starts over (the echo moved in time, or the room changed).
|
||||
fn forget(&mut self) {
|
||||
self.w.fill(0.0);
|
||||
self.behind.fill(0.0);
|
||||
(self.erle, self.learned, self.sure, self.better, self.worse) = (1.0, 0, false, 0, 0);
|
||||
}
|
||||
|
||||
/// Where the echo sits: the lag (in blocks) at which the microphone's loudness follows the far side's best.
|
||||
fn lag(&self) -> Option<usize> {
|
||||
if self.mic_env.len() < ENV || self.far_env.len() < ENV + LAGS {
|
||||
return None;
|
||||
}
|
||||
let mic = &self.mic_env[self.mic_env.len() - ENV..];
|
||||
let mean = |x: &[f32]| x.iter().sum::<f32>() / x.len() as f32;
|
||||
let (mm, mut best) = (mean(mic), (0.6, None));
|
||||
let mv: f32 = mic.iter().map(|a| (a - mm) * (a - mm)).sum();
|
||||
for l in 0..=LAGS {
|
||||
let at = self.far_env.len() - ENV - l;
|
||||
let far = &self.far_env[at..at + ENV];
|
||||
let fm = mean(far);
|
||||
let (mut c, mut fv) = (0.0, 0.0);
|
||||
for (a, b) in mic.iter().zip(far) {
|
||||
c += (a - mm) * (b - fm);
|
||||
fv += (b - fm) * (b - fm);
|
||||
}
|
||||
let r = c / (mv * fv).sqrt().max(1e-12);
|
||||
if r > best.0 {
|
||||
best = (r, Some(l));
|
||||
}
|
||||
}
|
||||
best.1
|
||||
}
|
||||
|
||||
/// One pass of a filter over a window: what's left of `mic` goes to `out`; returns (left, echo made) as power,
|
||||
/// each sample's judged before the filter learns from it.
|
||||
fn pass(far: &[f32], delay: usize, w: &mut [f32], mic: &[f32], learn: bool, out: &mut [f32]) -> (f32, f32) {
|
||||
let (mut left, mut made) = (0.0, 0.0);
|
||||
let first = far.len() - mic.len() - delay;
|
||||
let mut norm = power(&far[first + 1 - TAPS..=first]);
|
||||
for (n, d) in mic.iter().enumerate() {
|
||||
let at = first + n;
|
||||
if n > 0 {
|
||||
norm += far[at] * far[at] - far[at - TAPS] * far[at - TAPS];
|
||||
}
|
||||
let x = &far[at + 1 - TAPS..=at];
|
||||
let mut y = 0.0;
|
||||
for (a, b) in w.iter().zip(x) {
|
||||
y += a * b;
|
||||
}
|
||||
let e = d - y;
|
||||
if learn && norm > SOUNDING {
|
||||
let g = MU * e / (norm + 1e-3);
|
||||
for (a, b) in w.iter_mut().zip(x) {
|
||||
*a += g * b;
|
||||
}
|
||||
}
|
||||
out[n] = e;
|
||||
left += e * e;
|
||||
made += y * y;
|
||||
}
|
||||
(left, made)
|
||||
}
|
||||
|
||||
/// A window of the microphone and the window of the far side played with it. What's left of the microphone's
|
||||
/// goes to `out`.
|
||||
pub fn push(&mut self, mic: &[f32], far: &[f32], out: &mut Vec<f32>) -> Heard {
|
||||
self.far.drain(..far.len());
|
||||
self.far.extend_from_slice(far);
|
||||
for (m, f) in mic.chunks(BLOCK).zip(far.chunks(BLOCK)) {
|
||||
self.mic_env.push(power(m));
|
||||
self.far_env.push(power(f));
|
||||
}
|
||||
let (m, f) = (self.mic_env.len().saturating_sub(ENV), self.far_env.len().saturating_sub(ENV + LAGS));
|
||||
self.mic_env.drain(..m);
|
||||
self.far_env.drain(..f);
|
||||
self.windows += 1;
|
||||
out.clear();
|
||||
out.resize(mic.len(), 0.0);
|
||||
|
||||
// is raea's voice in what the filter is asked about, and has the echo moved?
|
||||
let span = &self.far[self.far.len() - mic.len() - self.delay - TAPS..self.far.len() - self.delay];
|
||||
let sounding = power(span) / span.len() as f32 > SOUNDING;
|
||||
let loud = self.far_env[self.far_env.len().saturating_sub(ENV)..].iter().sum::<f32>() / (ENV * BLOCK) as f32 > SOUNDING;
|
||||
if loud && self.windows % 4 == 0 {
|
||||
if let Some(l) = self.lag() {
|
||||
self.vote = if l == self.vote.0 { (l, self.vote.1 + 1) } else { (l, 1) };
|
||||
// the filter starts 8 ms before where the echo is loudest
|
||||
let to = l.saturating_sub(2) * BLOCK;
|
||||
if self.vote.1 >= 3 && to.abs_diff(self.delay) > 2 * BLOCK {
|
||||
self.delay = to;
|
||||
self.forget();
|
||||
}
|
||||
}
|
||||
}
|
||||
if !sounding {
|
||||
out.copy_from_slice(mic);
|
||||
return Heard { far: false, near: true, sure: self.sure };
|
||||
}
|
||||
|
||||
// The filter that is used only takes out; a second one behind it never stops learning. When the second
|
||||
// leaves less (the first hadn't met this sound yet, or the room changed), it becomes the first. The person's
|
||||
// voice can't be learned as echo that way: it makes the second worse, not better, and the first is untouched.
|
||||
let (left, made) = Echo::pass(&self.far, self.delay, &mut self.w, mic, false, out);
|
||||
let mut scratch = vec![0.0; mic.len()];
|
||||
// (the one behind is judged as it stood before this window, then learns from it: judged while it learns, it
|
||||
// seems to take out some of any voice, since each sample's correction carries into the next)
|
||||
let (behind, _) = Echo::pass(&self.far, self.delay, &mut self.behind, mic, false, &mut scratch);
|
||||
Echo::pass(&self.far, self.delay, &mut self.behind, mic, true, &mut scratch);
|
||||
// (better only when it also takes most of the sound out: with the person talking nothing can, so a filter
|
||||
// that chased their voice is never taken up)
|
||||
let came = power(mic);
|
||||
self.better = if behind < 0.7 * left && behind < 0.5 * came { self.better + 1 } else { 0 };
|
||||
self.worse = if behind > 2.0 * left { self.worse + 1 } else { 0 };
|
||||
// (the person's voice leaves the one behind no better off; a sound the filter hadn't met does, at once)
|
||||
let misfit = behind < 0.85 * left;
|
||||
if self.better >= 2 {
|
||||
self.w.copy_from_slice(&self.behind);
|
||||
self.better = 0;
|
||||
} else if self.worse >= 3 {
|
||||
self.behind.copy_from_slice(&self.w);
|
||||
self.worse = 0;
|
||||
}
|
||||
// clear of the echo: well above what the filter usually leaves of it (four times, and never under a sixteenth),
|
||||
// and not something the filter behind could have taken out
|
||||
// (what is louder than the whole echo can't be the echo misjudged, whatever the filter behind makes of it)
|
||||
let near = (!misfit || left > 2.0 * made) && left > made * (4.0 / self.erle).max(0.06) && left / mic.len() as f32 > SOUNDING;
|
||||
if !(self.sure && near) {
|
||||
self.erle = 0.9 * self.erle + 0.1 * (came / left.max(1e-12)).min(1000.0);
|
||||
}
|
||||
// a filter gone wrong adds sound: then the microphone's own is what's left
|
||||
if left > came {
|
||||
out.copy_from_slice(mic);
|
||||
}
|
||||
self.learned += 1;
|
||||
// a second of its own voice learned, and the echo down by 10 dB (7 dB keeps it, once reached)
|
||||
self.sure = self.learned >= 32 && self.erle >= if self.sure { 5.0 } else { 10.0 };
|
||||
Heard { far: true, near, sure: self.sure }
|
||||
}
|
||||
}
|
||||
|
||||
/// The far side lined up with the microphone, window by window. Both come at their own pace in pieces, so a
|
||||
/// microphone window waits (a few milliseconds) until the far side that played with it, and the two windows after,
|
||||
/// have arrived: the echo then always comes after the sound that made it, never before.
|
||||
pub struct Sides {
|
||||
rs: Resample,
|
||||
far: Vec<f32>,
|
||||
/// how many far samples came before `far[0]`
|
||||
base: u64,
|
||||
/// the far sample that plays as the microphone's first is heard
|
||||
offset: Option<u64>,
|
||||
mic: u64,
|
||||
held: VecDeque<(Vec<f32>, Instant)>,
|
||||
room: Option<f32>,
|
||||
}
|
||||
|
||||
impl Sides {
|
||||
/// `rate`: the far side's. `room`: a simulated room's gain (checks), in place of a real one.
|
||||
pub fn new(rate: u32, room: Option<f32>) -> Sides {
|
||||
Sides { rs: Resample::new(rate, crate::turns::RATE as u32), far: vec![0.0; SPAN + WIN], base: 0, offset: None, mic: 0, held: VecDeque::new(), room }
|
||||
}
|
||||
|
||||
/// More of what went to the speakers.
|
||||
pub fn far(&mut self, x: &[f32]) {
|
||||
self.rs.push(x, &mut self.far);
|
||||
}
|
||||
|
||||
/// A window from the microphone.
|
||||
pub fn mic(&mut self, win: Vec<f32>) {
|
||||
self.held.push_back((win, Instant::now()));
|
||||
}
|
||||
|
||||
/// The next microphone window whose far side has come, and that far side.
|
||||
pub fn next(&mut self) -> Option<(Vec<f32>, Vec<f32>)> {
|
||||
let waited = self.held.front()?.1.elapsed();
|
||||
let total = self.base + self.far.len() as u64;
|
||||
let offset = *self.offset.get_or_insert(total);
|
||||
// where the far side stands as this window ends, and the two windows more the filter is given
|
||||
let now = offset + self.mic + WIN as u64;
|
||||
let end = now + 2 * WIN as u64;
|
||||
if total < end {
|
||||
// the speakers aren't being fed (they stopped, or never started): quiet stands in
|
||||
if waited < Duration::from_millis(300) {
|
||||
return None;
|
||||
}
|
||||
self.far.resize(self.far.len() + (end - total) as usize, 0.0);
|
||||
}
|
||||
let (mut mic, _) = self.held.pop_front()?;
|
||||
let at = |i: u64| (i - self.base) as usize;
|
||||
if let Some(gain) = self.room {
|
||||
room(&self.far[at(now) - WIN - SPAN..at(now)], gain, &mut mic);
|
||||
}
|
||||
let far = self.far[at(end) - WIN..at(end)].to_vec();
|
||||
self.mic += WIN as u64;
|
||||
// the far side behind what any later window can ask for goes
|
||||
let old = at(now).saturating_sub(WIN + SPAN);
|
||||
if old > 16_000 {
|
||||
self.far.drain(..old);
|
||||
self.base += old as u64;
|
||||
}
|
||||
Some((mic, far))
|
||||
}
|
||||
}
|
||||
|
||||
/// A room, for checks with no microphone: what the far side sounds like to a microphone 40 ms and a few surfaces
|
||||
/// away, at `gain`, added to `mic`. `far` ends where `mic` does and is `SPAN` longer.
|
||||
pub fn room(far: &[f32], gain: f32, mic: &mut [f32]) {
|
||||
const WAYS: [(usize, f32); 6] = [(640, 1.0), (688, -0.45), (816, 0.3), (1008, -0.2), (1360, 0.12), (1840, -0.07)];
|
||||
let first = far.len() - mic.len();
|
||||
for (n, m) in mic.iter_mut().enumerate() {
|
||||
let mut e = 0.0;
|
||||
for (late, by) in WAYS {
|
||||
e += by * far[first + n - late];
|
||||
}
|
||||
*m += gain * e;
|
||||
}
|
||||
}
|
||||
/// How much more of the far side `room` needs than the window it fills.
|
||||
pub const SPAN: usize = 1840;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Something like speech: noise that swells and falls a few times a second.
|
||||
fn babble(n: usize, seed: u32) -> Vec<f32> {
|
||||
let mut s = seed;
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
|
||||
let noise = (s >> 8) as f32 / (1u32 << 24) as f32 - 0.5;
|
||||
noise * 0.4 * (0.55 + 0.45 * (i as f32 * 0.0021).sin()) * if (i / 4000) % 3 == 2 { 0.05 } else { 1.0 }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Runs `secs` of raea talking in the simulated room, the person talking over it from `over` (a window) on.
|
||||
fn run(secs: usize, over: Option<usize>) -> (Echo, Vec<Heard>, Vec<f32>) {
|
||||
let n = secs * 16_000 / WIN;
|
||||
let far = babble(n * WIN + SPAN, 7);
|
||||
let person = babble(n * WIN, 99);
|
||||
let (mut echo, mut heard, mut ratio, mut out) = (Echo::default(), Vec::new(), Vec::new(), Vec::new());
|
||||
for k in 0..n {
|
||||
let mut mic = vec![0.0; WIN];
|
||||
room(&far[k * WIN..(k + 1) * WIN + SPAN], 0.8, &mut mic);
|
||||
if over.is_some_and(|o| k >= o) {
|
||||
for (m, p) in mic.iter_mut().zip(&person[k * WIN..]) {
|
||||
*m += p * 0.8;
|
||||
}
|
||||
}
|
||||
let came = power(&mic);
|
||||
heard.push(echo.push(&mic, &far[SPAN + k * WIN..SPAN + (k + 1) * WIN], &mut out));
|
||||
ratio.push(power(&out) / came.max(1e-12));
|
||||
}
|
||||
(echo, heard, ratio)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn its_own_voice_is_learned_and_taken_out() {
|
||||
let (echo, heard, ratio) = run(6, None);
|
||||
// the echo's direct sound is 640 samples late: the filter starts just before it
|
||||
assert!(echo.delay <= 640 && echo.delay + 256 >= 640, "delay {}", echo.delay);
|
||||
let sure = heard.iter().position(|h| h.sure).expect("never sure");
|
||||
assert!(sure < 3 * 16_000 / WIN, "sure only after {sure} windows");
|
||||
// once sure, nothing is taken for the person, and the echo is down to a twentieth or less in most windows
|
||||
let after = sure + 16;
|
||||
// (some windows stand out while the filter in use waits for the one behind; the session also wants them to
|
||||
// sound like speech, which noise doesn't)
|
||||
let own = heard[after..].iter().filter(|h| h.far && h.near).count();
|
||||
assert!(own * 5 <= heard.len() - after, "its own voice taken for the person in {own} of {} windows", heard.len() - after);
|
||||
let mut late: Vec<f32> = heard[after..].iter().zip(&ratio[after..]).filter(|(h, _)| h.far).map(|(_, r)| *r).collect();
|
||||
late.sort_by(f32::total_cmp);
|
||||
assert!(late[late.len() / 2] < 0.05, "half the windows keep more than a twentieth: {}", late[late.len() / 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_person_talking_over_it_stands_clear() {
|
||||
let at = 5 * 16_000 / WIN;
|
||||
let (_, heard, ratio) = run(6, Some(at));
|
||||
assert!(heard[at - 1].sure);
|
||||
let over = &heard[at..];
|
||||
let clear = over.iter().filter(|h| h.near).count();
|
||||
assert!(clear * 10 >= over.len() * 6, "clear in {clear} of {} windows", over.len());
|
||||
// (their voice has pauses) and it is left in: most of what came is still there
|
||||
assert!(ratio[at..].iter().sum::<f32>() / over.len() as f32 > 0.3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quiet_passes_through() {
|
||||
let (mut echo, mut out) = (Echo::default(), Vec::new());
|
||||
let mic: Vec<f32> = (0..WIN).map(|i| (i as f32 * 0.1).sin() * 0.2).collect();
|
||||
let h = echo.push(&mic, &[0.0; WIN], &mut out);
|
||||
assert!(!h.far && h.near && out == mic);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
//! `raea voice`: speech to speech on this computer, for an agent that talks (the app's ideation session). Silero VAD
|
||||
//! says when the person starts and stops speaking, Parakeet says what they said, and Pocket TTS says the agent's
|
||||
//! words as they arrive, sentence by sentence. Nothing leaves the computer and nothing is paid for; the models are
|
||||
//! fetched the first time (about 800 MB) into raea's model folder.
|
||||
//!
|
||||
//! `raea voice` is a session over lines of JSON (session.rs has them). `raea voice hear FILE.wav` and
|
||||
//! `raea voice say "WORDS" -o OUT.wav` are one hearing and one saying, with how long each took.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::time::Instant;
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
pub mod asr;
|
||||
pub mod audio;
|
||||
pub mod echo;
|
||||
pub mod session;
|
||||
pub mod speak;
|
||||
pub mod turns;
|
||||
|
||||
pub const USAGE: &str = "raea voice [--voice NAME] [--duplex] [--over] [--pause MS] [--from IN.wav] [--to OUT.wav] [--room GAIN] [--fast] | raea voice hear FILE.wav | raea voice say \"WORDS\" -o OUT.wav [--voice NAME]";
|
||||
pub const ABOUT: &str = "speech in and out on this computer, as lines of JSON on stdin and stdout: what raea.app's Ideate hears and speaks with. While it speaks it doesn't listen, unless --duplex (headphones: it listens all the time) or --over (speakers: its own voice is taken out of the microphone's sound, new and not yet tried across real rooms); --room GAIN is a simulated room for checking --over with files; hear writes a recording's words, say speaks words to a file";
|
||||
|
||||
/// A model's download told as it goes, once every 20 MB of each file.
|
||||
pub fn fetching(emit: fn(serde_json::Value)) -> impl FnMut(&str, u64) {
|
||||
let mut last = (String::new(), 0u64);
|
||||
move |file: &str, bytes: u64| {
|
||||
let mb = bytes / 20_000_000 * 20;
|
||||
if last.0 != file || last.1 != mb {
|
||||
last = (file.to_string(), mb);
|
||||
emit(json!({ "fetch": { "file": file, "mb": mb } }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The word after `name` on the command line.
|
||||
fn flag(args: &[String], name: &str) -> Option<String> {
|
||||
args.windows(2).find(|w| w[0] == name).map(|w| w[1].clone())
|
||||
}
|
||||
|
||||
fn quiet(_: serde_json::Value) {}
|
||||
|
||||
/// `raea voice hear FILE.wav`: what the file says, with how long loading and hearing took.
|
||||
fn hear(file: &str) -> anyhow::Result<String> {
|
||||
let (x, rate) = audio::read_wav(std::path::Path::new(file))?;
|
||||
let mut heard = Vec::with_capacity(x.len());
|
||||
audio::Resample::new(rate, turns::RATE as u32).push(&x, &mut heard);
|
||||
let t = Instant::now();
|
||||
let mut asr = asr::Asr::load(&raea_sys_ml::models::ensure(&asr::SPEC, &mut fetching(quiet))?)?;
|
||||
let load_ms = t.elapsed().as_millis() as u64;
|
||||
let t = Instant::now();
|
||||
let text = asr.hear(&heard)?;
|
||||
Ok(json!({ "text": text, "seconds": heard.len() as f64 / turns::RATE as f64, "load_ms": load_ms, "ms": t.elapsed().as_millis() as u64 }).to_string())
|
||||
}
|
||||
|
||||
/// `raea voice say "WORDS" -o OUT.wav`: the words said into a file, with how long the first sound and the whole took.
|
||||
fn say(text: &str, out: &str, voice: Option<String>) -> anyhow::Result<String> {
|
||||
use raea_sys_speech::pocket::{Out, Pocket};
|
||||
let t = Instant::now();
|
||||
let mut pocket = Pocket::load(&raea_sys_ml::models::ensure(&Pocket::SPEC, &mut fetching(quiet))?)?;
|
||||
// Pocket's stock voice, as a session's: never the clip the library's own default takes from the person's voice folder
|
||||
let voice = voice.unwrap_or_else(|| Pocket::VOICES[0].to_string());
|
||||
pocket.begin("", &voice, 1, 0.7)?;
|
||||
let load_ms = t.elapsed().as_millis() as u64;
|
||||
let t = Instant::now();
|
||||
let (mut sound, mut first_ms) = (Vec::new(), None);
|
||||
let mut g = pocket.begin(text, &voice, 7, 0.7)?;
|
||||
while let Some(o) = pocket.step(&mut g)? {
|
||||
if let Out::Audio(a) = o {
|
||||
first_ms.get_or_insert(t.elapsed().as_millis() as u64);
|
||||
sound.extend(a);
|
||||
}
|
||||
}
|
||||
let ms = t.elapsed().as_millis() as u64;
|
||||
audio::write_wav(std::path::Path::new(out), &sound, speak::RATE)?;
|
||||
Ok(json!({ "voice": voice, "seconds": sound.len() as f64 / speak::RATE as f64, "load_ms": load_ms, "first_ms": first_ms, "ms": ms }).to_string())
|
||||
}
|
||||
|
||||
pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
let said = |e: anyhow::Error| format!("raea voice: {e:#}");
|
||||
match args.get(1).map(String::as_str) {
|
||||
Some("hear") => hear(args.get(2).ok_or(USAGE)?).map_err(said),
|
||||
Some("say") => say(args.get(2).ok_or(USAGE)?, &flag(args, "-o").ok_or(USAGE)?, flag(args, "--voice")).map_err(said),
|
||||
Some("help" | "--help" | "-h") => Ok(format!("usage: {USAGE}\n({ABOUT})")),
|
||||
Some(a) if !a.starts_with("--") => Err(USAGE.into()),
|
||||
_ => {
|
||||
let pause_ms = match flag(args, "--pause") {
|
||||
Some(p) => p.parse().map_err(|_| "--pause takes milliseconds".to_string())?,
|
||||
None => 700,
|
||||
};
|
||||
let o = session::Opts {
|
||||
from: flag(args, "--from").map(PathBuf::from),
|
||||
to: flag(args, "--to").map(PathBuf::from),
|
||||
voice: flag(args, "--voice"),
|
||||
duplex: args.iter().any(|a| a == "--duplex"),
|
||||
over: args.iter().any(|a| a == "--over"),
|
||||
room: match flag(args, "--room") {
|
||||
Some(g) => Some(g.parse().map_err(|_| "--room takes a gain, like 0.5".to_string())?),
|
||||
None => None,
|
||||
},
|
||||
fast: args.iter().any(|a| a == "--fast"),
|
||||
pause_ms,
|
||||
};
|
||||
session::run(o).map(|_| String::new()).map_err(|e| {
|
||||
session::emit(json!({ "error": format!("{e:#}") }));
|
||||
said(e)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 2567 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user