Compare commits

..
418 changed files with 679 additions and 90201 deletions

No files matched your search

+1 -6
View File
@@ -118,12 +118,7 @@ jobs:
# debug info off: with it the test binaries of the app crates filled 27 GB of a runner's disk (#90)
env:
CARGO_PROFILE_TEST_DEBUG: "0"
# raea-bundle in a call of its own: Rolldown's crates turn on serde_json's arbitrary_precision, features unify
# across one cargo call, and with it on an untagged enum can't read a number (raea-core-brief's make dials failed
# here from 11-23 while passing alone). raea itself never links Rolldown: it loads it as a library at run time
run: |
cargo test --locked -p raea-runtime-plugins -p raea-io-media -p raea-core-fonts -p raea-native -p raea-core-brief -p raea-core-k -p raea-app-check -p raea-app-check-flash -p raea-io-ffmpeg -p raea-app-workspace -p raea-app-tools -p raea-app-targets
cargo test --locked -p raea-bundle
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
- 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
+1 -36
View File
@@ -2,7 +2,6 @@
# 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):
@@ -182,11 +181,6 @@ 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()
@@ -195,8 +189,6 @@ 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
@@ -210,10 +202,6 @@ 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:
@@ -221,16 +209,11 @@ 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*
dist/raea-*.AppImage*
path: dist/raea-*.tar.gz*
retention-days: 3
compression-level: 0
@@ -240,9 +223,6 @@ 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
@@ -372,24 +352,9 @@ jobs:
run: bash tools/release/lavapipe.sh
- name: Where the skills gate passed
run: bash tools/release/skills-passed.sh "$TAG" "${{ inputs.skills_passed }}"
# raea's own Windows programs signed (#221), once the repository has the signing identity: the variables
# AZURE_SIGN_CLIENT_ID, AZURE_SIGN_TENANT_ID and AZURE_SIGN_SUBSCRIPTION_ID name an Azure app whose federated
# credential trusts this workflow and which holds the Artifact Signing Certificate Profile Signer role on the
# account (no secret is stored: the job's own token is exchanged). Without them the zip is unsigned, as before
- name: Sign in to Azure for signing
if: ${{ vars.AZURE_SIGN_CLIENT_ID != '' }}
uses: azure/login@v2
with:
client-id: ${{ vars.AZURE_SIGN_CLIENT_ID }}
tenant-id: ${{ vars.AZURE_SIGN_TENANT_ID }}
subscription-id: ${{ vars.AZURE_SIGN_SUBSCRIPTION_ID }}
- name: jsign (signs raea's programs)
if: ${{ vars.AZURE_SIGN_CLIENT_ID != '' }}
run: choco install jsign -y --no-progress
- name: Pack and check (tools/release.sh)
env:
RAEA_CHECK_DIR: ${{ runner.temp }}/release-check
RAEA_WIN_SIGN: ${{ vars.AZURE_SIGN_CLIENT_ID != '' && '1' || '' }}
run: bash tools/release.sh "${TAG#v}" target/dist HEAD
# live play on Windows (PT20 left it unproven): bevy-ts's play cases, `play --offscreen` with an input script and
# a snapshot's pixels probed, run by the raea just built; check.sh reads the pixels with ImageMagick, which the
-175
View File
@@ -1,175 +0,0 @@
# raea built natively for Windows on ARM (#82: a Snapdragon X runs the x64 build under emulation, and asked for its
# own). GitHub's windows-11-arm runner builds what release.yml's windows job builds, for aarch64-pc-windows-msvc, runs
# `raea --version`, packs and checks raea-VERSION-windows-arm64.zip with tools/release.sh (RAEA_WIN_ARCH=arm64)
# without drawing (RAEA_CHECK_NO_GPU=1: WARP segfaults in Bevy's compute shaders here as on x64, and Mesa's lavapipe has
# no ARM64 build; a Snapdragon PC is what draws, #82), and on a v* tag attaches it to that
# release. It runs beside release.yml, not in it, so a release never waits on or fails with the ARM64 build; a
# promoted release (release-go.sh) builds it again from the tag. install.ps1 takes it on an ARM64 PC when it's there.
name: windows-arm
on:
workflow_dispatch:
inputs:
ref:
description: "commit, branch or tag to build"
required: false
version:
description: "the version the zip is named for (raea-VERSION-windows-arm64.zip)"
required: false
push:
branches: [windows-arm64]
tags: ["v*"]
permissions:
contents: write
jobs:
build:
runs-on: windows-11-arm
timeout-minutes: 350
env:
# the release builds' compile cache (tools/release/compile-cache.sh), under this OS and architecture's own prefix
RELEASE_CACHE_ENDPOINT: ${{ secrets.RELEASE_CACHE_ENDPOINT }}
AWS_ACCESS_KEY_ID: ${{ secrets.RELEASE_CACHE_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.RELEASE_CACHE_SECRET }}
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.ref || github.sha }}
submodules: true
lfs: false
- name: Toolchain (rust-toolchain.toml's pin)
run: |
if ! command -v rustup >/dev/null; then
curl -fsSL --retry 3 -o "$RUNNER_TEMP/rustup-init.exe" https://static.rust-lang.org/rustup/dist/aarch64-pc-windows-msvc/rustup-init.exe
"$RUNNER_TEMP/rustup-init.exe" -y --default-toolchain none --profile minimal
echo "$USERPROFILE/.cargo/bin" >> "$GITHUB_PATH"
export PATH="$USERPROFILE/.cargo/bin:$PATH"
fi
rustup show active-toolchain || rustup toolchain install
rustc -vV
# ring builds its aarch64 assembly with clang (and only clang) on Windows
- name: clang (ring's assembly)
run: |
if ! command -v clang >/dev/null; then
for d in "/c/Program Files/LLVM/bin" "/c/Program Files/Microsoft Visual Studio"/*/*/VC/Tools/Llvm/ARM64/bin; do
[ -x "$d/clang.exe" ] && { echo "$d" >> "$GITHUB_PATH"; export PATH="$d:$PATH"; break; }
done
fi
command -v clang >/dev/null || { winget install -e --id LLVM.LLVM --accept-source-agreements --accept-package-agreements --silent; echo "/c/Program Files/LLVM/bin" >> "$GITHUB_PATH"; export PATH="/c/Program Files/LLVM/bin:$PATH"; }
clang --version
- name: jq that writes LF
run: |
mkdir -p "$RUNNER_TEMP/jq"
printf '#!/bin/bash\nexec "%s" -b "$@"\n' "$(command -v jq)" > "$RUNNER_TEMP/jq/jq"
chmod +x "$RUNNER_TEMP/jq/jq"
echo "$RUNNER_TEMP/jq" >> "$GITHUB_PATH"
- uses: oven-sh/setup-bun@v2
with:
bun-version: 1.4.2
- name: The runtime's packages
run: for d in sdk/react/js sdk/react/tw; do (cd "$d" && bun install --frozen-lockfile); done
# (an sccache the action can't fetch for ARM64 Windows leaves the build uncached, as compile-cache.sh does)
- name: Compile cache (sccache, as release.yml's)
if: env.AWS_ACCESS_KEY_ID != ''
continue-on-error: true
uses: mozilla-actions/[email protected]
- name: Use the compile cache
if: env.AWS_ACCESS_KEY_ID != ''
run: bash tools/release/compile-cache.sh
- name: Build
run: |
feat=$(bash tools/bevy-plugins.sh features sdk/raea/bench/bevy-plugins)
t() { s=$SECONDS; "$@"; echo "::notice::Windows ARM64 $(( (SECONDS - s) / 60 )) min: ${*:7}"; }
t cargo build --profile dist --locked -p raea-cli --bin raea --no-default-features --features "$feat"
t cargo build --profile dist --locked -p raea-rune-host
t cargo build --profile dist --locked -p raea-page-host --features window
t cargo build --profile dist --locked -p raea-perceive
- name: What raea.exe is and imports
run: |
file target/dist/raea.exe || true
dumpbin=$(ls "/c/Program Files/Microsoft Visual Studio"/*/*/VC/Tools/MSVC/*/bin/Hostarm64/arm64/dumpbin.exe 2>/dev/null | head -1)
[ -n "$dumpbin" ] && "$dumpbin" -nologo -headers -dependents target/dist/raea.exe | grep -iE 'machine|\.dll$' | sed 's/^ *//' | tee -a "$GITHUB_STEP_SUMMARY" || true
target/dist/raea.exe --version | tee -a "$GITHUB_STEP_SUMMARY"
- name: Models (pinned by URL and sha256 in tools/release/models.tsv)
run: |
while IFS=$'\t' read -r path url sha; do
case $path in ''|'#'*) continue ;; esac
mkdir -p "$HOME/.local/share/raea-models/$(dirname "$path")"
curl -fsSL "$url" -o "$HOME/.local/share/raea-models/$path"
echo "$sha $HOME/.local/share/raea-models/$path" | sha256sum -c -
done < <(tr -d '\r' < tools/release/models.tsv)
# bin\ as release.yml's windows job fills it, with the ARM64 runtime, uv and DXC (RAEA_WIN_ARCH=arm64), then the
# zip packed and checked by tools/release.sh as raea-VERSION-windows-arm64.zip. The skills gate is this commit's
# (public raea has no feed app; cli.md is still checked against this build's help); nothing is drawn
- name: Pack and check (tools/release.sh)
env:
RAEA_WIN_ARCH: arm64
RAEA_CHECK_DIR: ${{ runner.temp }}/release-check
RAEA_CHECK_NO_GPU: "1"
run: |
bash tools/release/onnxruntime.sh target/dist
bash tools/release/win-bundle.sh target/dist
v="${{ inputs.version }}"
case $GITHUB_REF in
refs/tags/v*)
v=${v:-${GITHUB_REF_NAME#v}}
# where the skills gate passed, as release.yml reads it (the tag's skills-passed line)
eval "$(GITHUB_ENV= bash tools/release/skills-passed.sh "$GITHUB_REF_NAME" | grep '^RAEA_SKILLS_PASSED=')" ;;
*) RAEA_SKILLS_PASSED=$(git rev-parse HEAD) ;;
esac
export RAEA_SKILLS_PASSED
bash tools/release.sh "${v:-0.0.0-arm64}" target/dist HEAD
# on a v* tag, beside release.yml's archives (the release made here if release.yml hasn't yet)
- name: Attach to the release
if: startsWith(github.ref, 'refs/tags/v')
env:
GH_TOKEN: ${{ github.token }}
run: |
pre=; case $GITHUB_REF_NAME in *-*) pre=--prerelease ;; esac
gh release view "$GITHUB_REF_NAME" -R "$GITHUB_REPOSITORY" >/dev/null 2>&1 ||
gh release create "$GITHUB_REF_NAME" -R "$GITHUB_REPOSITORY" $pre --title "raea ${GITHUB_REF_NAME#v}" --notes "Built by .github/workflows/release.yml; notes follow." ||
gh release view "$GITHUB_REF_NAME" -R "$GITHUB_REPOSITORY" >/dev/null
gh release upload "$GITHUB_REF_NAME" -R "$GITHUB_REPOSITORY" dist/raea-*-windows-arm64.zip dist/raea-*-windows-arm64.zip.sha256 --clobber
- uses: actions/upload-artifact@v4
if: always()
with:
name: windows-arm64-zip
path: dist/raea-*-windows-arm64.zip*
retention-days: 7
compression-level: 0
if-no-files-found: ignore
- uses: actions/upload-artifact@v4
if: always()
with:
name: windows-arm64-bins
path: |
target/dist/raea.exe
target/dist/raea_bundle.dll
target/dist/raea-rune-host.exe
target/dist/raea-page-host.exe
target/dist/raea-perceive.exe
retention-days: 7
if-no-files-found: ignore
# vendor/metis-sys's header change reaches release.yml's x64 build too (windows-latest's Visual Studio): metis-sys
# alone, in a scratch crate, compiled there
metis-x64:
runs-on: windows-latest
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.ref || github.sha }}
sparse-checkout: vendor/metis-sys
- name: metis-sys on x64 MSVC
run: |
c="$RUNNER_TEMP/metis-x64"; mkdir -p "$c/src" && : > "$c/src/lib.rs"
printf '[package]\nname = "metis-x64"\nversion = "0.0.0"\nedition = "2021"\n[dependencies]\nmetis-sys = { path = "%s" }\n[workspace]\n' "$(cygpath -m "$GITHUB_WORKSPACE/vendor/metis-sys")" > "$c/Cargo.toml"
cl 2>&1 | head -1 || true
cd "$c" && cargo build
-55
View File
@@ -1,55 +0,0 @@
# 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
+4 -66
View File
@@ -10263,6 +10263,8 @@ dependencies = [
[[package]]
name = "metis-sys"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "769ee6be814b21c52afcc631f07051f578487d642f3e89a45f2a086fd94fffa9"
dependencies = [
"cc",
]
@@ -13894,9 +13896,6 @@ dependencies = [
"raea-core-facts",
"raea-core-review",
"raea-io-home",
"raea-runtime-cut-plan",
"raea-runtime-goal-plan",
"raea-runtime-lod-plan",
"resvg 0.48.1",
"serde_json",
]
@@ -13919,7 +13918,6 @@ dependencies = [
name = "raea-app-motion"
version = "0.1.0"
dependencies = [
"glam 0.33.12",
"raea-io-home",
"raea-runtime-bundle",
"raea-sys-kimodo",
@@ -13957,18 +13955,6 @@ dependencies = [
"winit",
]
[[package]]
name = "raea-app-playable"
version = "0.1.0"
dependencies = [
"dunce",
"raea-io-home",
"raea-runtime-bundle",
"regex",
"serde_json",
"zip",
]
[[package]]
name = "raea-app-registry"
version = "0.1.0"
@@ -13990,7 +13976,6 @@ dependencies = [
"raea-core-scene",
"raea-runtime-bundle",
"raea-runtime-export",
"raea-runtime-lod-plan",
"raea-sys-contact",
"raea-sys-light-meter",
"raea-sys-stage",
@@ -14057,7 +14042,6 @@ dependencies = [
"anyhow",
"cpal 0.15.3",
"ort",
"raea-io-trace",
"raea-sys-ml",
"raea-sys-speech",
"serde_json",
@@ -14253,7 +14237,6 @@ name = "raea-bundle"
version = "0.1.0"
dependencies = [
"anyhow",
"base64 0.22.1",
"dunce",
"lightningcss",
"oxc",
@@ -14306,7 +14289,6 @@ dependencies = [
"raea-app-media",
"raea-app-notes",
"raea-app-play",
"raea-app-playable",
"raea-app-scene",
"raea-app-solid",
"raea-app-sound",
@@ -14822,9 +14804,7 @@ name = "raea-light"
version = "0.1.0"
dependencies = [
"image",
"raea-core-facts",
"raea-io-home",
"raea-io-trace",
"raea-runtime-bundle",
"serde_json",
]
@@ -15083,7 +15063,6 @@ dependencies = [
"raea-sys-engine-shaders",
"raea-sys-post",
"raea-sys-rt",
"raea-sys-viewbox",
"serde_json",
"wgpu",
]
@@ -15310,15 +15289,6 @@ dependencies = [
"raea-io-home",
]
[[package]]
name = "raea-runtime-cut-plan"
version = "0.1.0"
dependencies = [
"raea-core-brief",
"raea-io-soft",
"serde_json",
]
[[package]]
name = "raea-runtime-dom"
version = "0.1.0"
@@ -15394,7 +15364,6 @@ version = "0.1.0"
dependencies = [
"raea-core-facts",
"raea-core-scene",
"raea-runtime-lod-plan",
"raea-sys-contact",
"raea-sys-stage",
"serde_json",
@@ -15441,14 +15410,6 @@ dependencies = [
"wgpu",
]
[[package]]
name = "raea-runtime-goal-plan"
version = "0.1.0"
dependencies = [
"raea-core-brief",
"serde_json",
]
[[package]]
name = "raea-runtime-gpuframe"
version = "0.1.0"
@@ -15543,18 +15504,6 @@ 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"
@@ -16196,7 +16145,6 @@ name = "raea-sys-framepass"
version = "0.1.0"
dependencies = [
"bevy",
"raea-sys-compose",
"raea-sys-frame",
"raea-sys-material",
"raea-sys-sampler",
@@ -16451,22 +16399,11 @@ 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"
@@ -16799,7 +16736,6 @@ name = "raea-sys-viewbox"
version = "0.1.0"
dependencies = [
"bevy",
"raea-sys-compose",
"raea-sys-frame",
]
@@ -20442,6 +20378,8 @@ dependencies = [
[[package]]
name = "taffy"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c8480887e8803986d96a7173729565520d4bbb721ad6b7ad6941a22897207aa"
dependencies = [
"serde",
"slotmap",
-13
View File
@@ -86,7 +86,6 @@ members = [
"systems/tone",
"systems/mix",
"systems/mix/level",
"systems/mix/device",
"systems/ml",
"systems/mlx",
"systems/kimodo",
@@ -194,9 +193,6 @@ members = [
"runtime/canvas",
"runtime/export",
"runtime/endchecks",
"runtime/lod-plan",
"runtime/cut-plan",
"runtime/goal-plan",
"runtime/live",
"runtime/page",
"runtime/appscreen",
@@ -239,7 +235,6 @@ members = [
"apps/capcut",
"apps/layers",
"apps/play",
"apps/playable",
"tools/sdk-props",
"tools/hands-audit",
]
@@ -348,10 +343,6 @@ 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:")
@@ -408,10 +399,6 @@ 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" }
+4 -11
View File
@@ -32,10 +32,10 @@
---
> 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`.
> **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`.
## The app
@@ -80,13 +80,6 @@ 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
+3 -44
View File
@@ -55,11 +55,6 @@ 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}")
@@ -73,17 +68,6 @@ 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."
))
@@ -94,17 +78,11 @@ mod tests {
use super::*;
use serde_json::json;
/// 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 d = std::env::temp_dir().join(format!("raea-inbox-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
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");
@@ -119,25 +97,6 @@ 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"));
+1 -7
View File
@@ -148,13 +148,7 @@ 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" | "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());
}
let sent = if matches!(event, "PostToolUse" | "AfterTool" | "Stop") { crate::inbox::told(agent, &v) } else { None };
if event == "Stop" {
// what the person sent, and a `make` job that isn't done (docs/make.feature MK2): either keeps the turn going
let reasons: Vec<String> = [sent, raea_app_check_make::stop(&v)].into_iter().flatten().collect();
-50
View File
@@ -240,16 +240,6 @@ 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();
@@ -279,46 +269,6 @@ 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) {
+1 -8
View File
@@ -58,7 +58,7 @@ fn brief_of(path: Option<&str>) -> Result<Value, String> {
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let out = std::process::Command::new(exe).args(["spec", p, "--as", "brief"]).output().map_err(|e| e.to_string())?;
let text = String::from_utf8_lossy(&out.stdout);
let start = text.find('{').ok_or_else(|| format!("judge: {p} didn't read as a brief: {}", why_refused(&out)))?;
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))
}
@@ -226,10 +226,3 @@ fn finish(args: &[String], kind: Option<&str>, dir: &Path, scores: serde_json::M
#[cfg(test)]
mod tests;
/// Why `raea spec` refused a brief, in its own words: its refusal is the last line it printed, on whichever stream
/// (a REFUSED line goes to stdout, a thrown module's error to stderr). Reading stderr alone left the reason empty.
pub fn why_refused(out: &std::process::Output) -> String {
let last = |b: &[u8]| String::from_utf8_lossy(b).lines().rev().find(|l| !l.trim().is_empty()).map(|l| l.trim().trim_start_matches("REFUSED").trim().to_string());
last(&out.stderr).or_else(|| last(&out.stdout)).unwrap_or_else(|| "raea spec printed nothing".into())
}
-6
View File
@@ -11,12 +11,6 @@ description = "raea make: a scene, kit or shot held to its frozen plan; what's m
raea-core-brief = { path = "../../core/brief" }
# the project's record of renders and checks, and the folder it lives in
raea-core-facts = { path = "../../core/facts" }
# the parts a render showed closer than their planned detail (MK24)
raea-runtime-lod-plan = { path = "../../runtime/lod-plan" }
# a cut job's gates: its client's brief as rules, held over the delivered files (MK25-MK27)
raea-runtime-cut-plan = { path = "../../runtime/cut-plan" }
# a goal job's gates: its commands and a fresh critic's verdict on its words (/goal)
raea-runtime-goal-plan = { path = "../../runtime/goal-plan" }
# the judge's rounds, passes and blocking defects, read as it keeps them
raea-app-judge = { path = "../judge" }
# the make questions, their calibrations and a sheet's ident, as raea ask keeps them (MK4)
+2 -4
View File
@@ -85,7 +85,7 @@ pub fn floor_svg(m: &Make) -> Result<String, String> {
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!("<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));
}
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>";
@@ -102,10 +102,8 @@ pub fn blockout_tsx(m: &Make) -> String {
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,
" <Mesh3d 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",
at[0],
at[1] + h / 2.0,
at[2],
+4 -6
View File
@@ -19,8 +19,7 @@ use std::path::{Path, PathBuf};
use raea_core_brief::make::Make;
use serde_json::Value;
pub const USAGE: &str = "raea make status [DIR] [--json] [--plan] (a scene, kit, shot, cut or goal held to its plan, `make` on brief.ts: what's missing, each gate (renders and checks, raea ask's calibrated questions, the critic on the kind's rubric), the judge's rounds, and whether it's done, decided in code; --plan writes the gates as check lines under the job's task in plan.org; the agent's Stop hook holds it there)
raea make judge [DIR] [--by claude|kimi] (a goal job: a fresh critic, which only reads, judges each `says` rule; review/goal.judge.json)
pub const USAGE: &str = "raea make status [DIR] [--json] [--plan] (a scene, kit or shot held to its plan, `make` on brief.ts: what's missing, each gate (renders and checks, raea ask's calibrated questions, the critic on the kind's rubric), the judge's rounds, and whether it's done, decided in code; --plan writes the gates as check lines under the job's task in plan.org; the agent's Stop hook holds it there)
raea make plan [DIR] [--no-review] (the plan stop: review/plan/floor-plan.png, a grey-box blockout from the entrance and its review sheets, comparison.png beside reference 0)
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)
@@ -59,7 +58,7 @@ pub fn read_make(brief: &Path) -> Result<Option<Make>, String> {
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let out = std::process::Command::new(exe).arg("spec").arg(brief).args(["--as", "brief"]).env("RAEA_RECORD", "off").output().map_err(|e| e.to_string())?;
let text = String::from_utf8_lossy(&out.stdout);
let start = text.find('{').ok_or_else(|| format!("{} didn't read as a brief: {}", brief.display(), raea_app_judge::why_refused(&out)))?;
let start = text.find('{').ok_or_else(|| format!("{} didn't read as a brief: {}", brief.display(), String::from_utf8_lossy(&out.stderr).lines().last().unwrap_or("")))?;
let v: Value = serde_json::from_str(&text[start..]).map_err(|e| format!("{}: {e}", brief.display()))?;
let b = v.get("brief").cloned().unwrap_or(v);
match b.get("make") {
@@ -89,7 +88,7 @@ pub fn status_of(brief: &Path, make: &Make) -> Value {
let record = project.as_deref().map(raea_core_facts::record::read).unwrap_or_default();
let (rounds, verdict, judged_at) = judged(dir);
let ledger = asked::Ledger::read();
let job = status::Job { make, dir, project: project.as_deref(), record: &record, rounds: &rounds, verdict: verdict.as_ref(), judged_at, ledger: &ledger, score_gates: raea_app_judge::kind_gates(make.kind.name()) };
let job = status::Job { make, dir, project: project.as_deref(), record: &record, rounds: &rounds, verdict: verdict.as_ref(), judged_at, ledger: &ledger, score_gates: raea_app_judge::kind_gates(status::kind_name(make.kind)) };
let mut s = status::status(&job);
s["brief"] = Value::String(brief.display().to_string());
s
@@ -103,7 +102,7 @@ pub fn status_in(dir: &Path) -> Result<Option<Value>, String> {
}
/// The flags that take a value: what follows them isn't a positional argument.
const VALUED: [&str; 8] = ["--only", "--model", "--tripo", "--meshy", "--name", "--to", "--out", "--by"];
const VALUED: [&str; 7] = ["--only", "--model", "--tripo", "--meshy", "--name", "--to", "--out"];
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)
@@ -185,7 +184,6 @@ fn step(verb: &str, args: &[String]) -> Result<String, String> {
pub fn cli(args: &[String]) -> Result<String, String> {
match args.get(1).map(String::as_str) {
Some("status") => {}
Some("judge") => return job(&PathBuf::from(positional(args, 2).first().map_or(".", String::as_str))).and_then(|(b, m)| raea_runtime_goal_plan::judge(m.goal.as_ref().ok_or("raea make judge: the job isn't a goal({...})")?, b.parent().unwrap_or(Path::new(".")), flag(args, "--by").unwrap_or("claude")).map(|v| serde_json::to_string_pretty(&v).unwrap_or_default())),
Some(v @ ("plan" | "refs" | "sheet" | "gen" | "pick-sheet" | "pick" | "prep" | "kit" | "framing" | "lenschart")) => return step(v, args),
_ => return Err(USAGE.into()),
}
+16 -22
View File
@@ -1,7 +1,8 @@
//! Whether a job is done (docs/make.feature MK1), from what's on disk and nothing the agent says: the deliverables, the
//! notes, the record of renders and checks, and the judge's rounds. Pure over a `Job` so it is tested on fixtures.
use std::{path::{Path, PathBuf}, time::SystemTime};
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use raea_core_brief::make::{self, Make};
use raea_core_facts::{Level, record::Entry};
@@ -58,6 +59,14 @@ pub fn sheets(job: &Job) -> Vec<(&'static str, PathBuf)> {
out.into_iter().filter(|(_, f)| f.is_file()).collect()
}
pub(crate) fn kind_name(k: make::Kind) -> &'static str {
match k {
make::Kind::Scene => "scene",
make::Kind::Kit => "kit",
make::Kind::Shot => "shot",
}
}
/// When a file last changed, and that as seconds since 1970 (a record entry's clock).
fn mtime(p: &Path) -> Option<SystemTime> {
std::fs::metadata(p).ok()?.modified().ok()
@@ -127,22 +136,15 @@ fn checks(job: &Job) -> Vec<Value> {
.collect()
}
/// MK24: parts a composition's last render showed closer than planned, held until replanned or answered (raea-runtime-lod-plan)
fn lods(job: &Job, notes: &str) -> Vec<Value> {
let plans = job.make.objects.iter().any(|o| o.lod.is_some());
let last = |c: &String| job.record.iter().rev().find(|e| e.of == job.project.map(|p| raea_core_facts::record::rel(p, &job.dir.join(c))).unwrap_or_else(|| c.clone()));
job.make.compositions.iter().filter_map(|c| last(c).and_then(|l| raea_runtime_lod_plan::gate(c, &l.id, &l.findings, notes, plans)).map(|(clear, says)| gate("lod", Some(c), clear, says))).collect()
}
/// Tier 3: a fresh critic has judged a round newer than the newest deliverable, and each blocking defect it named is
/// fixed (the round passed) or answered in NOTES.md by its name. Its score gates once the judge is calibrated.
fn critic(job: &Job, newest: Option<SystemTime>, notes: &str) -> Vec<Value> {
let Some(last) = job.rounds.last() else {
let kind = job.make.kind.name();
let kind = kind_name(job.make.kind);
let what = match job.make.kind {
make::Kind::Kit => "raea render shared/components/KIT/lineup.tsx --review review/r1",
make::Kind::Shot => "raea make framing --out review/r1",
make::Kind::Scene | make::Kind::Cut | make::Kind::Goal => "raea render EDIT.tsx --review review/r1",
make::Kind::Scene => "raea render EDIT.tsx --review review/r1",
};
return vec![gate("critic", None, false, format!("no round yet: {what}, then raea judge review/r1 --kind {kind} --by claude --brief brief.ts"))];
};
@@ -154,7 +156,7 @@ fn critic(job: &Job, newest: Option<SystemTime>, notes: &str) -> Vec<Value> {
};
out.push(gate("critic", None, fresh, if fresh { format!("round {} judged after the newest deliverable", job.rounds.len()) } else { "the newest deliverable came after the last round: review and judge it again".into() }));
// the kind's own rubric (MK5): a round judged on another's doesn't count
let kind = job.make.kind.name();
let kind = kind_name(job.make.kind);
if last["kind"].as_str() != Some(kind) {
let dir = last["dir"].as_str().unwrap_or("review/rN");
out.push(gate("rubric", None, false, format!("the last round wasn't judged on the {kind} rubric: raea judge {dir} --kind {kind} --by claude")));
@@ -182,18 +184,11 @@ pub fn status(job: &Job) -> Value {
}
}
let notes = notes_text(job.dir).unwrap_or_default();
if job.make.kind != make::Kind::Goal && !notes.to_lowercase().contains(&SKILL_HEADING.to_lowercase()) {
if !notes.to_lowercase().contains(&SKILL_HEADING.to_lowercase()) {
missing.push(format!("NOTES.md with a \"{SKILL_HEADING}\" section (one line per thing that cost time; what the guide got wrong for this job)"));
}
let mut gates = checks(job);
gates.extend(lods(job, &notes));
// a cut job: its brief's rules over every delivered file (MK25-MK27), and the person's review its critic; a goal's
let plan = |g: make::Gate| gate(g.name, g.of.as_deref(), g.clear, g.says);
match (&job.make.cut, job.make.kind) {
(Some(c), make::Kind::Cut) => gates.extend(raea_runtime_cut_plan::gates(c, job.dir).into_iter().map(plan)),
(_, make::Kind::Goal) => gates.extend(job.make.goal.iter().flat_map(|g| raea_runtime_goal_plan::gates(g, job.dir)).map(plan)),
_ => gates.extend(critic(job, newest, &notes)),
}
gates.extend(critic(job, newest, &notes));
let (asks, said) = crate::asked::gates(&sheets(job), job.ledger, &notes);
gates.extend(asks);
let cap = job.make.rounds.unwrap_or(make::ROUNDS) as usize;
@@ -216,7 +211,6 @@ pub fn status(job: &Job) -> Value {
"gates": gates,
"judge": {"rounds": job.rounds.len(), "cap": cap, "passesInARow": advice["passesInARow"], "changeApproach": advice["stall"], "again": advice["again"]},
"plan": make::doctor(job.make),
"files": {"deliverables": make::deliverables(job.make), "previews": make::previews(job.make)},
"advice": said,
"why": why,
})
@@ -241,6 +235,6 @@ pub fn text(s: &Value) -> String {
t.push(format!(" {} {}{of}: {}", if g["clear"] == true { "ok " } else { "open" }, g["gate"].as_str().unwrap_or(""), g["says"].as_str().unwrap_or("")));
}
let j = &s["judge"];
if s["kind"] != "goal" { t.push(format!("judge: {} of {} rounds, {} passes in a row{}", j["rounds"], j["cap"], j["passesInARow"], if j["changeApproach"] == true { "; the same defect keeps coming back: change the approach for that part, not the dose" } else { "" })); }
t.push(format!("judge: {} of {} rounds, {} passes in a row{}", j["rounds"], j["cap"], j["passesInARow"], if j["changeApproach"] == true { "; the same defect keeps coming back: change the approach for that part, not the dose" } else { "" }));
t.join("\n")
}
-16
View File
@@ -134,22 +134,6 @@ fn a_composition_needs_a_clean_check_newer_than_it() {
assert!(s["gates"].to_string().contains("changed since"), "{s:#}");
}
// MK24: a part a render showed closer than planned holds the job until it's replanned or answered in the notes
#[test]
fn a_part_seen_closer_than_planned_holds_the_job() {
let d = dir("lod");
delivered(&d);
put(&d, "scene.tsx", "x");
let mut make = kit();
make.compositions = vec!["scene.tsx".into()];
let future = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() + 60;
let entry: Entry = serde_json::from_value(json!({"id": "r1", "at": future, "by": "raea render", "of": "scene.tsx", "findings": [{"check": "lod-closer", "level": "warn", "about": [{"name": "kiosk"}], "says": "'kiosk' is planned at LOD 3", "by": "raea render"}]})).unwrap();
let s = run(&make, &d, &[entry.clone()], &[round(true, 7.5, json!([]))], later());
assert!(s["done"] == false && s["gates"].to_string().contains("seen closer than planned at r1: kiosk"), "{s:#}");
put(&d, "NOTES.md", "- lod kiosk: one frame at the cut, left as a box\n## What the skill got wrong\n- nothing\n");
assert_eq!(run(&make, &d, &[entry], &[round(true, 7.5, json!([]))], later())["done"], true);
}
#[test]
fn a_scene_wants_three_stills() {
let d = dir("scene");
+1 -2
View File
@@ -156,7 +156,7 @@ fn a_shot_frames_its_start_middle_and_end() {
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": "plant", "label": "Plant", "h": 1.2, "at": [0.5, 0, 4], "source": "invented"},
{"id": "pen", "label": "Pen", "max": 0.14}]}"#)
.unwrap();
let (placed, b) = crate::floor::extent(&m);
@@ -172,7 +172,6 @@ fn the_plan_draws_a_floor_plan_and_a_blockout() {
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`"));
}
-2
View File
@@ -7,8 +7,6 @@ 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"
[dependencies]
# a take's joints as vectors (score.rs)
glam = "0.33"
# raea's models folder, where the models and the PyTorch environment go
raea-io-home = { path = "../../io/home" }
serde_json = "1"
-12
View File
@@ -1,12 +0,0 @@
//! `raea 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)
}
}
}
+19 -62
View File
@@ -9,14 +9,12 @@
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] [--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 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 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";
@@ -29,7 +27,7 @@ fn number(args: &[String], name: &str, default: f64) -> R<f64> {
}
fn line(args: &[String]) -> String {
const WITH_VALUE: [&str; 7] = ["--keys", "--seconds", "--frames", "--seed", "--seeds", "--steps", "-o"];
const WITH_VALUE: [&str; 6] = ["--keys", "--seconds", "--frames", "--seed", "--steps", "-o"];
let mut out = Vec::new();
let mut i = 1;
while i < args.len() {
@@ -52,7 +50,6 @@ struct Ask {
constraints: Option<serde_json::Value>,
frames: usize,
seed: u64,
seeds: usize,
steps: usize,
out: Option<String>,
}
@@ -67,21 +64,15 @@ 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,
};
// 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"
));
if !(2..=600).contains(&frames) {
return Err(format!("a clip is 2 to 600 frames (20 s at 30 a second), asked {frames}"));
}
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));
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") })
make(Ask { words, keys, constraints, frames, seed, steps, out: flag(args, "-o") })
}
/// -o, else a file named by the line's words in the working folder
@@ -92,25 +83,6 @@ 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;
@@ -137,17 +109,10 @@ fn make(ask: Ask) -> R<String> {
));
}
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 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 motion = decode::decode(&made.features, &stats, &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("?"));
@@ -155,28 +120,26 @@ 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 = with_score(decode::clip_json_on(&motion, &sk, seed, ask.steps, &clean, ask.constraints.is_some(), &on), &sc, ask.seeds);
let clip = decode::clip_json_on(&motion, &sk, ask.seed, ask.steps, &clean, ask.constraints.is_some(), &on);
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 = 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 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 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}; {}){report}",
"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})",
clean,
if ask.keys.is_some() { " with keys" } else { "" },
ask.frames,
ask.frames as f64 / 30.0,
seed,
if ask.seeds > 1 { format!(", the best of {} takes", ask.seeds) } else { String::new() },
ask.seed,
ask.steps,
out.display(),
f("gen_s"),
f("load_s"),
travel(&motion),
sc.as_ref().map(|s| s.line()).unwrap_or_default(),
))
}
@@ -191,29 +154,23 @@ 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 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 made = k.make(&made_from, emb.as_deref(), None).map_err(|e| format!("raea motion: {e}"))?;
let gen_s = t1.elapsed().as_secs_f64();
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 clip = raea_sys_kimodo::decode::clip_json(&made.motion, &k.skeleton, ask.seed, ask.steps, &clean, ask.constraints.is_some());
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; {}){report}",
"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)",
clean,
if ask.keys.is_some() { " with keys" } else { "" },
ask.frames,
ask.frames as f64 / 30.0,
seed,
if ask.seeds > 1 { format!(", the best of {} takes", ask.seeds) } else { String::new() },
ask.seed,
ask.steps,
out.display(),
travel(&motion),
sc.as_ref().map(|s| s.line()).unwrap_or_default(),
travel(&made.motion)
))
}
-111
View File
@@ -1,111 +0,0 @@
//! A take scored for the faults a body shows (sheet3d plan E3), so `raea motion --seeds N` can keep the best of N:
//! a foot sliding while it's planted, the shoulders shrugging up, the hips sinking, and a hand or forearm inside the
//! torso or head. Read from the take's own joints (Kimodo's SOMA skeleton, metres, Y up) and its foot contacts.
//! Collision is a skeletal proxy: capsules round the spine and a sphere for the head, sized for SOMA's average adult;
//! the mesh check on the body a clip drives is the join's (sheet3d's join.py: head-in-body frames).
use raea_sys_kimodo::decode::Motion;
use raea_sys_kimodo::skeleton::Skeleton;
use glam::Vec3;
/// each fault in centimetres (collision: the deepest a hand or forearm point goes into the torso or head), and
/// their sum, each over its own allowance: 1 cm of drift, 3 cm of shrug, 5 cm of sinking, 1 cm into the body
pub struct Score {
pub foot_drift_cm: f32,
pub shoulder_rise_cm: f32,
pub hip_drop_cm: f32,
pub collision_cm: f32,
pub total: f32,
}
fn idx(sk: &Skeleton, n: &str) -> usize {
sk.names77.iter().position(|x| x == n).unwrap_or(0)
}
/// how far p is inside the capsule a-b of radius r (0 outside)
fn inside(p: [f32; 3], a: [f32; 3], b: [f32; 3], r: f32) -> f32 {
let (p, a, b) = (Vec3::from(p), Vec3::from(a), Vec3::from(b));
let ab = b - a;
let t = ((p - a).dot(ab) / ab.length_squared().max(1e-9)).clamp(0.0, 1.0);
(r - p.distance(a + t * ab)).max(0.0)
}
fn median(mut v: Vec<f32>) -> f32 {
if v.is_empty() {
return 0.0;
}
v.sort_by(|a, b| a.total_cmp(b));
v[v.len() / 2]
}
pub fn score(m: &Motion, sk: &Skeleton) -> Score {
let j = &m.joints77;
let n = j.len();
// a foot planted: its horizontal travel over each run of contact frames, the worst run
let feet = [("LeftFoot", 0), ("LeftToeBase", 1), ("RightFoot", 3), ("RightToeBase", 4)];
let mut drift = 0f32;
for (name, c) in feet {
let k = idx(sk, name);
let mut start: Option<usize> = None;
for f in 0..=n {
let on = f < n && m.contacts[f][c];
match (on, start) {
(true, None) => start = Some(f),
(false, Some(s)) => {
let mut far = 0f32;
for g in s..f {
let d = Vec3::from(j[g][k]) - Vec3::from(j[s][k]);
far = far.max(d.x.hypot(d.z));
}
drift = drift.max(far);
start = None;
}
_ => {}
}
}
}
// shoulders above the chest: the highest against the take's own usual, both sides
let chest = idx(sk, "Chest");
let mut rise = 0f32;
for s in ["LeftShoulder", "RightShoulder"] {
let k = idx(sk, s);
let h: Vec<f32> = j.iter().map(|f| f[k][1] - f[chest][1]).collect();
let med = median(h.clone());
rise = rise.max(h.iter().fold(f32::MIN, |a, &b| a.max(b)) - med);
}
// hips below where they stand: the lowest against the first second's median
let hips = idx(sk, "Hips");
let stand = median(j.iter().take(30).map(|f| f[hips][1]).collect());
let drop = (stand - j.iter().fold(f32::MAX, |a, f| a.min(f[hips][1]))).max(0.0);
// hands and forearms against the torso (hips to chest, chest to neck) and the head
let (spine1, neck, head) = (idx(sk, "Spine1"), idx(sk, "Neck1"), idx(sk, "Head"));
let limbs: Vec<usize> = ["LeftHand", "RightHand", "LeftHandMiddle1", "RightHandMiddle1"].iter().map(|x| idx(sk, x)).collect();
let fore = [("LeftArm", "LeftForeArm", "LeftHand"), ("RightArm", "RightForeArm", "RightHand")];
let mut deep = 0f32;
for f in j {
let mut pts: Vec<[f32; 3]> = limbs.iter().map(|&k| f[k]).collect();
for (_, e, h) in fore {
let (a, b) = (f[idx(sk, e)], f[idx(sk, h)]);
pts.push([(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0, (a[2] + b[2]) / 2.0]);
}
for p in pts {
let d = inside(p, f[hips], f[spine1], 0.12)
.max(inside(p, f[spine1], f[chest], 0.13))
.max(inside(p, f[chest], f[neck], 0.11))
.max(inside(p, f[head], f[head], 0.09));
deep = deep.max(d);
}
}
let (d, r, h, c) = (drift * 100.0, rise * 100.0, drop * 100.0, deep * 100.0);
Score { foot_drift_cm: d, shoulder_rise_cm: r, hip_drop_cm: h, collision_cm: c, total: d / 1.0 + r / 3.0 + h / 5.0 + c / 1.0 }
}
impl Score {
pub fn line(&self) -> String {
format!(
"score {:.2} (foot drift {:.1} cm, shoulder rise {:.1} cm, hip drop {:.1} cm, hand into body {:.1} cm)",
self.total, self.foot_drift_cm, self.shoulder_rise_cm, self.hip_drop_cm, self.collision_cm
)
}
}
-17
View File
@@ -1,17 +0,0 @@
[package]
name = "raea-app-playable"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "`raea playable`: a raea game exported as a playable ad, one page or ZIP per ad network (docs/playables.feature)"
[dependencies]
dunce = "1"
# the game and sdk/playable's host bundled into one page by raea's own bundler (Rolldown, in process)
raea-runtime-bundle = { path = "../../runtime/bundle" }
# where raea's files are: an install's share/raea, else this checkout
raea-io-home = { path = "../../io/home" }
regex = "1"
serde_json = "1"
zip = { version = "9", default-features = false, features = ["deflate-flate2"] }
-102
View File
@@ -1,102 +0,0 @@
//! `raea playable GAME.tsx -o DIR`: a raea game exported as a playable ad (docs/playables.feature PA13). The same TSX
//! that renders with `raea render` as the video ad (it plays itself) is linted (lint.rs), bundled once with
//! sdk/playable's browser host by raea's own bundler (Rolldown, in process: minified, its pictures and tables carried
//! in the script, one three.js), and written as each network's page or ZIP (pages.rs), each checked against its cap.
mod lint;
mod pages;
use std::path::{Path, PathBuf};
type R<T> = Result<T, String>;
pub const USAGE: &str = "raea playable GAME.tsx -o DIR [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both]";
pub const ABOUT: &str = "a game as a playable ad: one page or ZIP per network (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff, preview), each under its 5 MB cap, from the TSX that renders as the video ad";
/// A path as an import specifier (no Windows verbatim prefix, which Rolldown can't open): raea-bundle's own
pub(crate) use raea_runtime_bundle::spec;
fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
}
/// The folder whose node_modules holds the three.js a playable draws with: the project's own (`raea add [email protected]`),
/// else the copy beside sdk/playable or sdk/r3f in raea's own files
fn three_dir(game: &Path, home: &Path) -> R<PathBuf> {
let mut d = game.parent();
while let Some(dir) = d {
if dir.join("node_modules/three/package.json").is_file() {
return Ok(dir.to_path_buf());
}
d = dir.parent();
}
["sdk/playable", "sdk/r3f"]
.iter()
.map(|p| home.join(p))
.find(|d| d.join("node_modules/three/package.json").is_file())
.ok_or_else(|| "a playable draws its 3D with three.js, which this project doesn't have: `raea add [email protected]` in it".into())
}
/// The game and the host in one minified script that carries its files
fn bundle(game: &Path, home: &Path) -> R<String> {
let host = home.join("sdk/playable/src/host/main.tsx");
if !host.is_file() {
return Err(format!("{}: raea's playable host isn't there", host.display()));
}
let three = three_dir(game, home)?;
let out = std::env::temp_dir().join(format!("raea-playable-{}.js", std::process::id()));
let entry = format!("import {:?};\nimport {:?};\n", spec(game), spec(&host));
let alias = format!("three/={}", three.display());
let r = raea_runtime_bundle::bundle_entry(&entry, &out, &["--minify", "1", "--inline", "1", "--alias", &alias]);
let js = r.and_then(|_| std::fs::read_to_string(&out).map_err(|e| e.to_string()));
let _ = std::fs::remove_file(&out);
js
}
pub fn cli(args: &[String]) -> R<String> {
let game = args.get(1).filter(|a| !a.starts_with('-')).ok_or(USAGE)?;
let game = dunce::canonicalize(game).map_err(|e| format!("{game}: {e}"))?;
let out = PathBuf::from(flag(args, "-o").ok_or(format!("-o DIR is required: {USAGE}"))?);
let networks: Vec<&str> = flag(args, "--networks").map(|n| n.split(',').filter(|s| !s.is_empty()).collect()).unwrap_or_else(|| pages::NETWORKS.to_vec());
if let Some(bad) = networks.iter().find(|n| !pages::NETWORKS.contains(n)) {
return Err(format!("raea playable: no network {bad} (one of {})", pages::NETWORKS.join(", ")));
}
let orientation = flag(args, "--orientation").unwrap_or("both");
if !["portrait", "landscape", "both"].contains(&orientation) {
return Err("--orientation is portrait, landscape or both".into());
}
let store = serde_json::json!({"ios": flag(args, "--ios").unwrap_or(""), "android": flag(args, "--android").unwrap_or("")}).to_string();
let card = serde_json::json!({"title": flag(args, "--title").unwrap_or(""), "cta": flag(args, "--cta").unwrap_or("Play now")}).to_string();
let name = game.file_stem().and_then(|s| s.to_str()).unwrap_or("playable").to_string();
let mut report = Vec::new();
let found = lint::lint(&game)?;
report.push(format!("3D kinds: {}", if found.kinds.is_empty() { "none".into() } else { found.kinds.join(", ") }));
for c in &found.comps {
let shape = if c.height > c.width { "portrait" } else { "landscape" };
report.push(format!("composition {}: {}x{} {shape}, {} fps, {:.0} s", c.id, c.width, c.height, c.fps, c.frames as f64 / c.fps.max(1.0)));
}
report.extend(found.notes.iter().map(|n| format!("note: {n}")));
if !found.refusals.is_empty() {
// the reasons first: the CLI marks an error's first line REFUSED
let mut why = found.refusals.clone();
why.extend(report);
return Err(why.join("\n"));
}
let js = bundle(&game, &raea_io_home::home())?;
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
let mut over = false;
for net in networks {
let script = format!("{}\n{js}", pages::preamble(net, &store, &card));
let w = pages::write(net, &name, &script, &out, orientation)?;
let ok = w.bytes <= pages::CAP;
over |= !ok;
report.push(format!("{:<10} {:<40} {:>6} KB / {} KB {}", w.network, w.file.display(), w.bytes / 1024, pages::CAP / 1024, if ok { "ok" } else { "OVER" }));
}
if over {
report.insert(0, format!("a page is over its network's {} KB cap", pages::CAP / 1024));
return Err(report.join("\n"));
}
report.push(format!("APPLIED {name} exported as a playable to {}", out.display()));
Ok(report.join("\n"))
}
-104
View File
@@ -1,104 +0,0 @@
//! What a playable can't have, refused before it is bundled (docs/playables.feature PA4): the source read for files
//! from disk, the network and the native engine's modules; the compositions rendered (sdk/playable/src/export/walk.ts,
//! through `raea run` in a process of its own) for their shapes and the 3D kinds the host doesn't draw.
use super::R;
use serde_json::Value;
use std::path::Path;
/// One composition the game registers
pub struct Comp {
pub id: String,
pub width: u32,
pub height: u32,
pub fps: f64,
pub frames: u64,
}
/// What the lint found: refusals stop the export, notes don't
pub struct Found {
pub comps: Vec<Comp>,
pub kinds: Vec<String>,
pub notes: Vec<String>,
pub refusals: Vec<String>,
}
const SOURCE_RULES: &[(&str, &str)] = &[
(r"\bstaticFile\s*\(", "staticFile() reads the edit's folder at render time; import the file instead (`import icon from \"./icon.png\"`), which the export carries in the page"),
(r"https?://", "a URL in the source: a playable makes no network requests (every network refuses one)"),
(r"\bfetch\s*\(|XMLHttpRequest|WebSocket", "fetch/XHR/WebSocket: a playable makes no network requests"),
(r#"from\s+["']raea/(native|ml|character|physics|media|matchmove|modelling)["']"#, "a module that needs the native engine (native calls, models, physics, footage)"),
(r"<(Video|Audio)\b", "<Video>/<Audio> play through the native media stack; a playable's sound is PA6 (not yet)"),
];
/// The game's source and its compositions, judged
pub fn lint(game: &Path) -> R<Found> {
let src = std::fs::read_to_string(game).map_err(|e| format!("{}: {e}", game.display()))?;
let mut refusals = Vec::new();
let mut notes = Vec::new();
// a URL the SVG namespace names is a name, not a request
let src_no_ns = src.replace("http://www.w3.org", "");
for (re, why) in SOURCE_RULES {
if regex::Regex::new(re).map_err(|e| e.to_string())?.is_match(&src_no_ns) {
refusals.push(why.to_string());
}
}
if !src.contains("raea/playable") {
notes.push("no raea/playable import: the game never opens the store itself (add an <EndCard> or <InstallButton>); the host's own end card shows at the last frame".into());
}
let walked = match walk(game) {
Ok(w) => w,
// what the source can't have (a fetch, a URL) often stops the render too: the refusal says why, the render's end doesn't
Err(_) if !refusals.is_empty() => return Ok(Found { comps: vec![], kinds: vec![], notes, refusals }),
Err(e) => return Err(e),
};
let comps: Vec<Comp> = walked["comps"]
.as_array()
.into_iter()
.flatten()
.map(|c| Comp {
id: c["id"].as_str().unwrap_or("").into(),
width: c["width"].as_u64().unwrap_or(0) as u32,
height: c["height"].as_u64().unwrap_or(0) as u32,
fps: c["fps"].as_f64().unwrap_or(30.0),
frames: c["frames"].as_u64().unwrap_or(0),
})
.collect();
let strings = |k: &str| walked[k].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(String::from)).collect::<Vec<_>>();
if comps.is_empty() {
refusals.push("no composition registered (registerRoot)".into());
}
if comps.len() == 1 {
notes.push("one composition: the other orientation is letterboxed (Unity, AppLovin, Moloco and Mintegral want both; register a second one at the other shape)".into());
}
for k in strings("refused") {
refusals.push(format!("3D kind {k} isn't drawn in a playable"));
}
Ok(Found { comps, kinds: strings("kinds"), notes, refusals })
}
/// sdk/playable's walk run on the engine (`raea run`) after the game, in a process of its own so the game's React stays
/// out of this one; its answer is the JSON it prints
fn walk(game: &Path) -> R<Value> {
let walk = raea_io_home::home().join("sdk/playable/src/export/walk.ts");
if !walk.is_file() {
return Err(format!("{}: raea's playable SDK isn't there", walk.display()));
}
let work = std::env::temp_dir().join(format!("raea-playable-lint-{}", std::process::id()));
std::fs::create_dir_all(&work).map_err(|e| e.to_string())?;
let entry = work.join("lint.ts");
std::fs::write(&entry, format!("import {:?};\nexport {{ default }} from {:?};\n", super::spec(game), super::spec(&walk))).map_err(|e| e.to_string())?;
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let run = std::process::Command::new(exe).arg("run").arg(&entry).output().map_err(|e| format!("raea run: {e}"));
let _ = std::fs::remove_dir_all(&work);
let run = run?;
let out = String::from_utf8_lossy(&run.stdout);
if !run.status.success() {
let err = String::from_utf8_lossy(&run.stderr);
let said: Vec<&str> = err.lines().chain(out.lines()).filter(|l| !l.trim().is_empty()).collect();
// the line that names the error, else the last one ("… ended with exit 1" says nothing)
let why = said.iter().find(|l| l.contains("Error") || l.contains("error:")).or(said.last()).unwrap_or(&"").trim().to_string();
return Err(format!("the game didn't render for the lint: {why}"));
}
let at = out.find('{').ok_or("the lint's walk printed no answer")?;
serde_json::from_str(&out[at..]).map_err(|e| format!("the lint's walk: {e}"))
}
-100
View File
@@ -1,100 +0,0 @@
//! Each network's package around the one script (docs/playables.feature, the Background's table): the page every
//! network gets, with that network's own tags, as one HTML file or a ZIP, checked against its cap.
use super::R;
use std::io::Write;
use std::path::{Path, PathBuf};
pub const NETWORKS: &[&str] = &["applovin", "unity", "google", "meta", "moloco", "mintegral", "tiktok", "liftoff", "preview"];
/// Every network's cap, 5 MB (TikTok's counted zipped, which is what's written)
pub const CAP: u64 = 5 * 1024 * 1024;
/// What one network got: the file and its size
pub struct Written {
pub network: String,
pub file: PathBuf,
pub bytes: u64,
}
/// The settings a page starts with, as the globals the host reads (sdk/playable network.ts, host/main.tsx): the network,
/// the store links, the end card's words
pub fn preamble(network: &str, store: &str, card: &str) -> String {
format!("var __RAEA_NETWORK__={},__RAEA_STORE__={store},__RAEA_PLAYABLE__={card};", serde_json::to_string(network).unwrap_or_default())
}
/// The page: the network's head and body tags, then the script (a page's inline script ends at the first "</script")
pub fn page(title: &str, head: &str, body: &str, script: &str) -> String {
let title = title.replace('&', "&amp;").replace('<', "&lt;");
format!(
"<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover\">\n<title>{title}</title>\n{head}\n</head>\n<body>\n{body}\n<script>\n{}\n</script>\n</body>\n</html>\n",
script.replace("</script", "<\\/script")
)
}
fn zip(file: &Path, entries: &[(String, String)]) -> R<()> {
let f = std::fs::File::create(file).map_err(|e| format!("{}: {e}", file.display()))?;
let mut w = zip::ZipWriter::new(f);
let o = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
for (name, text) in entries {
w.start_file(name.as_str(), o).map_err(|e| e.to_string())?;
w.write_all(text.as_bytes()).map_err(|e| e.to_string())?;
}
w.finish().map_err(|e| e.to_string())?;
Ok(())
}
/// `network`'s package of `script` (its preamble already first) written into `out` as NAME-NETWORK.html or .zip
pub fn write(network: &str, name: &str, script: &str, out: &Path, orientation: &str) -> R<Written> {
let html = |head: &str, body: &str| page(name, head, body, script);
let file = match network {
// a ZIP with index.html; exitapi.js and the orientation tag in the head (Google Ads help 9981650)
"google" => {
let o = if orientation == "both" { "portrait,landscape" } else { orientation };
let head = format!("<meta name=\"ad.orientation\" content=\"{o}\">\n<script type=\"text/javascript\" src=\"https://tpc.googlesyndication.com/pagead/gadgets/html5/api/exitapi.js\"></script>");
let f = out.join(format!("{name}-google.zip"));
zip(&f, &[("index.html".into(), html(&head, ""))])?;
f
}
// a ZIP with index.html and config.json; TikTok's playable SDK before the game's script (TikTok Ads help)
"tiktok" => {
let o = match orientation {
"portrait" => 1,
"landscape" => 2,
_ => 0,
};
let body = "<script src=\"https://sf16-muse-va.ibytedtos.com/obj/union-fe-nc-i18n/playable/sdk/playable-sdk.js\"></script>";
let f = out.join(format!("{name}-tiktok.zip"));
zip(&f, &[("index.html".into(), html("", body)), ("config.json".into(), format!("{{\"playable_orientation\": {o}}}\n"))])?;
f
}
// a ZIP holding a folder and a page of the same name
"mintegral" => {
let f = out.join(format!("{name}-mintegral.zip"));
zip(&f, &[(format!("{name}/{name}.html"), html("", ""))])?;
f
}
// one HTML file, everything inlined; MRAID is injected by the network's webview (Meta: data URIs only)
"applovin" | "unity" | "meta" | "moloco" | "liftoff" | "preview" => {
let f = out.join(format!("{name}-{network}.html"));
std::fs::write(&f, html("", "")).map_err(|e| format!("{}: {e}", f.display()))?;
f
}
other => return Err(format!("raea playable: no network {other} (one of {})", NETWORKS.join(", "))),
};
let bytes = std::fs::metadata(&file).map(|m| m.len()).unwrap_or(0);
Ok(Written { network: network.into(), file, bytes })
}
#[cfg(test)]
mod tests {
#[test]
fn a_script_cannot_end_its_page_early() {
let p = super::page("t", "", "", "a('</script>')");
assert_eq!(p.matches("</script").count(), 1, "{p}");
}
#[test]
fn the_preamble_names_the_network_as_a_string() {
assert_eq!(super::preamble("applovin", "{}", "{}"), "var __RAEA_NETWORK__=\"applovin\",__RAEA_STORE__={},__RAEA_PLAYABLE__={};");
}
}
+1 -3
View File
@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "raea scene lint|explain|light|stage|lod: a composition's frames stepped without drawing and held to the contact, light and stage checks"
description = "raea scene lint|explain|light|stage: a composition's frames stepped without drawing and held to the contact, light and stage checks"
[dependencies]
raea-runtime-bundle = { path = "../../runtime/bundle" }
@@ -12,8 +12,6 @@ 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" }
# 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
+3 -7
View File
@@ -1,7 +1,6 @@
//! `raea scene lint|explain|light|stage|lod`: a composition's frames stepped without drawing and handed to raea-sys-contact
//! `raea scene lint|explain|light|stage`: a composition's frames stepped without drawing and handed to raea-sys-contact
//! (what each part rests on, and parts that clip), raea-sys-light-meter (the light on a subject) and raea-sys-stage (3D
//! type that can't be read, parts that snap, a camera that lurches, empty frames: docs/stage-guards.feature). `lod` is
//! each part's planned detail beside how large the frames show it (docs/make.feature MK23).
//! type that can't be read, parts that snap, a camera that lurches, empty frames: docs/stage-guards.feature).
use serde_json::json;
@@ -11,11 +10,9 @@ use raea_runtime_export::{frame_of, items};
// how near the camera passes to each solid part, every frame (`--clearance M`, MK16)
pub mod clearance;
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|lod EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--json]";
pub const USAGE: &str = "raea scene lint|explain|light|stage EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--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,
@@ -27,7 +24,6 @@ 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),
"lint" | "explain" => {}
_ => return Err(usage.into()),
}
-37
View File
@@ -1,37 +0,0 @@
//! `raea scene lod EDIT.tsx [--composition ID] [--from N] [--to N] [--json]` (docs/make.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)
}
+6 -23
View File
@@ -1,7 +1,7 @@
//! `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, 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
//! them. 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).
@@ -12,16 +12,8 @@ use raea_core_facts::{Level, finding};
use raea_runtime_bundle::{bundle_composition, comp_opts, flag};
use raea_runtime_export::{all_items, scene_frames_to};
/// 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> {
pub(crate) fn cli(args: &[String]) -> Result<String, String> {
let usage = "raea scene stage EDIT.tsx [--composition ID] [--from N] [--to N] [--clearance M] [--json]";
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();
@@ -33,19 +25,10 @@ pub(crate) fn stepped(args: &[String], usage: &str) -> Result<Stepped, 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();
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 (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 items = all_items(&frames);
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:?}"))?;
+3 -9
View File
@@ -21,10 +21,8 @@ struct Hook {
fn hooks(agent: &str) -> R<Vec<Hook>> {
let h = |event, matcher, secs| Hook { event, matcher, secs };
Ok(match agent {
// 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)],
"claude" => vec![h("PreToolUse", "Bash", 30), h("PostToolUse", "*", 60), h("Stop", "", 30)],
"codex" => vec![h("PreToolUse", "^(Bash|shell|shell_command|exec_command)$", 30), h("PostToolUse", "^(apply_patch|Edit|Write)$", 60)],
"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")),
@@ -126,8 +124,7 @@ 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, 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());
let [pre, post, stop] = <[Hook; 3]>::try_from(hooks("claude").unwrap()).ok().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());
@@ -136,9 +133,6 @@ 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
View File
@@ -12,7 +12,6 @@ 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" }
+42 -2
View File
@@ -108,7 +108,7 @@ pub fn microphone(tx: Sender<Vec<f32>>) -> anyhow::Result<cpal::Stream> {
rs.push(&mono, &mut out);
let _ = tx.send(out);
};
let bad = raea_io_trace::once::said_once::<cpal::StreamError>("raea voice: the microphone");
let bad = 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)
@@ -242,7 +242,7 @@ impl Speaker {
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}"))?;
let stream = dev.build_output_stream(&cfg.config(), play, 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) })
}
@@ -286,3 +286,43 @@ mod tests {
assert!(x.iter().zip(&y).all(|(a, b)| (a - b).abs() < 1e-3));
}
}
/// A device's error said once, then only how often it came back (at its 10th, 100th, ... time, and never more than once
/// a second): a failing ALSA device calls a stream's error callback without pause, and every call printed a line: #239's
/// app.log reached 40 GB of one line in two days.
fn said_once<E: std::fmt::Display>(what: &'static str) -> impl FnMut(E) + Send + 'static {
let mut seen = Repeats::default();
move |e| {
let m = e.to_string();
match seen.hit(&m, std::time::Instant::now()) {
Some(1) => eprintln!("{what}: {m}"),
Some(n) => eprintln!("{what}: {m} ({n} times now)"),
None => {}
}
}
}
/// Which of an error's repeats get said: `hit` answers with the count to print, or nothing.
#[derive(Default)]
struct Repeats {
last: String,
n: u64,
next: u64,
at: Option<std::time::Instant>,
}
impl Repeats {
fn hit(&mut self, m: &str, now: std::time::Instant) -> Option<u64> {
if m != self.last || self.n == 0 {
(self.last, self.n, self.next) = (m.to_string(), 0, 1);
}
self.n += 1;
let soon = self.at.is_some_and(|t| now.duration_since(t).as_secs() < 1);
if self.n < self.next || (soon && self.n > 1) {
return None;
}
self.next = self.n.saturating_mul(10);
self.at = Some(now);
Some(self.n)
}
}
+1 -1
View File
@@ -16,7 +16,7 @@ mkdir -p "$OUT"
export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
expected() { case $1 in
examples/games/animated-character.tsx) echo "its media/RobotExpressive.glb was deleted" ;;
examples/playables/brick-rush.tsx) echo "RAEA_LIVE3D_CHECK panics on frame 1: the fast rows carry the sun's rotation and the full rows don't (runtime/scene/src/live.rs; docs/playables.feature PA18)" ;;
examples/playables/brick-rush.tsx) echo "a playable: it needs the playable host's raea_playable (sdk/playable)" ;;
sdk/raea/bench/bevy-parity/3d/rotate_environment_map.tsx) echo "clearcoat textures need raea-sys-material's multi-layer feature, off by default (as bench/bevy-parity/runs.tsv leaves it out)" ;;
esac; }
SAME=0 DIFF=0 ERR=0 SKIP=0
-30
View File
@@ -1,30 +0,0 @@
#!/bin/bash
# Two paint bugs, each held to what Chrome draws. Exits 1 on a failure.
# #241 z.html: a stacking context's z-index: -1 child goes under its text. White pixels (the word) must be there:
# before the fix the box covered the word and the frame had none.
# #240 miter.html: a stroked rounded rect under a negative viewBox origin. Nothing blue left of the outline (x 0-60,
# y 84-130: the outline starts at x 92), and the outline's top-left corner is round (dark at its square corner).
# bench/paint-order/check.sh (RAEA_BIN: the raea to run, default target/release/raea)
cd "$(dirname "$0")/../.." || exit 2
BIN=${RAEA_BIN:-$PWD/target/release/raea}
export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
OUT=$(mktemp -d "${TMPDIR:-/tmp}/raea-paint-order.XXXXXX")
trap 'rm -rf "${OUT:?}"' EXIT
status=0
for p in z miter; do
"$BIN" render "bench/paint-order/$p.html" -o "$OUT/$p.png" > "$OUT/$p.log" 2>&1 || { echo "FAIL render $p (log below)"; sed 's/^/ /' "$OUT/$p.log"; exit 1; }
done
# how many pixels of a region are near a colour
count() { magick "$OUT/$1.png" -alpha off -crop "$2" +repage -fuzz "${4:-6}%" -fill black +opaque "$3" -fill white -opaque "$3" -colorspace Gray -format "%[fx:int(mean*w*h+0.5)]" info:; }
white=$(count z 600x300+0+0 "#ffffff")
(( white > 2000 )) || { echo "FAIL #241: $white white pixels, the word is under its z-index: -1 child"; status=1; }
box=$(count z 600x300+0+0 "#10203C" 3)
(( box > 3000 )) || { echo "FAIL #241: $box pixels of the box behind the word"; status=1; }
bar=$(count miter 60x46+0+84 "#3c82f0")
(( bar == 0 )) || { echo "FAIL #240: $bar blue pixels left of the outline (the miter join's bar)"; status=1; }
corner=$(count miter 6x6+91+99 "#3c82f0")
(( corner == 0 )) || { echo "FAIL #240: the outline's top-left corner is square ($corner blue pixels at its corner)"; status=1; }
edge=$(count miter 200x6+400+97 "#3c82f0")
(( edge > 300 )) || { echo "FAIL #240: the outline's top edge isn't drawn ($edge pixels)"; status=1; }
[ $status = 0 ] && echo "PASS paint order: #241 text over a negative z-index child, #240 a miter join after an arc"
exit $status
-7
View File
@@ -1,7 +0,0 @@
<!doctype html>
<!-- #240: a thin rounded outline, nothing left of it (896 wide under a viewBox that starts at -20 drew a bar from x=0) -->
<html><body style="margin:0;background:#111">
<div data-composition-id="main" data-start="0" data-duration="1" data-width="1080" data-height="600" style="position:relative;width:1080px;height:600px;background:#111">
<svg width="936" height="440" viewBox="-20 -20 936 440" style="position:absolute;left:72px;top:80px"><rect x="0" y="0" width="896" height="400" rx="24" fill="none" stroke="#3c82f0" stroke-width="3"/></svg>
</div>
</body></html>
-7
View File
@@ -1,7 +0,0 @@
<!doctype html>
<!-- #241: white "Hollow" over a blue box that is its own z-index: -1 child -->
<html><body style="margin:0;background:#111">
<div data-composition-id="main" data-start="0" data-duration="1" data-width="600" data-height="300" style="position:relative;width:600px;height:300px;background:#111;display:flex;align-items:center;justify-content:center">
<span style="position:relative;display:inline-block;z-index:1;color:#fff;font:700 80px sans-serif"><div style="position:absolute;inset:0;z-index:-1;background:#10203C;border:3px solid #3474D6"></div>Hollow</span>
</div>
</body></html>
-242
View File
@@ -1,242 +0,0 @@
//! A cut job's contract (docs/make.feature MK25): `make: cut({...})` on brief.ts, the client's brief made into rules
//! before anything is planned or cut. A brief read as context gets lost (11-25, Shane, on StreetTalk's street interview
//! ads: "you need to make the process of ingesting the brief more direct, or else it's just context that gets lost. It
//! needs to be written as a brief typescript rule that is then enforced"). Every rule quotes the brief line it came
//! from (`from`), and `raea make status` (apps/make cut.rs) finds each quote in the brief's text, so a rule can't be
//! invented and a brief line can't drift; then it holds every delivered file to the rules, from what's on disk.
use serde::{Deserialize, Serialize};
use ts_rs::TS;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "MakeCut")]
pub struct Cut {
/// the brief as text, relative to brief.ts (`pdftotext -layout brief.pdf media/brief.txt`): every `from` is found in it
pub brief: String,
/// how many cuts the brief asks for; fewer planned is held open until an answered `open` item about "count" says why
pub count: Option<Quoted<u32>>,
/// a cut's length when its own `seconds` says none: [least, most]
pub seconds: Option<[f64; 2]>,
/// the formats every cut is delivered in when its own `formats` says none: "9:16", "16:9", "1:1", "4:5"
#[serde(default)]
#[ts(as = "Option<Vec<String>>", optional)]
pub formats: Vec<String>,
#[serde(default)]
#[ts(as = "Option<Vec<CutPlan>>", optional)]
pub cuts: Vec<CutPlan>,
/// what is said or shown: in every cut unless `every: false` (then in one or more)
#[serde(default)]
#[ts(as = "Option<Vec<Phrase>>", optional)]
pub say: Vec<Phrase>,
/// what no cut says or shows: a banned claim, a word, a name
#[serde(default)]
#[ts(as = "Option<Vec<Phrase>>", optional)]
pub never: Vec<Phrase>,
/// the line every cut ends on, heard or on screen in its last `within` seconds
pub cta: Option<Cta>,
/// the brief's open items ([TO CONFIRM]): each holds the job open until it has an answer
#[serde(default)]
#[ts(as = "Option<Vec<Open>>", optional)]
pub open: Vec<Open>,
/// every face whole and every text big enough, by the frames check of each file (true when left out)
pub frames: Option<bool>,
}
/// A value with the brief's words for it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(deny_unknown_fields)]
#[ts(rename = "MakeQuoted")]
pub struct Quoted<T: TS> {
pub value: T,
/// the brief's own words, as they are in its text
pub from: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "MakeCutPlan")]
pub struct CutPlan {
/// [a-z0-9_], unique: each format lands as out/cuts/<id>_<W>x<H>.mp4 ("a1_s1_9x16.mp4")
pub id: String,
pub angle: Option<String>,
/// solo or mashup
pub kind: Option<String>,
/// one of the brief's hook types ("Direct Problem", "Reaction")
pub hook: Option<String>,
/// captions, hook (a text hook) or none
pub text: Option<String>,
#[serde(default)]
#[ts(as = "Option<Vec<String>>", optional)]
pub formats: Vec<String>,
pub seconds: Option<[f64; 2]>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "MakePhrase")]
pub struct Phrase {
/// as it's said or shown; compared in lower case, by letters and digits ("24/7" and "24-7" are the same)
pub text: String,
pub from: String,
/// `say` only: false when one cut saying it is enough
pub every: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "MakeCta")]
pub struct Cta {
pub text: String,
pub from: String,
/// the other lines a brief rotates (two host lines, a paid take's): any one lands it, each found in the brief
#[serde(default)]
#[ts(as = "Option<Vec<String>>", optional)]
pub also: Vec<String>,
/// how near the end it must land, in seconds (8 when left out)
pub within: Option<f64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "MakeOpen")]
pub struct Open {
pub question: String,
pub from: String,
/// what it decides: "count", "cta", "offer", a cut's id...
pub about: Option<String>,
/// the person's answer, as they gave it, and who gave it: until then the job can't be done
pub answer: Option<String>,
pub by: Option<String>,
}
/// How near the end the CTA lands when the contract says nothing.
pub const CTA_WITHIN: f64 = 8.0;
/// A format's frame shape, "9:16" -> (9, 16).
pub fn ratio(f: &str) -> Option<(u32, u32)> {
let (w, h) = f.split_once(':')?;
Some((w.trim().parse().ok().filter(|&w| w > 0)?, h.trim().parse().ok().filter(|&h| h > 0)?))
}
/// A cut's formats and its length: its own, else the contract's.
pub fn formats<'a>(c: &'a Cut, p: &'a CutPlan) -> &'a [String] {
if p.formats.is_empty() { &c.formats } else { &p.formats }
}
pub fn seconds(c: &Cut, p: &CutPlan) -> Option<[f64; 2]> {
p.seconds.or(c.seconds)
}
/// Where a cut's format lands, relative to the brief: out/cuts/a1_s1_9x16.mp4.
pub fn file(p: &CutPlan, format: &str) -> String {
format!("out/cuts/{}_{}.mp4", p.id, format.replace(':', "x"))
}
/// Every file the contract asks for.
pub fn deliverables(c: &Cut) -> Vec<String> {
c.cuts.iter().flat_map(|p| formats(c, p).iter().map(move |f| file(p, f))).collect()
}
/// Every `from` in the contract, with what it backs: the quotes `raea make status` finds in the brief's text.
pub fn quotes(c: &Cut) -> Vec<(String, &str)> {
let mut q: Vec<(String, &str)> = Vec::new();
if let Some(n) = &c.count {
q.push(("count".into(), &n.from));
}
for (what, list) in [("say", &c.say), ("never", &c.never)] {
for p in list {
q.push((format!("{what} \"{}\"", p.text), &p.from));
}
}
if let Some(cta) = &c.cta {
q.push(("cta".into(), &cta.from));
for line in &cta.also {
q.push((format!("cta \"{line}\""), line));
}
}
for o in &c.open {
q.push((format!("open \"{}\"", o.question), &o.from));
}
q
}
/// What the contract lacks before it can be cut against, each with what to do.
pub fn doctor(c: &Cut) -> Vec<String> {
let mut out = Vec::new();
if c.brief.trim().is_empty() {
out.push("no `brief`: the brief as text beside brief.ts (pdftotext -layout BRIEF.pdf media/brief.txt), which every `from` quotes".into());
}
if c.cuts.is_empty() {
out.push("no cuts: list every cut the brief asks for, with its id, angle, hook and formats".into());
}
if c.count.is_none() {
out.push("no `count`: how many cuts the brief asks for, with its words".into());
}
if c.cta.is_none() {
out.push("no `cta`: the line the brief says every cut ends on (or an `open` item asking for it)".into());
}
let mut seen = std::collections::BTreeSet::new();
for p in &c.cuts {
if !seen.insert(p.id.as_str()) {
out.push(format!("cut `{}` is listed twice", p.id));
}
if !crate::make::is_name(&p.id) {
out.push(format!("cut `{}`: ids are [a-z0-9_], the file it lands as", p.id));
}
let fs = formats(c, p);
if fs.is_empty() {
out.push(format!("cut `{}` has no formats: give it `formats`, or the contract's", p.id));
}
for f in fs.iter().filter(|f| ratio(f).is_none()) {
out.push(format!("cut `{}`: format `{f}` isn't W:H (\"9:16\", \"16:9\", \"1:1\", \"4:5\")", p.id));
}
match seconds(c, p) {
None => out.push(format!("cut `{}` has no length: `seconds: [least, most]`, its own or the contract's", p.id)),
Some([a, b]) if !(a > 0.0 && a <= b) => out.push(format!("cut `{}`: seconds [{a}, {b}] isn't [least, most]", p.id)),
_ => {}
}
if let Some(t) = &p.text
&& !matches!(t.as_str(), "captions" | "hook" | "none")
{
out.push(format!("cut `{}`: text is captions, hook or none, not `{t}`", p.id));
}
}
for (what, from) in quotes(c) {
if from.trim().is_empty() {
out.push(format!("{what} has no `from`: the brief's own words for it"));
}
}
for p in c.say.iter().chain(&c.never) {
if norm(&p.text).is_empty() {
out.push(format!("phrase `{}` has no letters or digits to find", p.text));
}
}
out
}
/// Text as it's compared: lower case, letters and digits, one space between words ("24/7" -> "24 7").
pub fn norm(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut gap = false;
for ch in s.chars().flat_map(char::to_lowercase) {
// a curly apostrophe or a plain one joins its word ("it's" is one word, "its" is another)
if ch == '\'' || ch == '\u{2019}' {
continue;
}
if ch.is_alphanumeric() {
if gap && !out.is_empty() {
out.push(' ');
}
gap = false;
out.push(ch);
} else {
gap = true;
}
}
out
}
-67
View File
@@ -1,67 +0,0 @@
//! A goal job's contract: `make: goal({...})` on brief.ts, the person's goal written as rules before the work starts
//! (11-26, Shane: "we essentially just need to make sure that it can't stop unless all the goals pass, or all the rules
//! in the brief"). `/goal` in raea.app and an agent's own goal are this: the goal in the person's words, then each
//! thing that must hold, as a command that must pass, a file that must exist, or words a fresh critic must find true.
//! `raea make status` (runtime/goal-plan) decides from them whether the agent may stop; the agent saying so never does.
use serde::{Deserialize, Serialize};
use ts_rs::TS;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "MakeGoal")]
pub struct Goal {
/// the goal as the person said it
pub goal: String,
/// what must hold before the agent may stop: every one, each checked in code or by a fresh critic
#[serde(default)]
#[ts(as = "Option<Vec<GoalRule>>", optional)]
pub rules: Vec<GoalRule>,
}
/// One thing that must hold. Exactly one of `run`, `file` or `says`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "MakeGoalRule")]
pub struct GoalRule {
/// a short name: [a-z0-9_], how status, the critic and NOTES.md name it
pub id: String,
/// a command that must exit 0, run in the brief's folder (`bun test`, `raea check edit.tsx`)
pub run: Option<String>,
/// the seconds `run` gets before it counts as failed (300 when left out)
pub timeout: Option<u32>,
/// a file that must exist, relative to the brief (`a|b`: either; `dir/`: three or more pictures in it)
pub file: Option<String>,
/// words that must be true of the work, judged by a fresh critic (`raea make judge`), never by the agent that did it
pub says: Option<String>,
}
/// What the goal's rules still lack, each with what to do. Empty when it's ready.
pub fn doctor(g: &Goal) -> Vec<String> {
let mut out = Vec::new();
if g.goal.trim().is_empty() {
out.push("no `goal`: the goal in the person's own words".into());
}
if g.rules.is_empty() {
out.push("no `rules`: what must hold before you stop, each a `run` command, a `file` or words a critic judges (`says`)".into());
}
let mut seen = std::collections::BTreeSet::new();
for r in &g.rules {
if !crate::make::is_name(&r.id) {
out.push(format!("rule `{}`: ids are [a-z0-9_]", r.id));
}
if !seen.insert(r.id.as_str()) {
out.push(format!("rule `{}` is listed twice", r.id));
}
let n = [r.run.is_some(), r.file.is_some(), r.says.is_some()].iter().filter(|x| **x).count();
if n != 1 {
out.push(format!("rule `{}` needs exactly one of `run`, `file` or `says` (it has {n})", r.id));
}
if r.timeout.is_some() && r.run.is_none() {
out.push(format!("rule `{}` has a `timeout` but no `run`", r.id));
}
}
out
}
-4
View File
@@ -4,8 +4,6 @@
//! types (`declarations`), so what tsc checks is exactly what this crate reads.
pub mod brief;
pub mod cut;
pub mod goal;
pub mod make;
pub mod parts;
pub mod script;
@@ -41,8 +39,6 @@ pub fn declarations() -> String {
taste::Taste, taste::TasteSection, taste::Rule, taste::RuleCheck, taste::RuleLevel, taste::Check,
parts::Parts, parts::Concept, parts::Level, parts::Count, parts::Part,
make::Make, make::Kind, make::Source, make::DialValue, make::Dial, make::Route, make::Origin, make::Pick, make::Object, make::Shot,
cut::Cut, cut::Quoted<u32>, cut::CutPlan, cut::Phrase, cut::Cta, cut::Open,
goal::Goal, goal::GoalRule,
));
out.join("\n\n") + "\n"
}
+1 -66
View File
@@ -19,10 +19,6 @@ pub enum Kind {
Kit,
/// stills or camera moves of a built scene, from words
Shot,
/// ads cut from footage to a client's brief: its deliverables, phrases, claims and CTA as rules (cut.rs, MK25)
Cut,
/// any other work held to a goal: commands that must pass, files that must exist, words a critic judges (goal.rs)
Goal,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
@@ -56,15 +52,6 @@ pub struct Make {
pub deliverables: Vec<String>,
/// the most critic rounds the job gets; at the cap it is delivered with what's still missing (8 by default)
pub rounds: Option<u32>,
/// a cut job's contract: the brief as rules (cut.rs)
pub cut: Option<crate::cut::Cut>,
/// a goal job's contract: the goal and its rules (goal.rs)
pub goal: Option<crate::goal::Goal>,
/// what the job shows but never delivers, relative to the brief (pictures, render tests, examples): each a file or a
/// `dir/` (review/ and previews/ when left out). Deliverables are what it hands over; previews are how it got there
#[serde(default)]
#[ts(as = "Option<Vec<String>>", optional)]
pub previews: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
@@ -163,10 +150,6 @@ pub struct Object {
pub at: Option<[f64; 3]>,
pub rot: Option<f64>,
pub hero: Option<bool>,
/// how large it is planned to be seen, which is how much of it gets built: 0 the hero (half the frame or more),
/// 1 featured (under 50%), 2 dressing (under 20%), 3 background (under 8%: a grey box reads), 4 far (under 2%: a
/// silhouette). A render that shows it finer than this says so (`lod-closer`; `raea scene lod` lists every part)
pub lod: Option<u8>,
pub pick: Option<Pick>,
/// what was fixed by script ("glass made transmissive, label kept opaque")
#[serde(default)]
@@ -199,22 +182,12 @@ pub struct Shot {
pub fps: Option<f64>,
}
impl Kind {
/// as brief.ts writes it, and as raea judge's rubrics are named
pub fn name(self) -> &'static str {
// in the enum's order
["scene", "kit", "shot", "cut", "goal"][self as usize]
}
}
/// Each kind's dials: what may be set, and what an unset one is read from the references as.
pub fn dials(kind: Kind) -> &'static [&'static str] {
match kind {
Kind::Scene => &["density", "tidiness", "wear", "wetness", "time_of_day", "weather", "atmosphere", "power", "warmth", "look"],
Kind::Kit => &["count", "variety", "detail", "wear", "wetness", "warmth", "look"],
Kind::Shot => &["res", "seconds", "lens", "handheld", "look"],
Kind::Cut => &["look"],
Kind::Goal => &[],
}
}
@@ -241,22 +214,9 @@ pub fn deliverables(m: &Make) -> Vec<String> {
}
// a shot is a still or a move, so either file answers; apps/make reads `a|b`
Kind::Shot => m.shots.iter().map(|s| format!("out/shots/{0}.png|out/shots/{0}.mp4", s.name)).collect(),
Kind::Cut => m.cut.as_ref().map(crate::cut::deliverables).unwrap_or_default(),
// a goal's `file` rules
Kind::Goal => m.goal.iter().flat_map(|g| &g.rules).filter_map(|r| r.file.clone()).collect(),
}
}
/// What the job shows but doesn't deliver: the plan's own list, else review/ and previews/.
pub fn previews(m: &Make) -> Vec<String> {
if m.previews.is_empty() { vec!["review/".into(), "previews/".into()] } else { m.previews.clone() }
}
/// A name a file lands as: [a-z0-9_], not empty.
pub fn is_name(s: &str) -> bool {
!s.is_empty() && s.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
}
/// What the plan still lacks before it can be built against, each with what to do. Empty when it's ready.
pub fn doctor(m: &Make) -> Vec<String> {
let mut out = Vec::new();
@@ -269,18 +229,6 @@ pub fn doctor(m: &Make) -> Vec<String> {
Kind::Scene | Kind::Kit if m.objects.is_empty() => out.push("no objects: list every object with its real size and route".into()),
_ => {}
}
match (&m.cut, m.kind) {
(Some(c), Kind::Cut) => out.extend(crate::cut::doctor(c)),
(None, Kind::Cut) => out.push("no `cut`: the brief as rules (count, cuts, say, never, cta, open), each quoting it".into()),
(Some(_), k) => out.push(format!("`cut` is for a cut job, not a {k:?}: drop it, or make this `cut({{...}})`")),
_ => {}
}
match (&m.goal, m.kind) {
(Some(g), Kind::Goal) => out.extend(crate::goal::doctor(g)),
(None, Kind::Goal) => out.push("no `goal`: the goal in the person's words and its `rules`".into()),
(Some(_), k) => out.push(format!("`goal` is for a goal job, not a {k:?}: drop it, or make this `goal({{...}})`")),
_ => {}
}
if m.kind == Kind::Kit && m.style.is_none() {
out.push("no `style`: one paragraph (era, palette, materials, wear, one fictional maker) every reference carries".into());
}
@@ -292,9 +240,6 @@ pub fn doctor(m: &Make) -> Vec<String> {
if o.h.is_none() && o.dims.is_none() && o.max.is_none() {
out.push(format!("object `{}` has no size: give `h` (metres), `dims` for boxy things or `max` for flat ones", o.id));
}
if o.lod.is_some_and(|l| l > 4) {
out.push(format!("object `{}` has lod {}: 0 (the hero, half the frame or more) to 4 (far, under 2% of it)", o.id, o.lod.unwrap_or(0)));
}
if o.route.is_none() && m.kind == Kind::Scene {
out.push(format!("object `{}` has no route: solid, rule, gen, library or picture", o.id));
}
@@ -309,7 +254,7 @@ pub fn doctor(m: &Make) -> Vec<String> {
if !names.insert(s.name.as_str()) {
out.push(format!("shot `{}` is listed twice", s.name));
}
if !is_name(&s.name) {
if !s.name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') {
out.push(format!("shot `{}`: names are [a-z0-9_], the file it lands as", s.name));
}
if s.composition.is_none() {
@@ -318,13 +263,3 @@ pub fn doctor(m: &Make) -> Vec<String> {
}
out
}
/// One gate as `raea make status` lists it: its name, the file, item or rule it's about, whether it's clear, and what
/// it says. A cut's gates come from raea-runtime-cut-plan, a goal's from raea-runtime-goal-plan.
#[derive(Debug, Clone, PartialEq)]
pub struct Gate {
pub name: &'static str,
pub of: Option<String>,
pub clear: bool,
pub says: String,
}
-11
View File
@@ -117,17 +117,6 @@ fn a_make_plan_reads_and_its_doctor_names_what_it_lacks() {
assert!(want.contains(&"out/kit/phone/phone_lod1.glb".to_string()) && want.contains(&"out/kit/kit.json".to_string()), "{want:?}");
}
// MK22: an object's planned detail, 0 (the hero) to 4 (far)
#[test]
fn an_object_plans_its_detail_and_the_doctor_holds_it_to_five_levels() {
let m: make::Make = read("make", r#"{"kind": "scene", "objects": [
{"id": "kiosk", "label": "Kiosk", "h": 2.4, "route": "solid", "lod": 3},
{"id": "tower", "label": "Tower", "h": 40, "route": "picture", "lod": 7}]}"#).unwrap();
assert_eq!(m.objects[0].lod, Some(3));
let d = make::doctor(&m);
assert!(d.iter().any(|x| x.contains("`tower` has lod 7")) && !d.iter().any(|x| x.contains("`kiosk`")), "{d:?}");
}
#[test]
fn a_shot_plan_wants_a_still_or_a_move_per_shot() {
let m: make::Make = read("make", r#"{"kind": "shot", "shots": [{"name": "counter_push", "move": "push_in"}, {"name": "Bad Name"}]}"#).unwrap();
-128
View File
@@ -224,131 +224,3 @@ pub fn ray_tri(o: Vec3, d: Vec3, [a, b, c]: [Vec3; 3]) -> Option<f32> {
let t = e2.dot(q) / det;
(t >= 0.0).then_some(t)
}
/// The part's lowest points (its feet): its vertices within a millimetre (or 2% of its height) of its lowest, and
/// points across the faces lying there (a slab's corners overhang what holds it up; its middle doesn't), about 4 n at most.
pub fn feet(p: &Part, n: usize) -> Vec<Vec3> {
let tol = (0.02 * (p.hi.y - p.lo.y)).clamp(0.0005, 0.003);
let low = |q: &Vec3| q.y <= p.lo.y + tol;
let mut v: Vec<Vec3> = p.tris.iter().flatten().filter(|q| low(q)).copied().collect();
let bases: Vec<&[Vec3; 3]> = p.tris.iter().filter(|t| t.iter().all(low)).collect();
let area: f32 = bases.iter().map(|t| 0.5 * (t[1] - t[0]).cross(t[2] - t[0]).length()).sum();
if area > 0.0 {
// about n points over the base, spread by area
let step = (area / n as f32).sqrt();
for t in bases {
let long = (t[1] - t[0]).length().max((t[2] - t[1]).length()).max((t[0] - t[2]).length());
let m = ((long / step).ceil() as usize).clamp(1, 32);
for i in 0..=m {
for j in 0..=(m - i) {
let (a, b) = (i as f32 / m as f32, j as f32 / m as f32);
v.push(t[0] + (t[1] - t[0]) * a + (t[2] - t[0]) * b);
}
}
}
}
v.sort_by(|a, b| (a.x, a.z, a.y).partial_cmp(&(b.x, b.z, b.y)).unwrap_or(std::cmp::Ordering::Equal));
v.dedup_by(|a, b| (*a - *b).length() < 1e-4);
if v.len() > 4 * n {
let k = v.len() as f32 / (4 * n) as f32;
v = (0..4 * n).map(|i| v[(i as f32 * k) as usize]).collect();
}
v
}
/// A wall, or a piece of one (the strip of wall over a window, the window in it): no thicker than WALL_THICK, at least
/// WALL_WIDE across and WALL_TALL high (metres; the kitchen's strip over its back window is 9.6 cm).
const WALL_THICK: f32 = 0.35;
const WALL_WIDE: f32 = 0.8;
const WALL_TALL: f32 = 0.05;
/// Whether a part is a wall or a piece of one: thin, wide and high.
pub fn wall(p: &Part) -> bool {
let e = p.hi - p.lo;
e.y >= WALL_TALL && e.x.min(e.z) <= WALL_THICK && e.x.max(e.z) >= WALL_WIDE
}
/// A wall's face area, for which of two is set into the other.
pub fn face(p: &Part) -> f32 {
let e = p.hi - p.lo;
e.y * e.x.max(e.z)
}
/// Whether a part's own material gives off light (a lamp's panel, a neon tube): any of its emissive's red, green or
/// blue above zero. A model's materials are in its file and aren't read here.
pub fn glows(it: &Item) -> bool {
it.material.as_ref().and_then(|m| m.props.get("emissive")).is_some_and(glows_in)
}
fn above_zero(v: &Value) -> bool {
v.as_f64().unwrap_or(0.0) > 0.0
}
/// A colour as the SDK writes one: [r, g, b, a], { red, green, blue, alpha }, a tagged one ({ LinearRgba: {...} }) or a
/// CSS string.
fn glows_in(v: &Value) -> bool {
match v {
Value::Array(a) => a.iter().take(3).any(above_zero),
Value::Object(o) => {
let own = ["red", "green", "blue", "r", "g", "b"].iter().filter_map(|k| o.get(*k)).any(above_zero);
own || o.values().any(|v| (v.is_object() || v.is_array()) && glows_in(v))
}
Value::String(c) => !matches!(c.trim_start_matches('#').to_ascii_lowercase().as_str(), "000" | "000000" | "black" | ""),
_ => false,
}
}
/// How far from the scene a part is parked: a piece swaps a flipbook's frames (MALL RAT's fountain, 88 water models) by
/// moving the ones not shown hundreds of metres away, where they lie in one another and read as faces fighting.
const PARKED: f32 = 500.0;
/// The parts in the scene, without those parked far from it (further than PARKED from the median of every part's
/// centre), each of those said once as not checked.
pub fn unparked<T>(parts: Vec<Part>, items: Vec<T>, skipped: &mut Vec<String>) -> (Vec<Part>, Vec<T>) {
if parts.len() < 3 {
return (parts, items);
}
let mid = |k: usize| {
let mut v: Vec<f32> = parts.iter().map(|p| ((p.lo + p.hi) * 0.5)[k]).collect();
v.sort_by(f32::total_cmp);
v[v.len() / 2]
};
let centre = Vec3::new(mid(0), mid(1), mid(2));
let mut parked = 0;
let kept: (Vec<Part>, Vec<T>) = parts.into_iter().zip(items).filter(|(p, _)| {
let far = ((p.lo + p.hi) * 0.5).distance(centre) > PARKED;
parked += far as usize;
!far
}).unzip();
if parked > 0 {
skipped.push(format!("{parked} part{} parked over {PARKED} m from the scene (a flipbook's frames not shown)", if parked == 1 { "" } else { "s" }));
}
kept
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_flipbooks_frames_parked_far_away_are_left_out() {
let part = |name: &str, c: Vec3, s: Vec3| Part { label: name.into(), tris: Vec::new(), node: Vec::new(), nodes: Vec::new(), lo: c - s / 2.0, hi: c + s / 2.0, excused: false, moving: false };
let mut parts = vec![part("floor", Vec3::ZERO, Vec3::new(20.0, 0.1, 20.0)), part("bench", Vec3::new(1.0, 0.3, 0.0), Vec3::new(1.5, 0.5, 0.4)), part("water0", Vec3::new(0.0, 0.5, 3.0), Vec3::ONE)];
for i in 1..4 {
parts.push(part(&format!("water{i}"), Vec3::new(0.0, -900.0, 3.0), Vec3::ONE));
}
let mut skipped = Vec::new();
let (kept, _) = unparked(parts, vec![(); 6], &mut skipped);
assert_eq!(kept.iter().map(|p| p.label.as_str()).collect::<Vec<_>>(), ["floor", "bench", "water0"]);
assert!(skipped[0].starts_with("3 parts parked"), "{skipped:?}");
}
#[test]
fn a_colour_with_any_light_in_it_glows() {
use serde_json::json;
assert!(glows_in(&json!({"red": 0.0, "green": 120.0, "blue": 0.0, "alpha": 1.0})));
assert!(glows_in(&json!([2200.0, 120.0, 80.0, 1.0])));
// black with an alpha of 1 doesn't
assert!(!glows_in(&json!({"red": 0.0, "green": 0.0, "blue": 0.0, "alpha": 1.0})));
assert!(!glows_in(&json!([0.0, 0.0, 0.0, 1.0])));
}
}
+14 -149
View File
@@ -22,6 +22,7 @@ struct Face {
n: Vec3,
d: f32,
tri: [Vec3; 3],
area: f32,
}
fn face(t: &[Vec3; 3]) -> Option<Face> {
@@ -31,7 +32,7 @@ fn face(t: &[Vec3; 3]) -> Option<Face> {
return None;
}
let n = c / l;
Some(Face { n, d: n.dot(t[0]), tri: *t })
Some(Face { n, d: n.dot(t[0]), tri: *t, area: 0.5 * l })
}
type Key = (i32, i32, i32, i64);
@@ -45,17 +46,11 @@ fn near(k: Key) -> impl Iterator<Item = Key> {
(-1..=1).flat_map(move |a| (-1..=1).flat_map(move |b| (-1..=1).flat_map(move |c| (-1..=1).map(move |e| (k.0 + a, k.1 + b, k.2 + c, k.3 + e as i64)))))
}
/// A point of a plane with normal `n` as two numbers, in an orthonormal frame of the plane.
fn flat_in(n: Vec3) -> impl Fn(Vec3) -> Vec2 {
let u = n.any_orthonormal_vector();
let v = n.cross(u);
move |p| Vec2::new(p.dot(u), p.dot(v))
}
/// Whether two coplanar faces overlap by more than INSIDE: separating axes in the plane, in an orthonormal frame.
fn overlap(a: &Face, b: &Face) -> bool {
let point = flat_in(a.n);
let flat = |t: &[Vec3; 3]| t.map(&point);
let u = a.n.any_orthonormal_vector();
let v = a.n.cross(u);
let flat = |t: &[Vec3; 3]| t.map(|p| Vec2::new(p.dot(u), p.dot(v)));
let (p, q) = (flat(&a.tri), flat(&b.tri));
for tri in [&p, &q] {
for k in 0..3 {
@@ -78,119 +73,24 @@ fn overlap(a: &Face, b: &Face) -> bool {
true
}
/// What two coplanar faces share: its area, and its middle. One triangle cut by the other's three edges.
fn shared(a: &Face, b: &Face) -> (f32, Vec3) {
// the same frame flat_in makes, to carry the middle back into the world
let u = a.n.any_orthonormal_vector();
let v = a.n.cross(u);
let flat = flat_in(a.n);
let mut poly: Vec<Vec2> = a.tri.iter().map(|p| flat(*p)).collect();
let q = b.tri.map(flat);
// b's winding in this frame, so its inside is on one known side of each edge
let turn = (q[1] - q[0]).perp_dot(q[2] - q[0]).signum();
for k in 0..3 {
let (e0, e1) = (q[k], q[(k + 1) % 3]);
let side = |p: Vec2| (e1 - e0).perp_dot(p - e0) * turn;
let mut cut = Vec::with_capacity(poly.len() + 2);
for i in 0..poly.len() {
let (p0, p1) = (poly[i], poly[(i + 1) % poly.len()]);
let (s0, s1) = (side(p0), side(p1));
if s0 >= 0.0 {
cut.push(p0);
}
if (s0 > 0.0 && s1 < 0.0) || (s0 < 0.0 && s1 > 0.0) {
cut.push(p0 + (p1 - p0) * (s0 / (s0 - s1)));
}
}
poly = cut;
if poly.len() < 3 {
return (0.0, Vec3::ZERO);
}
}
let mut area = 0.0;
let mut mid = Vec2::ZERO;
for i in 1..poly.len() - 1 {
let t = 0.5 * (poly[i] - poly[0]).perp_dot(poly[i + 1] - poly[0]).abs();
area += t;
mid += (poly[0] + poly[i] + poly[i + 1]) / 3.0 * t;
}
if area <= 0.0 {
return (0.0, Vec3::ZERO);
}
let mid = mid / area;
(area, u * mid.x + v * mid.y + a.n * a.d)
}
fn same_plane(a: &Face, b: &Face) -> bool {
a.n.dot(b.n) >= PARALLEL && (a.n.dot(b.tri[0]) - a.d).abs() <= PLANE
}
/// One face over another: how many pairs, the area they share, and the middle of the largest shared patch. `b` None: within `a` itself.
/// One face over another: how many pairs, about how much area (the smaller face of each pair, summed: an upper
/// bound), and where the first is. `b` None: within `a` itself.
pub fn overlaps(a: &[[Vec3; 3]], b: Option<&[[Vec3; 3]]>) -> Option<(usize, f32, Vec3)> {
let o = sorted(a, b);
o.fight.or(o.twins).or(o.bases)
}
/// Faces in one plane over each other, by whether they show.
#[derive(Default, Debug)]
pub struct Overlaps {
/// One face over a different one: the picture flickers between them.
pub fight: Option<(usize, f32, Vec3)>,
/// Between two parts, the same triangle in both (a slab built into two neighbouring chunks): nothing to see where
/// they look alike, since either draws the same.
pub twins: Option<(usize, f32, Vec3)>,
/// Between two parts, faces looking straight down in the plane both parts stand on (two boxes on one floor, one
/// set into the other): their undersides, which the floor hides.
pub bases: Option<(usize, f32, Vec3)>,
}
/// Corners this close (metres) are one corner.
const CORNER: f32 = 0.0005;
fn twin(a: &Face, b: &Face) -> bool {
a.tri.iter().all(|p| b.tri.iter().any(|q| p.distance(*q) <= CORNER))
}
/// The lowest corner of a part's faces.
fn low(faces: &[Face]) -> f32 {
let mut y = f32::INFINITY;
for f in faces {
for p in &f.tri {
y = y.min(p.y);
}
}
y
}
/// As `overlaps`, with the pairs that don't show kept apart (between two parts only: inside one model every pair counts).
pub fn sorted(a: &[[Vec3; 3]], b: Option<&[[Vec3; 3]]>) -> Overlaps {
if b.is_none() && a.len() > SELF_MAX {
return Overlaps::default();
return None;
}
let fa: Vec<Face> = a.iter().filter_map(face).collect();
let fb: Vec<Face> = b.map(|b| b.iter().filter_map(face).collect()).unwrap_or_default();
let others = if b.is_some() { &fb } else { &fa };
let (low_a, low_b) = (low(&fa), low(&fb));
let mut buckets: HashMap<Key, Vec<usize>> = HashMap::new();
for (i, f) in others.iter().enumerate() {
buckets.entry(key(f.n, f.d)).or_default().push(i);
}
let mut out = Overlaps::default();
// the largest patch each kind has seen, for where to point
let mut most = [0.0f32; 3];
let mut add = |kind: usize, to: &mut Option<(usize, f32, Vec3)>, f: &Face, g: &Face| {
let (area, mid) = shared(f, g);
if area <= 0.0 {
return;
}
let e = to.get_or_insert((0, 0.0, mid));
e.0 += 1;
e.1 += area;
if area > most[kind] {
most[kind] = area;
e.2 = mid;
}
};
let (mut count, mut area, mut at) = (0usize, 0f32, None);
for (i, f) in fa.iter().enumerate() {
let mut seen: Vec<usize> = Vec::new();
for k in near(key(f.n, f.d)) {
@@ -202,20 +102,14 @@ pub fn sorted(a: &[[Vec3; 3]], b: Option<&[[Vec3; 3]]>) -> Overlaps {
seen.push(j);
let g = &others[j];
if same_plane(f, g) && overlap(f, g) {
let y = f.tri[0].y;
let base = b.is_some() && f.n.y <= -0.999 && (y - low_a).abs() <= 0.001 && (y - low_b).abs() <= 0.001;
if base {
add(0, &mut out.bases, f, g);
} else if b.is_some() && twin(f, g) {
add(1, &mut out.twins, f, g);
} else {
add(2, &mut out.fight, f, g);
}
count += 1;
area += f.area.min(g.area);
at.get_or_insert((f.tri[0] + f.tri[1] + f.tri[2]) / 3.0);
}
}
}
}
out
at.map(|at| (count, area, at))
}
#[cfg(test)]
@@ -233,12 +127,7 @@ mod tests {
let floor = quad(0.0, -1.0, 1.0, true);
let rug = quad(0.0001, 0.0, 0.5, true);
let (n, area, _) = overlaps(&rug, Some(&floor)).expect("the rug's top fights the floor's");
// the rug's whole top, 0.5 m², and no more (the floor's triangles are bigger); pointed at inside the rug
let at = overlaps(&rug, Some(&floor)).unwrap().2;
assert!(n >= 2 && (area - 0.5).abs() < 1e-4 && at.x > 0.0 && at.x < 0.5 && at.z > 0.0 && at.z < 1.0, "{n} {area} {at}");
// a strip 2 mm wide along a metre: 20 cm²
let (_, strip, _) = overlaps(&quad(0.0, 0.998, 2.0, true), Some(&floor)).expect("a strip over the floor's edge");
assert!((strip - 0.002).abs() < 1e-5, "{strip}");
assert!(n >= 2 && area > 0.1, "{n} {area}");
// 1 cm above it, it doesn't
assert!(overlaps(&quad(0.01, 0.0, 0.5, true), Some(&floor)).is_none());
// back to back (a box resting on another: one top up, the other's bottom down) doesn't fight
@@ -251,28 +140,4 @@ mod tests {
assert_eq!(overlaps(&doubled, None).map(|o| o.0), Some(1));
assert!(overlaps(&quad(0.5, 0.0, 1.0, true), None).is_none());
}
#[test]
fn the_same_faces_in_two_parts_and_undersides_on_one_floor_are_kept_apart_from_a_fight() {
// a slab built into two chunks: the same triangles in both
let slab = quad(8.8, 0.0, 4.0, true);
let o = sorted(&slab, Some(&slab));
assert!(o.fight.is_none() && o.twins.map(|t| t.0) == Some(2), "{o:?}");
// a rug's top in the floor's is a different face over it: a fight
let o = sorted(&quad(0.0001, 0.0, 0.5, true), Some(&quad(0.0, -1.0, 1.0, true)));
assert!(o.fight.is_some() && o.twins.is_none() && o.bases.is_none(), "{o:?}");
// a door set into a wall, both standing on the floor: their undersides overlap in the floor's plane
let mut wall = quad(0.0, -1.0, 1.0, false);
wall.extend(quad(2.0, -1.0, 1.0, true));
let mut door = quad(0.0, -0.4, 0.4, false);
door.extend(quad(1.0, -0.4, 0.4, true));
let o = sorted(&door, Some(&wall));
assert!(o.fight.is_none() && o.bases.is_some(), "{o:?}");
// the same underside held up off the ground (a soffit under a beam's) still fights
let mut beam = quad(2.0, -1.0, 1.0, false);
beam.extend(quad(0.0, -1.0, 1.0, true));
let mut soffit = quad(2.0, -0.4, 0.4, false);
soffit.extend(quad(1.5, -0.4, 0.4, true));
assert!(sorted(&soffit, Some(&beam)).fight.is_some());
}
}
-101
View File
@@ -1,101 +0,0 @@
@spec
Feature: raea cloud: a synced folder is pictured, understood, embedded and organized for the person
Shane, 2026-11-24: "when i have a data sync, we should auto index/tag and relate them to the appropriate folders or
have an ai agent or our ask/decision model api if available otherwise use their subscription agent and tag or
auto-organize the assets or files or folders so we can help understand what purpose they are for and predict what
they mean/do. also make sure we embed all the assets based on embedding type. this will mean if we have a client
library, we want to relate a client based folder to that library, or if disorganized we go file by file."
Later that day: "we should be able to pick a folder from a sync location and have all content when syncing
auto-tagged and organized for the user", "make sure thumbnails are also generated correctly", and of the models:
"isn't it running the models in modal?"
Today (11-24) a sync lists its folder through Composio and adds each file as a link item, all in one flat folder,
named and typed from its name and mime type only. Search embeds words (Workers AI's bge-small) and nothing else; no
file is tagged; pictures came from drive.google.com in the viewer's browser, so a viewer signed out of Google saw
none. The first real client demo is StreetTalk's: workspace streettalk, its Main library's "raea test — StreetTalk
samples (Nov 2026)" Drive folder (54 files: 47 videos, 6 documents, 1 picture) and three client libraries (Dutch,
Elfster, The Body Shop), each with a Drive folder of its own.
Background:
Given a workspace with Google Drive (or Box, Dropbox, Frame.io, Slack) connected through Composio
And raea never moves, renames or deletes anything in the tool: organizing happens in raea's library only
Rule: a folder is picked, and its shape comes with it
Scenario: IG1. A sync is a folder picked from the tool's own list
When the person adds a sync and picks a folder from Drive's list (syncadd.js)
Then the sync keeps the folder's id and its name; a folder typed as its id or its Drive link works the same,
and is named for the folder on its first run (built 11-24: sync-run.ts driveId, NAME)
Scenario: IG2. Subfolders come in as folders
Given the picked folder holds subfolders ("Raw/Angle 1", "Finals")
Then each becomes a library folder under the sync's folder, with the same name and nesting, and each file lands
in its own; a file moved between subfolders in the tool moves in raea on the next run
Rule: every file has a picture anyone who can see the library sees
Scenario: IG3. A synced file's picture is kept by raea
When a run lists a file that has a picture in its tool (Drive's thumbnailLink; Box's and Dropbox's thumbnails)
Then raea fetches it once at 640 px and keeps it in the workspace's own store (items.thumb, the API's signed
thumb_src), 60 a run, a failed fetch tried again on the next run (built 11-24 for Drive)
And the library's card shows it, with a play mark on a video; a tool's page address is never put in a <video>
Scenario: IG4. A file with no picture in its tool gets one made
Given a video, PDF or document the tool has no picture of
Then a frame (a video's at 10% of its length), a first page or a typeset title card is made on Modal (IG8) and
kept the same way
Rule: every file is understood
Scenario: IG5. Each new file is read by its kind
When a run brings files in
Then each is read once per version (its tool's modified time or checksum): a picture by its picture; a video by
its picture, frames at 10/50/90% and its words (transcribed); a document by its text (Drive exports Docs as
text, PDFs are read); a sound by its words or, with none, what it sounds like
And what it says about the file is kept on the item: a one-line description, tags (its kind: raw footage, b-roll,
a final cut, a brief, a script, a logo, a voiceover, a reference; its subject; its client or brand; its format,
9x16 or 16x9; its length), and for each tag who said it and why
Scenario: IG6. raea's model reads first; the workspace's agent when there's none
(built 11-24 with raea's model as a vision model on OpenRouter, tagger.ts: description, role, client, tags with
why, on the item and its turbopuffer rows; raea ask's clef model takes its place when it's deployed)
Given the workspace's plan has raea's ask model (raea ask, docs/ask.feature: clef-omni on the plan's pool)
Then the files are read by it, batched, the spend on the pool
Otherwise they are read by the workspace's own connected agent on raea cloud's box (Claude Code on its Claude, or
Antigravity on its Google AI plan), as a background job that never takes a project's turn
And with neither, files are tagged from their names, folders and types alone, and the library says how to get more
Scenario: IG7. A person's correction wins
When someone removes or changes a tag, or moves a file to another folder
Then raea never puts it back, and the next files like it are read with that correction in the prompt
Rule: every file is embedded by its kind, once, into turbopuffer (Enterprise)
Scenario: IG8. raea's own library indexer runs on Modal and writes to turbopuffer
Then each file is indexed by the desktop's own indexer (apps/app host/library/index-file.ts, in the cloud
indexer's image: EmbeddingGemma 2 for pictures, shots, sound and words, TransNetV2 cuts, Whisper; a document's
text in windows), as a job on Modal (ingest.py index_job, any length), so a desktop's and the cloud's vectors
compare; EmbeddingGemma 2 on a GPU (RAEA_INDEX_GPU=L4: fp16, CUDA 13) while there's work, else the CPU at q8
And its rows go to turbopuffer in raea-api's layout, one namespace a workspace (raea-cloud-<workspace>.
embeddinggemma-2@768), a row per segment and modality, replaced when the file is indexed again
And only an Enterprise workspace is indexed in the cloud (raea cloud is Enterprise only, Shane 11-24); the raea
app's Pro and Team plans embed on their own computers and keep their index in turbopuffer through raea-api,
Free on the Mac
(built 11-24: index-run.ts, tools/library-index cloud.ts, cloud-cli.ts, cloud-server.ts)
Scenario: IG9. Search finds a file by what's in it
(built 11-24: search.ts deep, turbopuffer's nearest segments, a hit's at {t0, t1})
When the person searches "girl laughing on a street corner, vertical"
Then the words are matched against pictures and frames (SigLIP's text tower), descriptions and transcripts, and
tags, fused into one ranking; a hit says where in a video it is
Rule: the files are organized for the person
Scenario: IG10. A folder about a client goes with that client's library
Given a synced folder whose name, or most of whose files, are about one of the workspace's clients
Then the sync is related to that client's library (or its files are, when the folder is the workspace's), shown
with the reason ("47 of 54 files show The Body Shop's products"), and undone in one click
Scenario: IG11. A disorganized folder is sorted file by file
Given a folder of files with no useful subfolders
Then raea proposes folders (by client, then by kind: Raw, B-roll, Finals, Briefs) with each file's place and
reason, as one review the person accepts whole, or file by file; nothing moves until they do
And once accepted, new files that fit are placed the same way on later runs
Rule: the person can see it working
Scenario: IG12. The left panel says what a sync is doing
Then a sync bringing files in turns in the left panel, on its row and its library's (built 11-24), then says
"Reading 12 of 54" while files are read, and its card shows the tags as they come
Scenario: IG13. Proven on StreetTalk's demo
When StreetTalk's four Drive syncs run from empty
Then every file has a picture, a description and tags; the three client folders are related to their client
libraries; a search for a shot finds it by what's in it; and the run says its time and what it cost
-124
View File
@@ -24,8 +24,6 @@ Feature: Make: scenes, kits and shots built to a frozen plan and held to a revie
once each is calibrated on the person's labels; a fresh critic's fixes always (fixed or answered), its score
once `raea judge calibrate` agrees with the person's eye.
5. Every job ends with its notes, including what the skill got wrong for it, so the next job starts from them.
6. Every object is planned at a level of detail, by how large it is meant to be seen, and every render says
when a shot shows one closer than that (MK21-MK24).
Background:
Given raea's scene loop as advice (sdk/guides/craft/bevy/scenes.md, from the 11-06 research): brief, routing,
@@ -196,128 +194,6 @@ Feature: Make: scenes, kits and shots built to a frozen plan and held to a revie
plan from the entrance (blockout.tsx, and `raea render --review` sheets of it) and puts the reference, the
blockout and the floor plan on comparison.png, for the person to approve before anything is generated
Rule: planned detail (MK21-MK24)
Shane, 2026-11-24: "define objects at an LOD level based on either us grayboxing or thinking of them as generally
distant objects and alert agents when an LOD that was at 3 or 4 for example is now appearing in frame at LOD 2
level or 1, or 0 ... helpful for planning objects as generally distant and unseen objects versus close ones and
knowing if we forgot about something over time". A level is how large a part is planned to be seen, which is how
much of it gets built; the frames are measured against it on every render, so a camera move added later, or a
box that was meant to be replaced, is said the next time anything is drawn.
@done
Scenario: MK21. A part shown closer than its planned detail is said
Given a level is how much of the frame a part's box spans through the frame's camera, the larger of its width's
and its height's share: 0 the hero (50% or more), 1 featured (20%), 2 dressing (8%), 3 background (2%), 4 far
And a part's plan is its own `lod` (Mesh3d, Model, and every part inside an Entity with a transform or a Group
that has one), else the `lod` of the plan's object of its name
When a frame shows a planned part at a finer level than its plan (raea-runtime-lod-plan)
Then the render's end checks, `raea scene stage` and `raea check --quick` say `lod-closer`: the part, its plan,
the level it is seen at, how much of the frame it spans at its largest and on which frame, how many frames it
is closer on, and the fix (build it for that level and plan it there, or keep the camera off it)
And one level finer is a warning, two or more an error, which fails the render as any error does
And a part out of the frame, behind the camera, or with another mesh's box across every line to it isn't seen;
a part the camera stands in or beside is measured at its nearest point; RAEA_LOD_CHECK=0 leaves the check out
@needs:MK21 @done
Scenario: MK22. The plan carries each object's level
Given `lod: 0..4` on an object of `make` in brief.ts (core/brief make.rs; `doctor` refuses a level past 4)
Then a render of a composition under that brief holds the parts named as the objects' ids to those levels
(runtime/lod-plan plan.rs reads the brief only when its words plan a level, once a version)
And `raea make plan` labels each footprint with its level and writes each grey box with its object's id as its
name and its `lod`, so the blockout is held to the plan it draws
@needs:MK21 @done
Scenario: MK23. `raea scene lod`: every part's plan beside what the frames show
When `raea scene lod EDIT.tsx [--from N] [--to N] [--json]` steps the frames without drawing
Then it lists every part: its planned level, the finest level a frame shows it at, how much of the frame it
spans there, on which frame, and how many frames it is in; parts seen closer than planned first (the widest
gap on top), then the rest of the planned, then the parts with no plan by how large they get
And a planned part no frame shows as close as its plan says so (built finer than it is ever seen)
And a level the plan gives a name that no part in the frames goes by is listed, since it holds nothing
And it exits 1 when a part is seen two or more levels finer than planned
@needs:MK22 @done
Scenario: MK24. A job is held at a part seen closer than planned
Given a job whose composition's last render or check found `lod-closer`
Then `raea make status` has a `lod` gate for that composition, open with the parts' names, until each is built
for the level it is seen at and replanned, kept out of the camera's way, or answered in NOTES.md on a line
with `lod` and its name; the Stop hook holds the agent there as at any open gate
And a job that plans a level and whose render found none shows the gate clear
Rule: cuts from a client's brief (MK25-MK27)
Shane, 11-25, on StreetTalk's street interview ads, cut by raea cloud agents from three clients' PDF briefs: "you
need to make the process of ingesting the brief more direct, or else it's just context that gets lost. It needs to
be written as a brief typescript rule that is then enforced ... I need raea make to be the standard". The agents had
read the briefs and still shipped what a contract catches: held to one written from Elfster's brief, Gemini's four
delivered solos (eight files) had "free, fun, and easy" missing from three, the CTA rewritten in one ("Download
Elfster for free in the App Store") and missing from another, no frames check on any final file, and four of the
ten cuts the brief asks for in its out/ folder.
@needs:MK0
Scenario: MK25. The brief as rules: `make: cut({...})`
Given a client's brief as text beside brief.ts (pdftotext -layout BRIEF.pdf media/brief.txt)
When the agent writes `make: cut({ cut: {...} })` before it plans a single cut
Then core/brief reads `cut` (cut.rs): `brief` (that text), `count` (how many cuts the brief asks for), `seconds`
and `formats`, each cut (id, angle, solo or mashup, hook, captions or a text hook, its own formats and length),
`say` (phrases every cut says or shows, or one cut with `every: false`), `never` (phrases no cut says or
shows), `cta` (the line every cut ends on, within its last 8 s; `also`: the other lines a brief rotates, any
one of which lands it, each found in the brief) and `open` (the brief's [TO CONFIRM] items)
And every rule has `from`: the brief's own words for it
And each cut lands at a fixed path, out/cuts/<id>_<W>x<H>.mp4 for each of its formats
And `doctor` names what the contract still lacks: no count, no cta, an id that isn't [a-z0-9_], a format that
isn't W:H, a cut with no length, a rule with no `from`
@needs:MK25
Scenario: MK26. Held to the brief's own words, its count and its open items
Given a cut contract
Then `raea make status` finds every `from` in the brief's text, compared by letters and digits: a rule the brief
doesn't say, or says in other words, holds the job ("quotes")
And fewer cuts than `count` hold it, unless an `open` item about "count" has the person's answer ("count")
And every `open` item without an answer holds it, so the agent stops at a review to ask ("open")
@needs:MK25
Scenario: MK27. Every delivered file held to the rules, from what's on disk
Given a cut's file at its path
Then its shape and length are read from its own MP4 boxes, so a file re-encoded after its render is read as it is
now ("shape")
And its words must be heard after its last change (FILE.words.json, `raea words`), and in them or its render's
text (FILE.render.json): every `say` phrase ("say"), no `never` phrase, with the second it's heard ("never"),
and the CTA in its last `within` seconds, 85% of its words in order ("cta")
And its frames check must have run after its last change (FILE.frames-check.json, `raea frames check`) with no
error: no face cut by the frame or a seam, no text under the size floor ("frames")
And the cut job has no critic tier yet: the person's review is its critic
Rule: any goal, held to rules (MK28-MK29)
Shane, 11-26, asking whether raea make is just a version of /goal: "when we use these things, they should just
probably be consolidated into one workflow, because in any case we'll have a goal or a brief or something that
dictates what we need. And then we essentially just need to make sure that it can't stop unless all the goals pass,
or all the rules in the brief". /goal in raea.app's chat let the agent end the loop by writing "GOAL MET"; a goal it
can declare met is advice. So /goal and raea make are one loop: a goal is a fifth kind of job, its words become
rules in brief.ts before the work starts, and only `raea make status` says it's met.
@needs:MK2
Scenario: MK28. A goal as rules: `make: goal({...})`
Given work that isn't a scene, kit, shot or cut (fix a bug, write a page, ship a change)
When the agent writes `make: goal({ goal: "the person's words", rules: [...] })` before it starts
Then core/brief reads `goal` (goal.rs): the goal as the person said it, and `rules`, each an id and exactly one of
`run` (a command that must exit 0 in the brief's folder, within `timeout` seconds, 300 by default), `file` (a
file that must exist: a deliverable) or `says` (words that must be true of the work)
And `doctor` names what it lacks: no goal, no rules, an id that isn't [a-z0-9_] or is listed twice, a rule with
none or more than one of run, file and says, a timeout with no run
And a goal job needs no NOTES.md "What the skill got wrong" section (no skill made it) and has no render critic
@needs:MK28
Scenario: MK29. Held by a command's exit and a fresh critic, never the agent's word
Given a goal job
Then `raea make status` runs every `run` rule at every status, the Stop hook's included, and holds the job on one
that fails or outlives its timeout, with its exit code and last line ("run")
And a `says` rule is clear only when review/goal.judge.json, written by `raea make judge [DIR] [--by claude|kimi]`
(a fresh session that may only read: Read, Grep and Glob), found it true at a time no earlier than the work's
newest file, the job's own review/, .raea/, NOTES.md, .git and node_modules left out, compared at whole seconds
("says")
And `file` rules are its deliverables, listed under missing
And raea.app's /goal is this job: it writes the rules first, and only the status ends the loop
Rule: raea cloud (MK19-MK20)
@needs:MK2 @done
+2 -3
View File
@@ -66,9 +66,7 @@ else throws a SyntaxError, as Chrome's does.
that doesn't load rejects, and the text falls back.
- `window` has `innerWidth`, `innerHeight` and `devicePixelRatio` for the composition's size, and `getComputedStyle`.
- `requestAnimationFrame` calls back once per frame drawn, given that frame's time, so a frame drawn again gets the
same calls. `new Image()` fires `load` when its `src` is set (a `staticFile` path, a data: URL or an http URL), and
by then `naturalWidth` and `naturalHeight` are the picture's size; `width` and `height` are the ones you gave, else
the same. A file that isn't there fires `error` instead.
same calls. `new Image()` fires `load` when its `src` is set, with no pixel size.
- `ResizeObserver` calls back once when it starts observing, then after any layout that changed an observed element's
size, with `contentRect`, `borderBoxSize` and `contentBoxSize`.
@@ -77,6 +75,7 @@ else throws a SyntaxError, as Chrome's does.
- `MutationObserver` and `IntersectionObserver` exist, so a component that makes one doesn't throw, but they never
call back.
- An `<img>`'s `onError` never fires: an image that doesn't load fails the render, naming its src.
- `new Image()` has no `naturalWidth` or `naturalHeight` (they stay 0).
- An element has no `innerHTML` or `outerHTML`: read `textContent`, or walk `children` and `childNodes`.
- A Range across wrapped lines is one rect, not one per line, and an inline element's `getClientRects()` is one rect
too.
+1 -1
View File
@@ -1,7 +1,7 @@
---
title: "raea app"
summary: "Run, check headless and package a desktop app written as one TSX file on @raea/ui."
order: 8
order: 7
sources: ["engine/cli/src/cli.rs", "engine/rune/src/main.rs"]
---
+1 -1
View File
@@ -1,7 +1,7 @@
---
title: "raea bundle"
summary: "Bundle a composition into one JavaScript file that render_bundle draws, on the Mac or the iPhone."
order: 7
order: 6
sources: ["engine/cli/src/cli.rs", "runtime/bundle/src/lib.rs"]
---
+1 -1
View File
@@ -1,7 +1,7 @@
---
title: "raea export"
summary: "The composition as a CapCut draft ready in its timeline: its footage and sounds as clips of their own files at their trims and gains, everything raea draws as transparent overlay clips above them."
order: 6
order: 5
sources: ["engine/cli/src/cli.rs"]
---
+1 -2
View File
@@ -35,7 +35,6 @@ Render, play and package what you wrote.
| [`raea render`](render.md) | Render a composition to an MP4, a PNG or a folder of frames, on the GPU and headless. |
| [`raea play`](play.md) | Play a game live in a window, or headless with scripted keys, snapshots and a timing report. |
| [`raea export-game`](export-game.md) | Package a game as a program of its own: a Mac app or a command-line program. |
| [`raea playable`](playable.md) | Export a game as a playable ad: one page or ZIP for each ad network, under its size cap, from the same TSX that renders as the video ad. |
| [`raea export`](export.md) | The composition as a CapCut draft ready in its timeline: its footage and sounds as clips of their own files at their trims and gains, everything raea draws as transparent overlay clips above them. |
| [`raea bundle`](bundle.md) | Bundle a composition into one JavaScript file that render_bundle draws, on the Mac or the iPhone. |
| [`raea app`](app.md) | Run, check headless and package a desktop app written as one TSX file on @raea/ui. |
@@ -69,7 +68,7 @@ What's wrong before anyone watches it.
| [`raea make`](make.md) | A scene, kit or shot made to its plan: the plan stop, the kit's references, generators, pick, prep and landing, a shot list's framing and lens charts, and whether it's done, decided in code; the agent's Stop hook holds it there. |
| [`raea fingerprint`](fingerprint.md) | A person's sense of good work, learned on this Mac: axes with small heads over on-device encoders that score a render moment by moment and say what they can't judge yet. |
| [`raea findings`](findings.md) | What each render and check found, read back from the project's record: fixed, new and carried since the one before. |
| [`raea scene`](scene.md) | Find floating, sunk and clipping 3D parts, say what each part rests on, meter a shot's light, hold every frame to the stage checks a render runs, and list each part's planned detail beside how large the frames show it. |
| [`raea scene`](scene.md) | Find floating, sunk and clipping 3D parts, say what each part rests on, meter a shot's light, and hold every frame to the stage checks a render runs. |
| [`raea light`](light.md) | Measure a scene's light on each light path against its path-traced reference: distance in stops, the worst tile, flicker and cost. |
| [`raea bench`](bench.md) | Each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets. |
| [`raea world`](world.md) | A frame as one world: its layers, text, 3D parts, camera, shots, clips, cues and lines as entities, queried across media. |
+2 -27
View File
@@ -5,18 +5,13 @@ order: 44
sources: ["apps/make/src/lib.rs", "apps/make/src/status.rs", "apps/make/src/asked.rs", "apps/make/src/plan.rs", "apps/make/src/kit.rs", "apps/make/src/kitout.rs", "apps/make/src/shots.rs", "apps/make/src/floor.rs", "apps/make/src/sheet.rs", "core/brief/src/make.rs", "apps/check/make/src/lib.rs"]
---
`raea make status` reads the job on a project's brief.ts (`make: scene({...})`, `kit({...})`, `shot({...})`, `cut({...})` or `goal({...})` from
`raea make status` reads the job on a project's brief.ts (`make: scene({...})`, `kit({...})` or `shot({...})` from
`raea/brief`) and says what's still missing, from what's on disk and never from what the agent says:
- the kind's deliverables (a scene's three or more stills; a kit's GLB, LOD1 and thumbnail per object, its lineup
and kit.json; a shot's still or move per shot), or the plan's own `deliverables`;
- NOTES.md, ending with a "What the skill got wrong" section;
- each composition the plan names has a render or check newer than it that found no error (the project's record);
- no part is seen closer than its planned detail. An object's `lod` (0 the hero to 4 far; the levels are in
[raea scene](scene.md)) says how large it is planned to be seen, so a grey box or a far backdrop is planned at 3
or 4. A render that shows it two levels finer is an error, held by the line above; one level finer holds the job
until the part is built for that level and replanned, the camera keeps off it, or NOTES.md answers it on a line
with `lod` and its name. `raea scene lod` lists every part;
- a fresh critic (`raea judge --kind KIND`) has judged a round newer than the newest deliverable on the job's own
kind's rubric, and each blocking defect it named is fixed or answered in NOTES.md by its name; once the judge is
calibrated against your eye, two passes in a row as well;
@@ -26,24 +21,6 @@ sources: ["apps/make/src/lib.rs", "apps/make/src/status.rs", "apps/make/src/aske
An answer counts for the sheet it was asked of, matched by the file's bytes, so a sheet rendered again is asked
again.
A goal job (`goal({...})`, what raea.app's `/goal` writes) is any other work: the goal in your words and the rules
that must hold before the agent stops. A `run` rule is a command that must exit 0 in the brief's folder (status runs
it every time, 300 seconds unless its `timeout` says otherwise); a `file` rule is a deliverable; a `says` rule is
words that must be true of the work, judged by a fresh critic that may only read: `raea make judge` asks one
(`--by claude` or `kimi`) and keeps its verdict in review/goal.judge.json, and the rule clears only while that verdict
is no older than the work's newest file. A goal job needs no NOTES.md section and has no render critic.
```ts
make: goal({
goal: "the export plays and the README says how to run it",
rules: [
{ id: "tests", run: "bun test" },
{ id: "export", file: "out/final.mp4" },
{ id: "readme", says: "README.md says how to install and run it, in order" },
],
}),
```
`--plan` writes the gates as check lines under the job's own task in the project's plan.org, keeping the person's
mark (DONE, DROPPED) and their own lines; the Stop hook runs it so.
@@ -98,8 +75,7 @@ raea make lenschart counter_push
## Usage
```sh
raea make status [DIR] [--json] [--plan] (a scene, kit, shot, cut or goal held to its plan, `make` on brief.ts: what's missing, each gate (renders and checks, raea ask's calibrated questions, the critic on the kind's rubric), the judge's rounds, and whether it's done, decided in code; --plan writes the gates as check lines under the job's task in plan.org; the agent's Stop hook holds it there)
raea make judge [DIR] [--by claude|kimi] (a goal job: a fresh critic, which only reads, judges each `says` rule; review/goal.judge.json)
raea make status [DIR] [--json] [--plan] (a scene, kit or shot held to its plan, `make` on brief.ts: what's missing, each gate (renders and checks, raea ask's calibrated questions, the critic on the kind's rubric), the judge's rounds, and whether it's done, decided in code; --plan writes the gates as check lines under the job's task in plan.org; the agent's Stop hook holds it there)
raea make plan [DIR] [--no-review] (the plan stop: review/plan/floor-plan.png, a grey-box blockout from the entrance and its review sheets, comparison.png beside reference 0)
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)
@@ -118,7 +94,6 @@ Headless: it needs nothing running and opens no window. Takes up to 5 arguments
| Flag | Takes | What it does |
| --- | --- | --- |
| `--by` | `claude\|kimi` | The critic `judge` asks, a fresh session that may only read (default `claude`). |
| `--dry` | – | Quote the generation (refs, gen) and make nothing. |
| `--json` | – | Print the status as JSON: missing, gates, judge, done, short and why. |
| `--meshy` | `M` | The Meshy model for `gen` (default `fal:meshy/v7.1/image-to-3d`). |
+2 -13
View File
@@ -12,7 +12,7 @@ Body motion made on this machine by Kimodo (NVIDIA), on MLX on a Mac and on PyTo
## Usage
```sh
raea motion "LINE" [--keys KEYS.json] [--seconds 5 | --frames N] [--seed 1] [--seeds 1] [--steps 100] [-o CLIP.json] (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)
raea motion "LINE" [--keys KEYS.json] [--seconds 5 | --frames N] [--seed 1] [--steps 100] [-o CLIP.json] (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)
```
Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
@@ -21,11 +21,10 @@ Headless: it needs nothing running and opens no window. Takes up to 1 argument b
| Flag | Takes | What it does |
| --- | --- | --- |
| `--frames` | `N` | The clip's length in frames at 30 a second, 2 to 300 (10 s, Kimodo's limit: longer clips drift and break up; chain 10 s clips through `--keys` instead). Instead of `--seconds`. |
| `--frames` | `N` | The clip's length in frames at 30 a second, 2 to 600. Instead of `--seconds`. |
| `--keys` | `KEYS.json` | Kimodo constraints the motion must meet: full-body keyframes, a hand or foot at a place on a frame, a path for the hips. `bun sdk/body/tools/between.ts` writes them between two poses of the body library. |
| `--seconds` | `5` | The clip's length in seconds (5 unless said). |
| `--seed` | `1` | Which of the motions the line could be: another seed is another take of the same line. A seed on MLX is not that seed on PyTorch (the noise is drawn differently), so the same seed is a different take on a Mac and on Linux or Windows. |
| `--seeds` | `1` | How many takes to make, seeds `--seed` up: the one with the lowest score is kept and its score written into the clip (`score`: foot drift while a foot is planted, shoulder rise above the take's usual, hip drop below standing, and how far a hand or forearm goes into the torso or head, in cm, summed over allowances of 1, 3, 5 and 1 cm). The collision is a skeletal check, capsules sized for SOMA's average adult, not the body's mesh. |
| `--steps` | `100` | Denoising steps (Kimodo's 100). Fewer is faster and rougher. |
| `-o` | `CLIP.json` | Where the clip goes: `{fps, names, root, turns, contacts, ...}`, Kimodo's 77 SOMA joints as each one's turn in the world from the T-pose. Without it, the line's words name the file in the working folder. |
@@ -41,16 +40,6 @@ bun sdk/body/tools/between.ts skeleton.json LIBDIR aMale2_A1_Stand:0 aMale2_A1_S
raea motion "A person waves at the camera with their right hand" --keys stand.json --seconds 4 --seed 2 -o wave.clip.json
```
The best of four takes of a line, by the faults a body would show:
```sh
raea motion "A person stands in place and talks, gesturing with both hands" --seconds 10 --seeds 4 -o talk.clip.json
```
Longer than 10 s, make 10 s clips one after another, each with `--keys` holding the last second of the one before as
full-body keyframes, and ease each into the next over those frames: Kimodo keeps full-body keys to a few centimetres,
not exactly, so a clip cut straight onto the next would jump.
A clip takes about 8 seconds on an M5 Pro. `bun sdk/body/tools/makedo.ts` does the whole of it for a stage's lines:
three seeds a line, each checked against the captures the body hands on to, and the one that does the most kept in the
project's made clips.
-48
View File
@@ -1,48 +0,0 @@
---
title: "raea playable"
summary: "Export a game as a playable ad: one page or ZIP for each ad network, under its size cap, from the same TSX that renders as the video ad."
order: 5
sources: ["apps/playable/src/lib.rs"]
---
`raea playable` turns a raea game into a playable ad: a short game served in place of a video ad inside other apps,
ending on a card that opens the store. The same file renders with `raea render` as the video ad, because a game that
nobody touches plays itself. Each network gets the page or ZIP it takes, with its own start, pause and store calls,
checked against its 5 MB cap. Nothing in the page loads anything: pictures, sounds and the 3D renderer travel inside it.
```sh
raea playable game.tsx -o out/playable --ios https://apps.apple.com/app/id123 --android https://play.google.com/store/apps/details?id=com.example
raea playable game.tsx -o out/playable --networks applovin,google,preview --cta "Play free"
```
Before it bundles, the export refuses what a playable can't have: files read from disk at render time (`staticFile`;
import the file instead), URLs and network calls, modules that need the native engine, `<Video>` and `<Audio>`, and 3D
kinds the playable's renderer doesn't draw. It notes a game with only one orientation, and one that never imports
`raea/playable` (`<EndCard>`, `<InstallButton>`, `install()`) to open the store itself.
The 3D is drawn by three.js on raea's scene contract, with Bevy's light units and tone mapping. It comes from the
project (`raea add [email protected]`).
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
## Usage
```sh
raea playable GAME.tsx -o DIR [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both] (a game as a playable ad: one page or ZIP per network (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff, preview), each under its 5 MB cap, from the TSX that renders as the video ad)
```
Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
## Flags
| Flag | Takes | What it does |
| --- | --- | --- |
| `--android` | `URL` | The Google Play page the store tap opens on Android. |
| `--cta` | `TEXT` | The button's words on the host's own end card, `Play now` by default. A game's `<EndCard cta>` sets its own. |
| `--ios` | `URL` | The App Store page the store tap opens on iPhone and iPad. |
| `--networks` | `LIST` | The networks to write, split by commas: `applovin`, `unity`, `google`, `meta`, `moloco`, `mintegral`, `tiktok`, `liftoff`, `preview`. All of them by default. |
| `--orientation` | `portrait\|landscape\|both` | What Google's `ad.orientation` tag and TikTok's `config.json` are told; `both` by default. The game plays whichever of its compositions is nearest the screen's shape either way. |
| `--title` | `TEXT` | The title on the host's own end card, shown at the last frame when the game never shows an `<EndCard>`. |
| `-o` | `DIR` | The folder the pages and ZIPs go in, named GAME-NETWORK.html or .zip. |
<!-- generated:end -->
+1 -1
View File
@@ -1,7 +1,7 @@
---
title: "raea run"
summary: "Run a TypeScript program on the engine, headless, and print what it prints."
order: 9
order: 8
sources: ["engine/cli/src/cli.rs"]
---
+6 -29
View File
@@ -1,8 +1,8 @@
---
title: "raea scene"
summary: "Find floating, sunk and clipping 3D parts, say what each part rests on, meter a shot's light, hold every frame to the stage checks a render runs, and list each part's planned detail beside how large the frames show it."
summary: "Find floating, sunk and clipping 3D parts, say what each part rests on, meter a shot's light, and hold every frame to the stage checks a render runs."
order: 47
sources: ["apps/scene/src/lib.rs", "apps/scene/src/light.rs", "apps/scene/src/stage.rs", "apps/scene/src/lod.rs", "runtime/lod-plan/src/lib.rs", "runtime/lod-plan/src/report.rs", "runtime/lod-plan/src/plan.rs", "systems/stage/src/lib.rs", "systems/stage/src/clearance.rs", "systems/contact/src/lint.rs", "systems/contact/src/zfight.rs"]
sources: ["apps/scene/src/lib.rs", "apps/scene/src/light.rs", "apps/scene/src/stage.rs", "systems/stage/src/lib.rs", "systems/stage/src/clearance.rs", "systems/contact/src/lint.rs", "systems/contact/src/zfight.rs"]
---
`raea scene` steps a composition's frames and measures its 3D scene without rendering pictures. `lint` reports
@@ -21,28 +21,6 @@ also holds the camera M metres off every solid part on every frame (0.45 for a c
part it comes closer to, the frames and the nearest it gets, or that it's inside the part. Glass, decals, volumes and
parts under 5 cm are passed over.
`lod` lists every part's planned detail beside what the frames show. A part's plan is how large it is meant to be
seen, which is how much of it gets built:
| lod | for | across the frame |
| --- | --- | --- |
| 0 | the hero | 50% or more |
| 1 | featured | 20% to 50% |
| 2 | set dressing | 8% to 20% |
| 3 | background: a grey box reads | 2% to 8% |
| 4 | far: a silhouette | under 2% |
The plan is the part's own `lod` prop (`<Mesh3d lod={3}>`, `<Model lod={4}>`, or a parent `<Entity transform lod>`
or `<Group lod>` for every part inside), else the `lod` of the object with the part's name in the job's plan (`make`
on the brief.ts above the composition). What a frame shows is how much of it the part's box spans through that
frame's camera, the larger of its width's and its height's share. The table puts parts seen closer than planned
first, then the rest of the planned parts, 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. Under it: each `lod-closer` finding, and any level the plan
gives a name that no part in the frames goes by. A part seen one level finer than planned is a warning; two or more
is an error, and `lod` exits 1. `raea render`, `raea scene stage` and `raea check --quick` say the same finding, and
`raea make status` holds a job at it. A part hidden behind other meshes isn't counted as seen; RAEA_LOD_CHECK=0
leaves the check out of a render.
```sh
raea scene lint room.tsx
raea scene explain room.tsx --frame 90 --json
@@ -50,7 +28,6 @@ raea scene light room.tsx --part hero
raea scene light film.tsx --composition shot1,shot2,shot3 # the light across the cuts
raea scene stage film.tsx --from 1800 --to 2400 # the stage checks on 20 s of it
raea scene stage walk.tsx --clearance 0.45 # and the camera kept off the set
raea scene lod walk.tsx # every part's planned detail against the frames
```
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
@@ -59,7 +36,7 @@ raea scene lod walk.tsx # every part's pl
```sh
raea scene export EDIT.tsx -o DIR [--composition ID] [--frame N | --at A-B] (the composition's 3D as data other tools build: DIR/scene.json, each part placed (y up, metres) with its shape, material or light, and the camera; meshes/ and models/ beside it)
raea scene lint|explain|light|stage|lod EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--json] (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)
raea scene lint|explain|light|stage EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--json] (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)
```
Headless: it needs nothing running and opens no window. Takes up to 2 arguments besides its flags.
@@ -72,10 +49,10 @@ Headless: it needs nothing running and opens no window. Takes up to 2 arguments
| `--clearance` | `M` | `stage`: every run of frames where the camera is nearer a solid part than M metres (0.45 carried, 0.15 on a rig). |
| `--composition` | `ID` | Which composition to measure. `light` takes several, comma-separated, to compare the light across their cuts. |
| `--frame` | `N` | The frame to measure (0 by default; `light` also takes `last`). |
| `--from` | `N` | With `stage` and `lod`: the first frame held to the checks (0 when left out). Every frame before it is still stepped, so a scene that builds over time is as it would render. |
| `--json` | – | Print as JSON: `lint` its findings (check, level, the parts they are about, frames, says, measure, fix), `explain` every part with its support, gap and box, `lod` every part's row (planned, seen, largest, at, frames, closer), the plan's names no part goes by, and its findings. |
| `--from` | `N` | With `stage`: the first frame held to the checks (0 when left out). Every frame before it is still stepped, so a scene that builds over time is as it would render. |
| `--json` | – | Print as JSON: `lint` its findings (check, level, the parts they are about, frames, says, measure, fix), `explain` every part with its support, gap and box. |
| `--part` | `NAME` | With `light`: the part to meter, in place of the shot's subject. |
| `--to` | `N` | With `stage` and `lod`: the last frame held to the checks (the composition's last when left out). |
| `--to` | `N` | With `stage`: the last frame held to the checks (the composition's last when left out). |
| `-o` | `DIR` | `export`: the folder scene.json is written to, with meshes/ and models/ beside it. |
<!-- generated:end -->
+1 -1
View File
@@ -51,7 +51,7 @@ raea show out/cut-v2.mp4 --replaces i-show-2f9c --done c-3 --done c-4 --note "Wa
## Usage
```sh
raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --label "PLACE TAG" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)
raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), or questions, all of them one item; --label "PLACE TAG" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)
```
Needs the raea app's host running on this machine; then waits for a person's click in the raea app (to answer). Takes any number of arguments besides its flags.
+1 -1
View File
@@ -24,7 +24,7 @@ Headless: it needs nothing running and opens no window. Takes up to 2 arguments
| `--duplex` | – | Listen all the time, with nothing taken out of the microphone's sound. For headphones: through speakers it hears itself and stops. |
| `--fast` | – | With `--from`: read the recording as fast as it can be heard, not at the pace it was spoken. For tests. |
| `--from` | `IN.wav` | A recording in the microphone's place. |
| `--over` | – | Listen while it speaks, with its own voice taken out of the microphone's sound, so the person can talk over it through speakers. Experimental, and raea.app doesn't use it. It works in a simulated room. In the one real room it was tried in (a wireless USB microphone and a Mac mini's speakers, 11-25) its own voice was never taken out well enough to be sure of, so nobody could talk over it and it behaved as without the flag: it never stopped itself by mistake either. |
| `--over` | – | Listen while it speaks, with its own voice taken out of the microphone's sound, so the person can talk over it through speakers. New: checked in a simulated room, not yet across real rooms. The first word or two said over it can be lost. |
| `--pause` | `MS` | How long a silence ends the person's turn, in milliseconds. |
| `--room` | `GAIN` | With `--from` and `--over`: a simulated room. What it says comes back into the recording at this gain (0.5 is a quiet room, 1.5 a loud one). |
| `--to` | `OUT.wav` | A file in the speakers' place: everything it says is written there. |
-3
View File
@@ -279,7 +279,6 @@ hand-written element.
| `scale` | `Vec3 \| number` | one number, or x, y and z |
| `transform` | `{ translation?: Vec3; rotation?: [number, number, number, number]; scale?: Vec3 }` | Bevy's Transform (Transform.fromXyz(..).withRotation(..)), in place of position, rotation and scale: the entity is then a parent whose children (meshes, lights, models, other entities) move with it, as Bevy's ChildOf children do (the old Group) |
| `pass` | `string` | with `transform`: the composition pass of every part inside that doesn't name its own (Mesh's `pass`) |
| `lod` | `PlannedLod` | with `transform`: the planned detail of every part inside that plans none of its own, 0 (the hero) to 4 (far) |
| `children` | `ReactNode` | its Bevy components (<BevyComponent>, or the generated wrappers in raea/bevy-own); with `transform`, also the parts it carries |
Used in: [ui/widgets/viewport_node](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/widgets/viewport_node.tsx), [3d/3d_shapes](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/3d/3d_shapes.tsx), [3d/atmospheric_fog](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/3d/atmospheric_fog.tsx), [3d/3d_scene](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/3d/3d_scene.tsx), [3d/parenting](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/3d/parenting.tsx), [stress_tests/many_foxes](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/stress_tests/many_foxes.tsx), [camera/projection_zoom](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/camera/projection_zoom.tsx), [animation/animated_transform](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/animation/animated_transform.tsx), and 5 more.
@@ -555,7 +554,6 @@ Bevy: `bevy_pbr::mesh_material::MeshMaterial3d<raea_render::engine::look::LookMa
| `scale` | `number \| Vec3` | one number, or x, y and z |
| `allowOverlap` | `boolean` | it may pass through other parts on purpose (a blade into a body, a ghost through a wall): raea's clipping check leaves it out |
| `posed` | `boolean` | set at an angle on purpose (a bowl knocked over, a mug on its side): `raea scene lint` doesn't call it tilted |
| `floating` | `boolean` | it hangs in the air on purpose, touching nothing (a balloon, a sign on wires that aren't modelled): `raea scene lint` doesn't call it left in the air |
| `animation` | `string \| number` | a clip to play: its name in the file, or its index |
| `screens` | `ModelScreens` | live pictures on its materials, by the glTF material's name: `{ monitor_screen: <Screen resolution={[384, 272]}> <Game /></Screen> }` (or a bare `<Game />` for the defaults). Each mesh with that material shows the screen, the picture fitted to the mesh's texture coordinates and stood upright |
| `hide` | `string[]` | nodes of the glTF hidden, by name (a robot's painted-on eyes under the screen that replaces them) |
@@ -571,7 +569,6 @@ Bevy: `bevy_pbr::mesh_material::MeshMaterial3d<raea_render::engine::look::LookMa
| `flat` | `boolean` | its surfaces without light: shape and colour alone, like a drawing (the site look keeps the light: its grain is made of it) |
| `shadow` | `boolean` | false: its meshes cast no shadow (true by default) |
| `detail` | `Detail` | where it's drawn: its distances or sizes on screen, cross-faded, and its shadow (Detail; raea-sys-lod) |
| `lod` | `PlannedLod` | its planned detail, 0 (the hero) to 4 (far): how large it is meant to be seen. A render that shows it finer says so (`lod-closer`); a stand-in or a far backdrop is planned at 3 or 4 (PlannedLod) |
| `receiveShadow` | `boolean` | false: no shadow falls on its meshes, its own included (true by default): a furry coat of many cards that would otherwise speckle itself in the shadow maps |
| `pixelSize` | `number` | a cell's size in frame pixels for the pixel and site looks (6 by default) |
| `edgeColor` | `string` | the pixel look's one-cell outline, a hex colour ("#000000" by default), or "none" |
+3 -69
View File
@@ -30,10 +30,10 @@ See [Workspaces and projects](../../concepts/workspaces.md) for where each spec
<!-- generated:begin by tools/manual-ref/sdk.ts from the SDK's exports and doc comments; edit outside this block -->
```ts
import { brief, cut, fingerprint, goal } from "raea/brief"
import { brief, fingerprint, kit, parts } from "raea/brief"
```
`raea/brief` exports 10 functions, 42 types. Source: [sdk/raea/src/brief.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/brief.ts).
`raea/brief` exports 8 functions, 34 types. Source: [sdk/raea/src/brief.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/brief.ts).
## Functions
@@ -46,14 +46,6 @@ the project's plan.org.
function brief(b: Brief): Brief
```
### `cut`
ads cut from footage to a client's brief: `cut: {...}` is the brief as rules, each quoting it
```ts
function cut(m: Omit<Make, "kind">): Make
```
### `fingerprint`
A fingerprint (fingerprint.ts): its axes and the encoders its heads were trained on.
@@ -62,16 +54,6 @@ A fingerprint (fingerprint.ts): its axes and the encoders its heads were trained
function fingerprint(f: Fingerprint): Fingerprint
```
### `goal`
any other work held to a goal (`/goal`): the goal in the person's words and the rules that must hold before the agent
stops, each a command that must pass (`run`), a file that must exist (`file`) or words a fresh critic judges
(`says`, by `raea make judge`). `raea make status` holds the agent to every one.
```ts
function goal({ goal, rules, ...m }: MakeGoal & Omit<Make, "kind" | "goal">): Make
```
### `kit`
A kit: props in one style at real size (`style` is the paragraph every reference carries: era, palette, materials,
@@ -223,24 +205,6 @@ type Line = { /** * a character, or "narrator" */ who: string, says: string, /**
type Make = { kind: MakeKind, /** * the pictures the job answers to (paths beside the brief): what is in it and where for a scene, the style for a kit */ references?: Array<string>, /** * one paragraph every reference prompt carries: era, palette, materials, wear, and one fictional maker */ style?: string, /…
```
### `MakeCta`
```ts
type MakeCta = { text: string, from: string, /** * how near the end it must land, in seconds (8 when left out) */ within?: number, }
```
### `MakeCut`
```ts
type MakeCut = { /** * the brief as text, relative to brief.ts (`pdftotext -layout brief.pdf media/brief.txt`): every `from` is found in it */ brief: string, /** * how many cuts the brief asks for; fewer planned is held open until an answered `open` item about "count" says why */ count?: MakeQuoted<number>, /**…
```
### `MakeCutPlan`
```ts
type MakeCutPlan = { /** * [a-z0-9_], unique: each format lands as out/cuts/<id>_<W>x<H>.mp4 ("a1_s1_9x16.mp4") */ id: string, angle?: string, /** * solo or mashup */ kind?: string, /** * one of the brief's hook types ("Direct Problem", "Reaction") */ hook?: string, /** * captions, hook (a text hook) or none */ tex…
```
### `MakeDial`
```ts
@@ -253,22 +217,10 @@ type MakeDial = MakeDialValue | { value: MakeDialValue, source?: MakeSource, /**
type MakeDialValue = number | string
```
### `MakeGoal`
```ts
type MakeGoal = { /** * the goal as the person said it */ goal: string, /** * what must hold before the agent may stop: every one, each checked in code or by a fresh critic */ rules?: Array<MakeGoalRule>, }
```
### `MakeGoalRule`
```ts
type MakeGoalRule = { /** * a short name: [a-z0-9_], how status, the critic and NOTES.md name it */ id: string, /** * a command that must exit 0, run in the brief's folder (`bun test`, `raea check edit.tsx`) */ run?: string, /** * the seconds `run` gets before it counts as failed (300 when left out) */ timeout?: num…
```
### `MakeKind`
```ts
type MakeKind = "scene" | "kit" | "shot" | "cut" | "goal"
type MakeKind = "scene" | "kit" | "shot"
```
### `MakeObject`
@@ -277,36 +229,18 @@ type MakeKind = "scene" | "kit" | "shot" | "cut" | "goal"
type MakeObject = { /** * snake_case, unique in the job */ id: string, label: string, /** * real height in metres */ h?: number, /** * [width, depth, height] in metres, for boxy things (generators invent depth) */ dims?: [number, number, number], /** * largest extent in metres, for things that lie flat (tools, pap…
```
### `MakeOpen`
```ts
type MakeOpen = { question: string, from: string, /** * what it decides: "count", "cta", "offer", a cut's id... */ about?: string, /** * the person's answer, as they gave it, and who gave it: until then the job can't be done */ answer?: string, by?: string, }
```
### `MakeOrigin`
```ts
type MakeOrigin = "reference" | "invented"
```
### `MakePhrase`
```ts
type MakePhrase = { /** * as it's said or shown; compared in lower case, by letters and digits ("24/7" and "24-7" are the same) */ text: string, from: string, /** * `say` only: false when one cut saying it is enough */ every?: boolean, }
```
### `MakePick`
```ts
type MakePick = { /** * "tripo-h31", "meshy", ... */ generator: string, /** * one line: why this one ("sharper dial numerals; Tripo fused the handset to the cradle") */ why: string, }
```
### `MakeQuoted`
```ts
type MakeQuoted = { value: T, /** * the brief's own words, as they are in its text */ from: string, }
```
### `MakeRoute`
```ts
+1 -1
View File
@@ -33,7 +33,7 @@ The composition, the app, and the specs and notes an agent writes.
| --- | --- | --- |
| [`raea`](raea.md) | The main entry: compositions, sequences, time, interpolation, springs, footage, sound and words. | 21 components, 9 hooks, 65 functions, 11 values, 109 types |
| [`raea/app`](app.md) | The App, its plugins and schedules, and the registry a video's compositions are kept in. | 1 component, 1 hook, 5 functions, 3 classes, 17 values, 18 types |
| [`raea/brief`](brief.md) | The specs an agent writes as data: brief, script, taste and an object's parts, checked against raea's schemas. | 10 functions, 42 types |
| [`raea/brief`](brief.md) | The specs an agent writes as data: brief, script, taste and an object's parts, checked against raea's schemas. | 8 functions, 34 types |
| [`raea/note`](note.md) | A person's note as a file in the project: their words kept as written, and the asks the agent restates it as. | 1 function, 4 types |
## Time and motion
-5
View File
@@ -207,8 +207,6 @@ raster-lit: Bevy 0.20's Solari can't trace it, unless `dynamic` gives a skinned
| `primarySamples` | `number` | direct light samples at the camera's first hit, a pixel a frame (Bevy's 8). After MetalFX's denoiser 4 bought the window scene nothing over 8 and saved 1.5 ms at 1080p's pixels |
| `secondarySamples` | `number` | direct light samples at each bounce (Bevy's 4) |
| `firstBounce` | `number` | the chance a pixel traces its first bounce this frame, its light divided by it (Russian roulette): 0.5 halves the bounce's tracing, most of a dense forest's (1, every pixel every frame) |
| `paths` | `number` | initial paths a pixel a frame (1 to 16, 1 by default): N cut the noise of one path N times, at N times its rays. A sunlit room seen through bounces (MALL RAT's court) needs 4 or more to hold still |
| `firefly` | `number` | the firefly filter: a sample over this many times the mean of its 8x8 pixels is cut back to that after temporal reuse (off by default; 2 and up). One very bright sample otherwise lingers and spreads: a patch jumps brighter and takes a second to fall back. Lower holds stiller and loses more light (a room lit by small bulbs: 6 holds still and reads 0.3 stops darker, 12 half of both; 32 loses nothing and gains little) |
| `cache` | `{ /** frames a cell's light is gathered over: steadier and slower to follow a change (B…` | Solari's world cache, the bounce light it keeps in cells across the scene |
| `scale` | `number` | draw the view at this fraction of its size a side (a third to 1) and let MetalFX's temporal scaler bring it up to the full size, so a game traces fewer pixels: 0.67 traces 45% of them. On the Mac; elsewhere it draws at the full size and raea says so. 1 (or left out): the full size; RAEA_SOLARI_SCALE overrides it |
| `denoise` | `boolean` | MetalFX's temporal denoiser on the lighting. false shows Solari's raw noise. Default true; RAEA_SOLARI_DENOISE=0 overrides it |
@@ -217,14 +215,11 @@ raster-lit: Bevy 0.20's Solari can't trace it, unless `dynamic` gives a skinned
| `emissive` | `"taa" \| "split" \| "mask"` | an emissive surface's own light: "taa" taken out before the denoiser and gathered over frames (RT11, RT32), "split" each frame's alone, "mask" left in for the denoiser. Default "taa"; RAEA_SOLARI_EMISSIVE overrides it |
| `upscale` | `"one" \| "two"` | a view drawn small (scale below 1): denoised and brought up in "one" pass, or denoised small and scaled in "two". Default "one"; RAEA_SOLARI_UPSCALE overrides it |
| `preexposure` | `number` | what MetalFX divides the light by before it denoises and multiplies it by after. Higher keeps more of a rare bright sample (a lamp found by one path in many) and lets more fireflies through: 1 kept 0.74 of the desk's light, 16 0.86, 64 0.91. Default 16; RAEA_METALFX_PREEXPOSURE overrides it |
| `knee` | `number` | where the denoiser's soft knee starts, in its white (1 by default; 0 off). Light above it is denoised as its log and restored after, so a silhouette against bright sky or a lit doorway doesn't step with the camera's jitter. RAEA_METALFX_KNEE overrides it |
| `late` | `boolean` | denoise after the forward meshes and the sky, so their edges are gathered over frames too instead of stepping with the camera's jitter. RAEA_SOLARI_DENOISE_LATE overrides it |
| `aa` | `boolean` | jitter a full-size view too, so the denoiser anti-aliases its edges as it gathers frames. Default true; RAEA_SOLARI_AA=0 overrides it |
| `jitter` | `"denoiser" \| "scaler" \| "both" \| "flip" \| "none"` | which of MetalFX's passes is told the camera's jitter: "denoiser", "scaler", "both", "flip" (the denoiser, negated), "none" (and the view isn't jittered). For A/Bs of RT9; default "denoiser"; RAEA_SOLARI_JITTER ("" the denoiser, "0" none) overrides it |
| `emissiveSharpness` | `number` | how fast a sample's weight falls with its distance from a pixel's centre in the emission's history, exp(-k d²) in output pixels: lower is softer. Default 6; RAEA_EMIT_TAA_SHARP overrides it |
| `jitterFrames` | `number` | the jitter's cycle at the full size, in frames: a view drawn at s of its size a side cycles through jitterFrames / s² offsets, and an emissive twig glimpsed through it may stay away that long. Default 8 (DLSS's) |
| `dynamic` | `boolean` | the traced scene follows what moves (a trial, false by default): a skinned character's traced twin is posed each frame, so it casts traced shadows and bounces light. Decided as each mesh is first traced, so set it from the first frame. (A hidden part, or one a frame leaves out, leaves the traced scene with or without it.) |
| `overscan` | `number` | overscan (off by default): the view is traced this much wider on every side (0.05 is a twentieth of its width and height) and the middle cropped back out, so the frame's border has light to gather from as the camera moves. For a moving shot whose edges crawl (`raea light steady` passing everywhere but the border). It costs (1 + 2 x overscan)² the tracing, the picture is drawn at 1 / (1 + 2 x overscan) of its size at most and brought up, and depth of field, motion blur and `--aov` read the wider view. Mac only (it rides MetalFX's denoiser) |
| `constants` | `{ /** how far ReSTIR looks for a neighbour's light samples, pixels (30): smaller keeps …` | constants in Solari's and the denoiser's shaders, compiled in when the scene loads (a value changed later in the composition isn't drawn); each left out keeps the shader's own, given in brackets. <ShaderConstants> reaches the rest |
### `SpotLight`
+3 -3
View File
@@ -114,7 +114,7 @@ One part, so a curve that grows is solid at every frame (never a chain of parts:
| `normal` | `Vec3` | the way its face looks: the normal of the plane it lies in (left out: the plane of its points, else +z) |
| `children` | `ReactNode` | its material (a white StandardMaterial when left out) |
Also takes the props of `MeshProps` (`animate`, `name`, `read`, `pass`, `quaternion`, `allowOverlap`, `posed`, `floating`, `lod`, `shape`, `driven`, `shadow`, `material`, `castShadow`, `surface`, `receiveShadow`, `attributes`, `compressed`, `layers`); `PointerHandlers3d` (`onClick`, `onDrag`, `onDragEnd`, `onDragEnter`, `onDragLeave`, `onDragOver`, `onDragStart`, `onDrop`, `onPointerDown`, `onPointerMove`, `onPointerUp`, `onPointerEnter`, `onPointerLeave`, `onPointerOver`, `onPointerOut`, `onWheel`); [`Mesh3dProps`](#mesh3dprops) (`visibility`, `transform`, `detail`).
Also takes the props of `MeshProps` (`animate`, `name`, `read`, `pass`, `quaternion`, `allowOverlap`, `posed`, `shape`, `driven`, `shadow`, `material`, `castShadow`, `surface`, `receiveShadow`, `attributes`, `compressed`, `layers`); `PointerHandlers3d` (`onClick`, `onDrag`, `onDragEnd`, `onDragEnter`, `onDragLeave`, `onDragOver`, `onDragStart`, `onDrop`, `onPointerDown`, `onPointerMove`, `onPointerUp`, `onPointerEnter`, `onPointerLeave`, `onPointerOver`, `onPointerOut`, `onWheel`); [`Mesh3dProps`](#mesh3dprops) (`visibility`, `transform`, `detail`).
### `Mesh2d`
@@ -139,7 +139,7 @@ shadow="only" draws it with the shadow-only material (engine/render shadow_only.
| `detail` | `Detail` | where it's drawn: its distances or sizes on screen, cross-faded, and its shadow (Detail; raea-sys-lod) |
| `children` | `ReactNode` | its material and child entities |
Also takes the props of `MeshProps` (`animate`, `name`, `read`, `pass`, `quaternion`, `allowOverlap`, `posed`, `floating`, `lod`, `shape`, `driven`, `shadow`, `material`, `castShadow`, `surface`, `receiveShadow`, `attributes`, `compressed`, `layers`); `PointerHandlers3d` (`onClick`, `onDrag`, `onDragEnd`, `onDragEnter`, `onDragLeave`, `onDragOver`, `onDragStart`, `onDrop`, `onPointerDown`, `onPointerMove`, `onPointerUp`, `onPointerEnter`, `onPointerLeave`, `onPointerOver`, `onPointerOut`, `onWheel`).
Also takes the props of `MeshProps` (`animate`, `name`, `read`, `pass`, `quaternion`, `allowOverlap`, `posed`, `shape`, `driven`, `shadow`, `material`, `castShadow`, `surface`, `receiveShadow`, `attributes`, `compressed`, `layers`); `PointerHandlers3d` (`onClick`, `onDrag`, `onDragEnd`, `onDragEnter`, `onDragLeave`, `onDragOver`, `onDragStart`, `onDrop`, `onPointerDown`, `onPointerMove`, `onPointerUp`, `onPointerEnter`, `onPointerLeave`, `onPointerOver`, `onPointerOut`, `onWheel`).
Used in: [ui/render_ui_to_texture](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/render_ui_to_texture.tsx), [ui/widgets/viewport_node](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/widgets/viewport_node.tsx), [3d/fog](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/3d/fog.tsx), [3d/vertex_colors](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/3d/vertex_colors.tsx), [3d/rotate_environment_map](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/3d/rotate_environment_map.tsx), [3d/transparency_3d](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/3d/transparency_3d.tsx), [3d/spherical_area_lights](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/3d/spherical_area_lights.tsx), [3d/animated_material](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/3d/animated_material.tsx), and 54 more.
@@ -181,7 +181,7 @@ A line through points in 3D with a round section (a pipe, a wire): one mesh, dra
| `radius` | `number` | its radius in metres (0.025) |
| `sides` | `number` | sides around its section (12) |
Also takes the props of `MeshProps` (`animate`, `name`, `read`, `pass`, `quaternion`, `allowOverlap`, `posed`, `floating`, `lod`, `shape`, `driven`, `shadow`, `material`, `castShadow`, `surface`, `receiveShadow`, `attributes`, `compressed`, `layers`); `PointerHandlers3d` (`onClick`, `onDrag`, `onDragEnd`, `onDragEnter`, `onDragLeave`, `onDragOver`, `onDragStart`, `onDrop`, `onPointerDown`, `onPointerMove`, `onPointerUp`, `onPointerEnter`, `onPointerLeave`, `onPointerOver`, `onPointerOut`, `onWheel`); [`Mesh3dProps`](#mesh3dprops) (`visibility`, `transform`, `detail`).
Also takes the props of `MeshProps` (`animate`, `name`, `read`, `pass`, `quaternion`, `allowOverlap`, `posed`, `shape`, `driven`, `shadow`, `material`, `castShadow`, `surface`, `receiveShadow`, `attributes`, `compressed`, `layers`); `PointerHandlers3d` (`onClick`, `onDrag`, `onDragEnd`, `onDragEnter`, `onDragLeave`, `onDragOver`, `onDragStart`, `onDrop`, `onPointerDown`, `onPointerMove`, `onPointerUp`, `onPointerEnter`, `onPointerLeave`, `onPointerOver`, `onPointerOut`, `onWheel`); [`Mesh3dProps`](#mesh3dprops) (`visibility`, `transform`, `detail`).
## Functions
-170
View File
@@ -1,170 +0,0 @@
---
title: "raea 0.1.10"
version: "0.1.10"
date: "2026-11-26"
summary: "The app is raea cloud on your own computer, in the system's own window on the Mac, Windows and Linux. Publishing is a project's delivery, raea make holds a 3D scene to its plan, Solari's light boils less, and a long 3D film renders whole with each frame's own light."
sources: ["https://github.com/shinyobjectz/raea/releases/tag/v0.1.10"]
---
raea 0.1.10 makes the app raea cloud on your own computer. It is the same dashboard, with projects that run here on
the AI you already use, in the system's own window on the Mac, Windows and Linux. A finished video is published from
its project. In the engine, `raea make` holds a 3D scene, kit or shot to its plan until every check passes, Solari's
light boils less and can be measured holding still, and a long 3D film that switches scenes renders whole with the
same light as each frame alone.
**Get the app at [raea.io](https://raea.io)** (a Mac with Apple silicon, Windows 10 or 11, or Linux on x86_64).
The engine alone:
```sh
curl -fsSL https://raea.io/install | sh
```
On Windows, in PowerShell: `irm https://raea.io/install.ps1 | iex`.
## What changed since 0.1.9
### In the app
**The app is laid out like raea cloud.** Its rail is Inbox, Projects, Agents, Workflows, Libraries and Fingerprints,
with your workspace above New, and Connections and Settings at the foot. Projects you start run on this computer, in a
raea cloud of its own, on the AI you already use: Claude Code unless you pick another in Settings → General. Cloud
workspaces sit in the same menu once you sign in. The first time it opens, the welcome and sign-in come first, then
your projects, agents, library and fingerprints from the earlier app move in. The files are cloned, not copied, and the
old folders are only read.
**In the system's own window.** The app now draws in the webview each system already has: WebKit on the Mac, WebView2
on Windows and WebKitGTK on Linux. Links open in your browser, Copy reaches the clipboard, the folder chooser is the
system's own on every system, and a `raea://` link brings the running app forward on Windows and Linux as on the Mac.
**Publishing is a project's delivery.** A workflow can end in a post: pick the accounts it posts to in its editor. When
a project delivers its video, it waits in Needs you at Publish, with the caption its agent wrote and the account it
goes to. Change the caption if you like, press Publish, and the project shows "Published" with the post's views once
the network answers. On a plan that doesn't publish, Publish says which plan does and the project stays where it was.
The separate Publishing page is gone.
**Ask a workflow to change.** In a workflow's editor, say what you want ("add a legal review before it posts") and
your AI changes the workflow. When it needs to know more, it asks first.
**Agents and chats are one place.** Each agent is listed with its conversations under it, the busiest first. Click an
agent to start a new chat with it, or its gear for its settings.
**The Inbox counts what you haven't seen.** Its number drops as cards come into view, and colour is kept for what needs
you: what's running, done or stopped is grey.
**Projects belong to clients.** As in raea cloud, a project is filed under its client, and the client's board gathers
its projects. Projects from the earlier app that sat inside another one join its client. In a terminal,
`raea project new NAME --client CLIENT` names one, and `raea project tag --client CLIENT` changes it.
**`raea show` waits in your Inbox.** What an agent shows you from a terminal session is a card waiting for you, with
its files, filed under its project's client. Your approval, or your notes and comments, go back to the session that
asked.
**Mark up a picture.** The editor's picture toolbar has Pen (P), Arrow (A) and Box (B) beside Comment, in red, yellow
or white, with Undo.
**A review link for work done here.** On Pro and Studio, a project in a workspace on this computer can hand out one of
raea's review links for what it delivered.
**Ideate's voice is your raea plan's.** Talking an idea through in Ideate uses your plan's voice minutes: 30 a month on
Pro, 300 on Studio, and no limit on Enterprise.
**Choose where your work is kept.** Settings → General → Where raea keeps your work: pick a folder on any drive, and from the next
start raea keeps your work there, once what's already there has been copied and counted. The old folder stays as it
was (#233).
**Light and dark.** The app follows your system, or stays light or dark: Settings → General → Theme.
### In the engine
**raea make.** `raea make status` holds a 3D scene, kit or shot written as `make` in a `brief.ts` to its plan: what's
missing, each gate (its renders and checks, and raea ask's questions), and whether it's done. An agent's turn can't
end until it is. Around it: `raea make plan` draws the floor plan and a grey-box blockout to review first, `raea make
refs` makes every object's reference in one style, kits land as a component set with a lineup, and shots come from
words or a path through the floor plan. A client's brief can be its rules (`make: cut({...})`), and each object and
part can name its planned detail, from `lod={0}` (the hero) to `lod={4}` (far away), checked against how big it is on
the frame.
**Solari's light boils less.** `<SolariLighting paths={N}>` starts N paths a pixel and merges them, which cuts the
crawling patches on sunlit floors and reflections in held interiors by nearly half. `firefly={6}` cuts back a bright
sample that stands far above its neighbours, and `overscan={0.05}` traces a little past the frame's edge so its border
lights like its middle (on the Mac, where it rides the denoiser). Both are off unless set.
**Light you can measure holding still.** `raea render --hold FRAME` draws one frame again and again, and
`raea light steady` says whether its light holds still, and if not, how it moves: settling, boiling, jitter or flicker.
`raea light check` runs it on every traced scene.
**A 3D film renders whole.** In 0.1.9 a long film that switched scenes under Solari could draw its later shots darker
than the same frames rendered alone: a part a scene had left stayed in the traced scene and kept shading the next one.
It leaves now, and a film rendered whole matches each frame alone.
**raea render and raea scene check more.**
- Words in the world that sit behind a part, so a viewer can't read them, are an error that names the part in front.
Text3D is checked as RichText is.
- A part a `<Label>` points at is the shot's subject: cutting it off at the frame's edge is an error.
- A part left in the air touching nothing is an error in `raea scene lint`, unless it's marked `floating`.
- A render whose shader didn't compile ends on an error, where before the frame came out without that pass.
- `raea check`'s contrast reads a moving text where it is on its middle frame, not where it ends (#236).
**raea fix.** `raea fix "the error text"` looks a problem up before it's guessed at: what others found and did about
the same symptom.
**raea/story.** A story as a typed program instead of a document: a premise, the values at stake, a cast with wants
and needs, who knows what and when, and beats that each turn a value. It reads a story through twelve lenses (McKee,
the Pixar spine, Campbell, Storynomics and others, plus a launch lens for product films), samples new stories from a
seed, compiles to a `script.ts`, storylets, Ink or Yarn, and `raea check` holds a script's scenes to their beats.
Measured against plain prompts, it works best as the editor of a draft rather than as the language a first draft is
written in.
**New in raea render and raea media.**
- `raea render --props JSON|FILE.json` hands a composition its inputs (`getInputProps()`), and `calculateMetadata` on
a `<Composition>` sets its size and length from them (#176).
- `raea render --scale S` draws a composition at S times its size: 0.5 for a quick look, 2 for a bigger master (#175).
- `raea media share FILE -o OUT.mp4` makes the copy to send: any player takes it, and it's held to a bitrate (#219).
**The engine as a Linux AppImage.** Each release also carries `raea-VERSION-linux-x86_64.AppImage` and its checksum:
make it executable and run it as `raea` (#226). The project has a [code of conduct](https://github.com/shinyobjectz/raea/blob/main/CODE_OF_CONDUCT.md) too
(#228).
**Fixes.**
- On Windows, a long chat scrolled in jerks, on fast graphics cards too (#215). In the system's own window a chat of
160 turns scrolls at the display's rate, with or without the graphics card.
- Two paint bugs, each held to what Chrome draws: a box behind a word with `z-index: -1` covered the word (#241), and
a rounded rectangle's stroke could draw a bar across the page from its left edge at some widths (#240).
- An Opus file couldn't be read back on Linux and Windows (#242).
- A failing audio device printed its error on every callback, and on Linux the app's log reached 40 GB in two days.
The error is said once, then how often it came back, and the app's log is kept to two files of 32 MB (#239).
- An `<R3F>` over another layer cut a box out of the layer under it. The layer shows around the scene now (#235).
- A WebM with alpha that another tool had remuxed drew opaque. Its alpha is read whatever the tag's case (#224).
- `<Mix lufs>` could land a decibel off its target with flat-topped peaks. It lands on the target (#220).
- `raea sounds get` of a second instrument into one folder replaced the first one's notes and licence. Each
instrument keeps its own folder (#217).
- `raea media sheet $FILES` in zsh, which passes every name as one argument, failed with "File name too long" (#218).
- A song's bars are the same on every platform: a 12 ms difference between decoders moved them (#49).
- A 3D scene with thousands of parts re-sent every part each frame. Parts whose props didn't change are skipped:
a 3000-part scene went from 103 to 78 ms a frame (#160).
- On Linux, signing in failed with "spawn /usr/bin/security ENOENT". The app keeps the sign-in in the desktop's
keyring, or in a file only you can read where there is none (#216, #222).
- `staticFile` from a composition in `compositions/` finds the project's `assets/`.
- A composition with the word "import" in a comment above its imports failed before its first frame with "Can't find
variable: raea". It renders.
- A still of a page (`raea render --frame N`, or `--at` that doesn't start at 0) drew its CSS animations from the
wrong time, so every animation showed its first keyframe. Each now runs from the composition's start, or from its
own `<Sequence>`'s, as in the video.
**Known**
- On Linux, raea needs a processor with AVX (most from 2011 on) and glibc 2.39 or newer (Ubuntu 24.04, Debian 13,
Fedora 40 and later).
- On Windows, TokenSynth runs on the CPU, so each note takes a minute or more to make.
- A CSS transition that a style change starts depends on the frames before it, so a still of that frame shows it
finished. Animate with `@keyframes` or `interpolate` for a still that matches the video.
- A seek while a film plays in the timeline can show one frame from before the seek (about 33 ms) before it jumps.
- Characters (the Character SDK) come in a later release.
- R3F's pointer input has no double click yet, and touches don't arrive as pointers.
- postprocessing's Outline, TextureEffect, DepthEffect and LUT1D, and TSL's OutlineNode, are skipped, with one
warning that names them.
- On a long held shot of an interior, Solari's light can still crawl in a few patches, most along the frame's edge.
`raea light steady` shows where; `<SolariLighting overscan={0.05}>` lights the edge as it lights the middle (Mac
only, about 1.2 times the tracing).
- The Windows app and engine are unsigned, as before: Windows asks once whether to run them, and with Smart App
Control on, the engine can't bundle a composition (#221).
-81
View File
@@ -1,81 +0,0 @@
---
title: "raea 0.1.11"
version: "0.1.11"
date: "2026-11-26"
summary: "A goal is a make job, judged by its own commands and a fresh critic. Live sound follows your output device, a picture taller than the GPU's largest texture draws, and Windows on ARM gets raea's installer and its own build. In the app, typing to Ideate answers with your own agent, there is one Settings page, and voice comes with Studio."
sources: ["https://github.com/shinyobjectz/raea/releases/tag/v0.1.11"]
---
raea 0.1.11 makes a goal something `raea make` holds an agent to: the goal's own commands and a critic that only
reads decide when it's done, never the agent's word. Live sound now follows the output you're listening on, a very
tall picture draws instead of being refused, and Windows on ARM PCs get raea's installer and a build of their own. In
the app, typing to Ideate answers with the agent you connected, Settings are one page, and talking with Ideate comes
with Studio.
**Get the app at [raea.io](https://raea.io)** (a Mac with Apple silicon, Windows 10 or 11, or Linux on x86_64).
The engine alone:
```sh
curl -fsSL https://raea.io/install | sh
```
On Windows, in PowerShell: `irm https://raea.io/install.ps1 | iex`.
## What changed since 0.1.10
**A goal is a make job.** Besides scenes, kits, shots and cuts, `make: goal({...})` in `brief.ts` is a fifth kind of
job (MK28-MK29). Its rules are commands that must pass and things it must say, and `raea make judge` has a fresh
critic, which only reads, judge each `says` rule into `review/goal.judge.json`. `raea make status` is the one judge
of whether the goal is met.
**Cuts from a brief rotate their call to action.** A `cut` brief's `cta.also` lists the other lines a brief rotates,
and each cut ends on one of them within its last 8 seconds (MK25).
**Live sound follows your output.** When the system's output changes (headphones, AirPods, a display) or the stream
breaks, live sound reopens on the device in use instead of going quiet.
**A tall picture draws (#245).** A picture larger than the GPU's image atlas (a 1080 x 18000 site capture drawn 880
wide) was refused with a message about a filtered layer. It is now decoded at a size that fits the atlas, which is
16384 px a side even on a GPU that allows larger textures.
**Windows on ARM (#82).**
- `irm https://raea.io/install.ps1 | iex` installs on an ARM64 PC: raea's ARM64 build when the release has one, else
the x86_64 build, which Windows 11 on ARM runs emulated. Before, the installer refused ARM64 PCs.
- raea is built natively for Windows on ARM (`raea-0.1.11-windows-arm64.zip`) when its build passes, beside the
release's other archives.
- On a Snapdragon PC, raea picks DirectX 12 for its Adreno GPU, where Vulkan drew 2D pages striped and with grey boxes
behind fading text.
**In the app.**
- Typing to Ideate answers with your own agent (Claude, Codex, or whichever you connected), named on screen while it
thinks, and the conversation stays open instead of fading after a few seconds. raea's own voice model is only for
speaking.
- Talking with Ideate comes with Studio (300 minutes a month) and Enterprise (no limit). Free and Pro type.
- Settings are one page: your workspace's sections, then this computer's (account, plan, sharing, general, storage
and debugging), searched together.
- Signing out on the Mac's workspace signs raea's account out, and the menu names the account you're in.
- A review's player starts with sound, and remembers if you turn it off.
- Every project has a canvas: deliverables, previews and the brief's frames, marked with a region or a point and a
`#tag`, sent back as a note or as edits.
- On Windows, Codex's shell commands run (#244). Codex's elevated sandbox waited on a Windows prompt or failed every
call with "The tool call failed"; raea now starts it with Windows' unelevated sandbox, unless you set your own.
**raea cloud.**
- Boxes move onto each new release, and each box build is stamped with the commit and files it came from.
- An agent's errors go into its run's trace, a runaway render is stopped before it takes the box down, and an agent
waiting on a long render keeps its connection.
- A render sends a project's footage once, known by the file rather than its path.
- `raea words` on a box transcribes with Whisper large-v3, and `raea frames check` measures what a cut's pictures get
wrong (faces cut off, split frames that make no sense).
- Google's AI signs in on the box, in a browser you work from the dashboard.
**Known**
- The Windows on ARM build is checked in CI without drawing: GitHub's ARM64 runner has no GPU raea can draw on. A
Snapdragon PC is where its pictures are checked. If something looks wrong, the x86_64 build still runs there, and
`WGPU_BACKEND=vulkan` or `dx12` chooses the graphics API by hand.
- The Windows app is unsigned, as before: Windows asks once whether to run it (#221).
- On Linux, raea needs a processor with AVX (most from 2011 on) and glibc 2.39 or newer (Ubuntu 24.04, Debian 13,
Fedora 40 and later).
- A proxy set by an automatic configuration (PAC) file isn't read. If yours uses one, start raea with `HTTPS_PROXY`
set.
-244
View File
@@ -1,244 +0,0 @@
@spec
Feature: raea games as playable ads, exported for every ad network from the TSX that renders the video ad
Shane, 2026-10-29: "lets build a playables feature and explore how we can optimize or help raea agents build for
playables specifically as well as explore the export options included with it". A playable ad is a 15-60 second
mini-game served in place of a video ad, inside other apps' WebViews; it ends on a card that opens the store. Bevy
stays the engine for games (docs/web-export.md is raea's own web build); a playable is an export of a game, drawn by
a light web renderer on the same scene contract, because Bevy's renderer doesn't fit an ad (PA0b). The code is
sdk/playable (raea/playable for authors, the browser host, the export tools); the example is
examples/playables/brick-rush.tsx.
Background:
Given the networks that take advertiser playables in 2026, read from each network's own spec on 10-29
| network | package | cap | install call | also |
| AppLovin | one HTML, all inlined (base64/122) | 5 MB | mraid.open(url) | MRAID 2.0; timer starts at the first touch |
| Unity Ads | one index.html, inlined, minified | 5 MB | mraid.open(url) | MRAID 3.0 injected by the webview; start on ready + viewable, pause when not; both orientations |
| Google | ZIP, index.html, at most 512 files | 5 MB | ExitApi.exit() | exitapi.js and <meta name="ad.orientation"> in the head; billed per engagement |
| Meta | one HTML with data URIs, or ZIP | 5 MB | FbPlayableAd.onCTAClick() | no mraid.js; ZIP at most 100 files (blogs that say 2 MB are out of date) |
| Moloco | one HTML with data URIs, no ZIP | 5 MB | FbPlayableAd.onCTAClick() | mraid.js banned |
| Mintegral | ZIP: a folder and a page of one name | 5 MB | window.install() | gameReady() when loaded, gameStart from the network, gameEnd() when over |
| TikTok | ZIP, index.html + config.json | 5 MB zipped | window.openAppStore() | their playable-sdk.js before the game's script; {"playable_orientation": 0/1/2}; no mraid.js |
| Liftoff | one HTML, or ZIP with one folder | 5 MB | Liftoff.open() | relative paths only |
And every network refuses a network request, a redirect without a tap, and sound before the first touch
And ironSource's own network closed on 2026-04-30 (its traffic is Unity LevelPlay's)
Rule: Settled questions
Scenario: PA0a. What a raea playable is
Given a game written as any raea game is: React TSX, its state a pure fold of input (useGameState), its 3D the
SDK's components (which render data-3d elements, the contract the native engine reads)
Then the same file renders with `raea render` as the video ad (no one touches it, so it plays itself) and exports
with `raea playable` as a playable for each network
And it imports raea/playable for the store: <EndCard show={over}> when the game is over, <InstallButton> anywhere,
or install() from a tap; outside an export install() does nothing
And it registers a portrait and a landscape composition when it can (the host plays the one nearest the screen;
a single one is letterboxed, and Unity, AppLovin, Moloco and Mintegral want both)
Scenario: PA0b. Bevy's renderer stays out of ads; a light web renderer draws them (measured 10-29)
Given brick-rush's scene (24 cuboids, paddle, ball, a shadowed directional light) in plain Bevy 0.20 for
wasm32 (opt-level z, fat LTO, wasm-opt -Oz), next to the three.js export of the same game
| build | wasm | one HTML (base64) | zipped |
| Bevy, default features | 23.3 MB | 31.3 MB | 7.4 MB |
| Bevy, the features raea-render turns on | 21.5 MB | 28.7 MB | 6.9 MB |
| Bevy, only what the scene needs (WebGL2) | 12.3 MB | 16.5 MB | 3.7 MB |
| Bevy, only what the scene needs (WebGPU) | 10.8 MB | 14.6 MB | 3.1 MB |
| Bevy logic only (App, ECS, Transform; no renderer) | 0.55 MB | 0.74 MB | 0.2 MB |
| sdk/playable: React + three.js + the game | - | 0.79 MB | 0.22 MB |
And stored gzipped inside the page (DecompressionStream, in every WebView since 2023) the stripped WebGL2 build
is 4.99 MB as base64: under 5 MB with nothing left for raea's own crates, the game or its assets (brotli: 3.4 MB,
but older WebViews can't decompress brotli)
And first frame served from localhost: Bevy 1.9 s, three.js 0.66 s; at 4x CPU throttle 3.2 s and 1.5 s
Then the renderer (wgpu, naga, bevy_pbr) is about 95% of Bevy on the web: logic alone is small
And the industry does the same: Unity Playworks (ex-Luna) never ships Unity's WebGL build; it converts the game's
C# to JavaScript and runs it on its own ~650 KB playable engine; PlayCanvas's engine is ~1.2 MB
And so a playable is drawn by a light WebGL2 renderer on raea's scene contract, its look held to the native
engine's by a parity check (PA9), its shading moving toward Bevy's own (PA10, PA11); Bevy's logic may come along
as wasm (PA12); Bevy wasm stays the path for raea's uncapped web export (docs/web-export.md)
And WebGPU is on by default in iOS 26's WKWebView and reported in Android WebView, but a playable targets WebGL2
for reach
Rule: Built 10-29
@done
Scenario: PA1. The browser host
Then sdk/playable/src/host/main.tsx mounts the registered composition nearest the screen's shape on a stage
scaled uniformly into the screen, steps a Clock 1/fps at a time off requestAnimationFrame with the person's
input recorded per frame as live entries (input.ts: keys, the primary pointer, every finger, in composition
px), and draws the page's data-3d parts with three.js under the page (scene.ts), the page's background behind
the 3D becoming its clear colour
And it starts when the network says the ad is viewable, pauses while it isn't, stops stepping when the game's
EndCard shows, and at the composition's last frame shows its own EndCard
And the status: brick-rush plays in headless mobile Chrome in portrait and landscape; a drag moves the paddle; three
misses show "So close!"; a tap on the card fires end then install (tools/check.ts, PLAY_SECONDS=25)
@done
Scenario: PA2. Each network's start, pause, store and end calls
Then sdk/playable/src/network.ts is built with the network's name (__RAEA_NETWORK__) and the store links, and maps
whenReady, install and end onto the table in the Background (MRAID's ready/viewableChange; Mintegral's
gameReady, gameStart, gameEnd; the store call per network; preview does nothing)
@done
Scenario: PA3. raea/playable for authors
Then install(), end(), <EndCard> (the whole card opens the store; end() when it first shows) and <InstallButton>,
plain page elements, so a native render draws them as the playable does
@done
Scenario: PA4. The lint: what a playable can't have, refused before it is bundled
Then `raea playable` (apps/playable lint.rs, with sdk/playable/src/export/walk.ts run by `raea run`) renders each
composition at 12 frames through its length and refuses a 3D kind the host doesn't draw (PLAYABLE_KINDS in
host/kinds.ts), staticFile, URLs, fetch/XHR/WebSocket, modules that need
the native engine, and <Video>/<Audio> until PA6; it notes a missing raea/playable import and a single
orientation
@done
Scenario: PA5. One export, every network's package
Then `raea playable GAME.tsx -o DIR [--networks ...] [--ios URL] [--android URL] [--title T] [--cta T]
[--orientation O]` lints, bundles one minified script (PA13) and writes each network's page or ZIP, its settings
in a preamble before the script, checked against its cap
And the status: brick-rush exports for all nine targets (eight networks and preview) at 916 KB per HTML and 292 KB
per ZIP (786 and 218 before PA10's tone-mapping table)
@done
Scenario: PA7. A playable played as a phone shows it
Then sdk/playable/tools/check.ts PAGE.html OUT [WxH] opens it at a phone's size with touch (WebKit since PA7b),
drags across it, saves screenshots, reads the console and the ad events back, and fails on an exception or a
network request; CPU_THROTTLE=4 for a slow phone, PLAY_SECONDS to play to the end and tap the card
Rule: Made viable again 11-28
The 11-06 public-first squash took raea/playable and @raea/playable out of the public sdk/tsconfig.base.json (as it
did raea/body and raea/gen), so every export failed at the lint with "Cannot find module 'raea/playable'"
@done
Scenario: PA4b. The tools resolve the SDK's names themselves
Then sdk/playable/tools/alias.ts resolves raea, raea/<module> and @raea/<package> from sdk/tsconfig.base.json's
paths as engine/bundle's script.rs does, plus raea/playable and @raea/playable/*, as a Bun plugin for the bundle
And the lint's walk (tools/walk.ts) runs bundled after the game instead of imported by Bun's runtime, whose own
tsconfig paths ("raea/*") catch raea/playable before any plugin
And a game's own components in a project with no SDK tsconfig bundle as they render (mobile-ads' gates did not)
And the status 11-28: brick-rush exports for all nine targets (1,431 KB per HTML, 471 KB per ZIP); mobile-ads'
tiles (1,393 KB) and gates (1,395 KB) export for AppLovin, Google and preview
@done
Scenario: PA7b. The check plays in WebKit
Given iOS ad WebViews are WebKit, and raea doesn't test in Chrome (Shane 11-15)
Then tools/check.ts plays the page in Playwright's WebKit (playwright-core 1.64.1, the app's version) at a phone's
size with real pointer input held over frames, fails on an exception, a network request, an empty page, or an
end-card tap with no install event; parity.ts draws its still in WebKit too, and tools/chrome.ts is gone
And a network's own page tags (Google's exitapi.js, TikTok's playable-sdk.js) are stopped but not failed: the ad
view serves them
And the status 11-28: brick-rush, tiles and gates play to their end cards, events ["end","install"], no requests
Rule: Next
Scenario: PA6. Sound in a playable
Given networks keep sound off until the first touch and most players never turn it on
Then raea/tone's instruments and the export's generated foley (TokenSynth, SAO) play through Web Audio from data
URLs after input.onFirstTouch, inside the size budget
Scenario: PA8. Fonts inlined
Given brick-rush's page asks for Inter, which a phone doesn't have (it fell back to a serif in the first check)
Then the export inlines the subset of each font the page uses, as the native render draws it
@done @needs:PA1
Scenario: PA9. The playable is held to the native render
Then a parity check renders the same composition frame with `raea render` and in the playable host (headless
Chrome, scripted input none, so both play themselves), and compares the 3D's colours where both drew a part
And it fails when they drift past a bar, so the light renderer can't quietly lose the look
And the status: sdk/playable/tools/parity.ts GAME.tsx COMPOSITION FRAME OUT [BAR] renders the frame with `raea render
--frame`, opens a preview build at the composition's size with #still=FRAME&comp=ID (the host draws that one frame
and stops), and compares the pixels the native frame drew over its background: coverage, mean colours, brightness
and mean difference (0-255), exiting 1 over BAR (default 16); native.png, playable.png and diff.png are kept
@done @needs:PA9
Scenario: PA10. The lighting conversion
Given the SDK's 3D layer hands lights to the renderer in its own units (r3f intensities converted from Bevy's lux,
lumens and cd/m²) and Bevy draws with its camera exposure and TonyMcMapface tone mapping
Then the host converts them so PA9's colours match
And the status: host/scene.ts turns the SDK's intensities back into Bevy's units (lux 8000, lumens 9e5 over 4π,
ambient 400 × π) times Bevy's camera exposure (1 / (1.2 · 2^9.7)); host/tonemap.ts draws the 3D into a half-float
target and maps it through TonyMcMapface, Bevy's own 48³ table (tools/tony.ts reads bevy_core_pipeline's ktx2)
resampled to 32³ sRGB bytes (98 KB; the 48³ table scored 5.3 for 311 KB more), sampled as tonemapping.wesl does;
where nothing was drawn it stays transparent over the page's own background
And the numbers on brick-rush (mean difference / 255, brightness): portrait frame 90 went from 50.2 and 0.688x
(three.js's units, no exposure) to 5.4 and 0.992x; landscape frame 300 is 9.1 and 0.971x. three.js's built-in
curves on the converted units scored Reinhard 14.5, Neutral 21.2, AgX 23.3, none 30.4, ACES 37.9; what is left is
the shading itself (the bricks' side faces a touch darker), PA11's job
@needs:PA9
Scenario: PA11. Bevy's own shading in the light renderer
Then Bevy's PBR shaders, composed for the pipelines a playable uses, are translated to GLSL ES 3.00 with naga at
export time, and the light renderer draws with them instead of three.js's own materials
And the 10-29 trial: Bevy 0.20's shaders are WESL, composed by bevy_shader with wesl 0.6 (defs as feature flags,
Int/UInt defs in a virtual `constants` package, `bevy_pbr/bevy_core_pipeline` folded to `bevy_core_pipeline`). A
standalone program doing the same over the registry sources, then naga 30 (validate, GLSL ES 3.00 for WebGL),
with WebGL2's defs (WEBGL2, NO_ARRAY_TEXTURES_SUPPORT, NO_CUBE_ARRAY_TEXTURES_SUPPORT, SIXTEEN_BYTE_ALIGNMENT,
AVAILABLE_STORAGE_BUFFER_BINDINGS=0, MAX_CASCADES_PER_LIGHT=1, PER_OBJECT_BUFFER_BATCH_SIZE=93 for the 176-byte
Mesh in 16 KB) and the mesh pipeline's for a plain forward StandardMaterial mesh with TonyMcMapface in the shader:
| shader | GLSL ES 3.00 | gzip | in Chrome's WebGL2 |
| bevy_pbr::render::pbr frag | 1,703 lines, 88 KB | 16 KB | compiles (29 ms) |
| bevy_pbr::render::mesh vert | 175 lines, 6.8 KB | 1.7 KB| compiles; the pair links (551 ms) |
| bevy_pbr::prepass (shadows) | 150 lines, 5.5 KB, vertex | | translated, not linked yet |
And what that leaves: nothing has been drawn with them. The program binds 7 textures (4 material maps, the point
and directional shadow maps, the Tony LUT) and 11 uniform blocks the host would fill as Bevy's render world does:
View (784 B), Lights (2,176 B), the cluster offsets, index lists and clustered lights (16 KB each, so the host
clusters lights on the CPU as Bevy does on WebGL2), the StandardMaterial (192 B), the Mesh batch and Globals.
That packing, and the shadow passes, are PA11's real work; the shaders themselves come over unchanged
Scenario: PA12. Bevy systems in a playable
Given Bevy's logic alone is 0.2 MB gzipped as wasm (PA0b)
Then a game whose rules are Rust (raea/ecs's world, behind the ecs.* native calls) runs them in wasm in the
playable, its world drawn by the light renderer
@done
Scenario: PA13. `raea playable`
Then the export is a raea CLI verb (apps/playable) on raea's own bundler, in process: engine/bundle gained
`minify` (Rolldown's minifier), `inline` (inline.rs: pictures, sounds, fonts and .glb as data URLs, a .bin as a
Uint8Array) and package-folder aliases (`--alias three/=DIR`, three.js from the project's node_modules, else
raea's own)
And the lint's walk runs as `raea run` in a process of its own; tools/playable.sh, bundle.ts, lint.ts, walk.ts,
alias.ts and chrome.ts are gone, and Bun is needed only for check.ts, parity.ts and tony.ts
And the status 11-28: brick-rush writes all nine targets in 7 s (1,384 KB per HTML, 464 KB per ZIP), mobile-ads'
tiles (1,345 KB) and gates (1,347 KB) export, and all play in WebKit, the Google and TikTok packages included;
a game with staticFile is refused with the reason first
And fonts travel as pictures do: an imported .ttf, .otf, .woff or .woff2 is its path in a native render and a data
URL in a playable, named in an @font-face; <EndCard> takes font, color and button for a brand's own card
Scenario: PA14. Agents writing playables
Then the raea skill says how a playable is shaped (hook, a hand until the first touch, a fail moment, the end card
within 30-60 s, both orientations), what the lint refuses, and how to check one (tools/check.ts)
And the guide is sdk/guides/craft/motion/playable.md (`raea guide playable`, copied into the skill's motion/), and
SKILL.md routes "a playable ad" to it
Scenario: PA15. A 2D playable carries no three.js
Given 11-28's tiles bundle: three.js 924 KB of 1,393 KB, react-dom 178 KB, for a game that draws no 3D
Then the export builds the host without the three.js scene when the lint finds no 3D kind (about 470 KB a page)
Scenario: PA16. Playables in the review (raea cloud and the desktop)
Given the review's own player (raea-platform board-simple review.js PLAYER_DRAWS) is the one view of a shown file
in raea cloud and in desktop v3, and a playable is one HTML page that loads nothing
Then a "playable" kind is drawn by that player: the preview page in a sandboxed iframe (allow-scripts only) inside
a phone frame, portrait and landscape, restarted from the stage's own button
And the host's ad events (ready, viewable, end, install) show beside it, so a reviewer sees the store tap fire
And each network's package, its size against the cap, is a download under it, and pins and notes work as on a video
And `raea show GAME.tsx --playable` exports the preview and shows it as that kind (`raea show PAGE.html` for a page
already exported); host/show.ts refuses .html today
# Status 11-28: built. Cloud: raea-platform #99 (merged into #97's oux-audit-1128) and #101: the playable kind
# (a delivered .html), its 9:16 card, the phone either way up with Restart, the events (ready, viewable,
# hidden, first touch, end card, store opened), and the network packages folded under it as downloads, red
# past 5 MB. Shane 11-28: the page plays on a domain of its own: play.raea.io, live 11-28 (#105, #106:
# PLAY_HOST, harness/play.ts: sandbox allow-scripts, 'wasm-unsafe-eval', network off, no-transform, framed by
# app.raea.cloud, api.raea.cloud and the desktop's local port). Checked live: the ACANA export uploaded, played
# from play.raea.io in a sandboxed frame in WebKit, ready and touch posted, the bytes as exported.
# Desktop: raea-feed #124: `raea show PAGE.html` posts a play item with a page, /host/playable serves it under
# the same policy, Playable.tsx draws it with pins. `raea show GAME.tsx --playable` exports the preview first
# (engine/cli show.ts, native.ts). Checked: the real ACANA export served under the policy runs clean in WebKit.
Scenario: PA17. Video ad and playable side by side
Then one shown game is both: its `raea render` (the video ad, played by its own hand) and its playable, one
project in the review, so a creative test brief gets both formats from one file
Scenario: PA18. brick-rush plays live in the native engine
Given bench/live-3d/corpus.sh skips brick-rush: under RAEA_LIVE3D_CHECK it panics on frame 1, because the fast
rows (runtime/scene/src/live.rs) carry the sun's rotation and the full rows don't
Then the fast and full rows agree on a light's transform, and brick-rush plays live and leaves the corpus's skips
-283
View File
@@ -1,283 +0,0 @@
# Solari, forked: where MALL RAT's frame time goes (11-25)
Measured on MALL RAT's own takes (Raea/anchor-tenant, `tools/solari-sweep.sh`, scored by `out/lab/pf/score.sh`): each
lever moved alone from the take's settings, 240 frames, wall time a frame, scored SSIM/PSNR against the take as it
renders (pf0) on the finished VHS look at 1440 x 1080. pfR is pf0 drawn again: its numbers are the noise floor (and wall
time itself moves about 10% run to run). The sweep stopped partway: t8 has four levers.
| lever | t2 ms (pf0 204) | t2 ssim / psnr | t4 ms (pf0 82) | t4 ssim / psnr |
|---|---|---|---|---|
| pfR, the floor | 185 | 0.991 / 37.2 | 80 | 0.989 / 42.6 |
| pfB, 1 bounce | 186 | 0.990 / 36.2 | **64** | 0.988 / 41.0 |
| pfS, half the samples (8/4) | 194 | 0.988 / 32.6 | 75 | 0.987 / 40.5 |
| pfF, firstBounce 0.5 | 161 | 0.989 / 35.8 | 61 | 0.984 / 38.8 |
| pfC, Solari at 0.67 scale | 149 | 0.986 / 35.8 | 52 | 0.964 / 34.3 |
| pfH, Solari at 0.5 | 154 | 0.984 / 35.1 | 33 | 0.959 / 35.0 |
| pfT, Solari at 0.35 | 153 | 0.980 / 33.8 | 25 | 0.950 / 33.1 |
| pfD, whole frame 720 x 540 | 180 | 0.983 / 33.4 | 25 | 0.967 / 34.2 |
| pfE, whole frame 960 x 720 | 165 | **0.987 / 36.6** | **37** | **0.978 / 38.6** |
Solari's own GPU time (RAEA_SOLARI_TIMES) on t2: 18.5 ms at 0.5 scale (initial path 14.6, spatial and shade 2.7, world
cache 1.1, light tiles 0.1), 31.7 ms at 960 x 720; by pixel count about 70 ms at full size.
## What it says
1. **t2 is not Solari's.** At 0.35 scale Solari takes 11 ms and the frame still takes 153. About 140 ms a frame in the
mall court goes to the rest: the composition's scene each frame (hundreds of LOD pieces, 88 baked water frames, the
arcade), raster, the look's FramePass chain and the encode. That is the biggest saving left, and it needs a CPU
and GPU profile of one t2 frame (xctrace), not a Solari change.
2. **Render the tape at 960 x 720.** The VHS look keeps about 320 x 240 a field, so the whole frame at 960 x 720 (pfE)
is the best lever measured: t4 55% faster at SSIM 0.978, t2 about 15% faster, nearly at the floor. It beats scaling
Solari alone (pfC) on both time and picture, because raster and the look shrink with it.
3. **One bounce is free in picture.** pfB sits at the floor on all three takes and saves 20% on t4: the world cache
already carries the light past the first bounce.
4. **Fewer samples are not.** Halving spp saves little time (the cost is per pixel, not per sample, at these counts)
and costs PSNR (t2 37.2 to 32.6). The other way round, the noise notes on v3 (21, 22) are answered with more samples
on t5 and t8 only.
5. t8's pfS and pfF score PSNR 19.8. Frame by frame it isn't a timing slip: pfS starts at 10 dB and climbs steadily to
39 over the 240 frames (pfR holds 35-42 throughout). With fewer samples t8's light starts far off and takes about
4 s to settle, most likely through its short world-cache life (`cache: { frames: 6 }`, set so the power cut drops
the light at once). In a take with a short cache, cutting samples costs seconds of wrong light, not noise.
## The quality fix: light selection by power, not by count
`generate_random_light_sample` (scene/sampling.wesl) picks a light source uniformly: `light_id = rand_range_u(light_count)`,
and every pdf divides by `light_count` (sampling.wesl 131-175, realtime/restir.wesl 330, realtime/initial_path.wesl 370).
Each emissive mesh, each directional light and each sky portal is one source. So:
- a dim exit sign gets as many samples as the sun, and a scene with 300 emissive pieces gives the sun 1/300 of them:
noise where the sun matters (v3 notes 7, 21, 22);
- a LOD swap or a set mounted mid-shot changes the count, so the sun's share jumps and the denoiser shows a one-frame
2-5x brightness step (t2 v3: frames 1042, 2263, 3960, 4315, each a LOD swap). The composition now holds LOD levels a
take and mounts sets for the whole take, which works round it, not through it.
Two ways to fix it in the fork, smallest first:
- **A fixed share for the sky.** Directional lights and portals get a fixed probability q (0.5) split among them,
emissive meshes share 1 - q. The count of emissive pieces then never moves the sun's share. Needs the two counts in
a uniform and the sources kept in two runs (LightIndex's swap_remove keeps no order today), and the five pdf sites
changed to read the share by kind.
- **Power-weighted (an alias table).** Each source weighted by its power (emissive luminance x area; a directional
light's illuminance; a portal's sky radiance x area), sampled in O(1) through an alias table rebuilt when the light
set changes. GpuLightSource grows from {kind, id} to {kind, id, pmf, threshold, alias}. The emissive-hit pdf (MIS in
the path tracer and initial_path) needs the hit's source pmf, so the instance needs its light index. ReSTIR DI's
light tiles inherit it for free, since they draw from generate_random_light_sample.
Either needs a release build and a check on t2's four swap frames and t8; neither was built while MALL RAT v4 held the
GPU.
## The splotches: the world cache's history, and a bake (11-25)
Shane on v4: "noisy splotchy thing in the lights and reflections ... it's definitely the world cache, can we bake it?"
Each cell takes one bounce ray an update and blends it over a history capped at 32, but the adaptive cut
(`alpha = |lum delta| / lum`, world_cache_update.wesl blend_new_samples) reads a cell's own noise as the light changing
and holds the history near 10. Ten one-ray samples is the blotch: cell-sized patches that crawl.
Built in the fork (vendor/bevy_solari, uncommitted, lane solari-bake to come):
- `world_cache_steady`: the blend keeps the whole history up to `cache.frames`, with no adaptive cut, and each update's
ray seeded by the cell's sample count, so one cell's rays don't repeat. `cache.steady` in the SDK.
- `world_cache_update_iterations`: N cache updates a frame. `cache.iterations` in the SDK.
- `world_cache_keep`: no decay, so cells never die. `world_cache_save` / `world_cache_load`: the cache buffer
written to a file (bake.rs: a copy to a MAP_READ buffer, mapped and written before the next frame's pipelines) or
read into it and held (the whole world-cache stage skipped). `cache.bake: { iterations, save }` and
`cache.load` in the SDK.
The bake doesn't fit. A cell's key holds its LOD band (stochastic between bands), its quantised position after a
±half-cell jitter and a plane slice along the normal, so one surface seen from a moving camera makes many keys. With
nothing decaying, t2's whole take filled all 2^20 slots, and so did each 6 s window of it (13 windows, each 100%).
A cache that is full loses cells, and a loaded cache missing cells has holes. A bake would need larger cells, no
jitter, or a cache sized to the take. So the live steady history is tried first: it gives the same convergence on
the cells the camera sees (they are read each frame, so never die) with no file and no capacity limit. It costs a lag
on light that moves, as long as the history: t8's power cut needs a short `frames`, as it has today.
## The cache's level does not drift: a pass's uniforms stood still (11-25)
An earlier reading here was wrong. The same t2 frame (1188) read 0.0189 cold at 1440 x 1080 and 0.0177 at 160 x 240,
but 7x that inside the long view render and 0.2x inside the long meter render, and it looked as if the world cache's
level depended on time and on how many pixels fed it. It doesn't. With the tape's exposure held constant, a 520-frame
moving run and a held frame agree (ratio 1.04), at any size.
What moved was the passes over the frame. A video's 3D is made live, and when a part is dropped mid-render the live
rows move up; a <FramePass>'s and a <Compute>'s `follow` found their row by the order the scene opened with, so from
the first drop on they read another row and kept the uniforms they opened with. The view's exposure stayed at its
first value (64 against 7.6 at t2's frame 720), the meter's passes kept their first camera, and the auto-exposure
built on that meter set the final 14 to 40x too bright: Shane's overexposed daylight. Fixed in the engine
(engine/render spawn.rs `name_rows`; docs/shaders.feature SH6). After it, t2's meter reads 3 to 4.6x higher than
before, a held meter frame and the moving one agree (0.89), and the take's white share fell from a median of 19.9%
to 3.7%.
How it was found, for the next time a sequence and a still disagree: hold the frame (`raea render --hold N:40`) and
compare it with frame N of the sequence; then make one input constant at a time (here the exposure uniform) until
they agree. The frame-purity check (`raea render`, every 300th frame drawn again alone) catches this class, and
MALL RAT renders with it off (RAEA_FRAME_PURE=0), because Solari's history makes a still differ from a sequence anyway.
## What fixes the patches, measured (11-25)
The patches are **boiling**, the industry's word for denoised traced light's soft patches crawling over still surfaces
(NRD, RTXDI, GI-1.0, the ReSTIR papers, Lumen). raea now uses it (docs/skills.glossary.md, the Solari guide's "Boiling");
`raea light steady`'s blotch is its size in one held frame.
What others do about it that raea hasn't tried yet:
- a longer denoiser history: NRD says history "can be bumped up to 60 frames relatively safely" to suppress residual
boiling, and Lumen's guides raise `MaxFramesAccumulated` (10 -> 16) before adding rays. MetalFX's history is the
next lever here;
- blue-noise sampling (NRD: "reduced residual boiling in areas with acceptable sampling quality"), against Solari's white
hash noise;
- a larger ReSTIR temporal cap with decorrelating mutations (Sawhney et al. 2024: boiling from hard indirect light is
resolved by a greater M cap, and mutations remove the blotches a larger cap brings), or RTXDI's boiling filter
(which loses energy);
- for an offline render, a noise pattern held still across frames (Octane's "static noise"): a held shot can't boil,
though its grain stops moving.
Measured with `raea light steady` (frame held, its light's movement over time; limit 1.5% blotch, worst tile 4.5%) on
MALL RAT t2 frame 1188 (150 held, 75 measured), and the bench kitchen (STEADY 0.63 today). t2's runs of one setup spread
by 0.1-0.4, so each setup that matters was run twice.
| setup on t2 | blotch | verdict |
|---|---|---|
| today (1 path, ReSTIR, live cache) | 2.84-3.09 | fails |
| the controls: raster, and the look's passes off | 0.0, 3.04 | the patches are Solari's |
| world cache baked and frozen | 2.55 | the cache is not the main cause |
| denoiser off / its guides off | grain 17.6, 2.9 | MetalFX passes the patches, doesn't make them |
| ReSTIR off; its confidence cap 32; spatial radius 8 | 2.13; 3.03; 2.98 | ReSTIR adds, its settings don't fix |
| 2x/4x direct-light samples; 64 small emissives removed; light selection by a sky share | no change | not the direct light |
| denoiser and ReSTIR off, cache frozen: the raw light | 98% per-pixel grain, white in space and time | one path's bounce has a sd as large as its mean |
| **paths 4 / 8** (new: N initial paths a pixel, RIS-merged) | **1.89 / 2.10** | halves it |
| paths 8 + frozen cache | 1.45, 1.53 | on the line |
| paths 8 + steady cache (1024 history, 8 updates) | 1.65, 1.69 | |
| paths 4-8 + steady + still-camera query (no jitter, one LOD) | 1.66-1.88 | no better |
| paths 8, ReSTIR off, steady / frozen | 1.60, 1.69 / 1.54 | |
| paths 8 + frozen, camera jitter off | 1.31 (the one pass) | jitter isn't the floor |
Bias: the kitchen's mean at 4 paths against 1 is +0.0015 stops (per-pixel median 0); with the steady cache and still
query +0.0013. Glade's moving shot (the still query off while it moves): flicker 0.708 against 0.702. Cost on t2: a
150-frame hold 50 s at 1 path, 82-94 s at 4, 112 s at 8; glade 1.72 -> 2.47 s a still at 4.
So: `paths` is the lever that ships (default 1; MALL RAT's takes set it). It takes t2 from about 3.0 to 1.6-1.9, which
still fails the gate. The rest is the world cache: a frozen one reads 0.1-0.3 lower than any live one at the same paths,
and the live cache made to converge (steady history, more updates, the still-camera query) doesn't close the gap. Left
for the next release: a cache that converges like the frozen one (cells kept for a held shot without the 2^20 overflow:
a bigger or per-take cache, or ReSTIR GI's reservoirs carrying the cache's light), then t2 again.
Built in the fork, all off unless asked: `paths` (SolariLighting::paths_per_pixel, RAEA_SOLARI_PATHS), `cache.steady`
and `cache.iterations`, the still-camera query (with `cache.steady`, RAEA_SOLARI_STEADY=1), `cache.bake`/`cache.load`
(experimental: a whole take overflows 2^20 cells), light selection by a fixed sky share (RAEA_SOLARI_SKY_SHARE, 0 =
upstream), ReSTIR's spatial radius (RAEA_SOLARI_SPATIAL_RADIUS, 30).
## Telling the movement apart, and what each kind was (11-25, afternoon)
`raea light steady` now tells the kinds of movement in a held frame apart (engine/light/src/kinds.rs). It
reads each 32 px square over the last 75 held frames and splits its light four ways:
- **settling**: the square's straight-line trend over the window. The light is still building, which a real render's
lead-in covers. It's reported as "unsettled" over p95 5%, not failed;
- **boiling**: what's left once the trend is removed, where it's slow (lag-1 correlation 0.5 or more);
- **jitter**: what repeats on a 2-16 frame cycle, the camera's sub-pixel jitter showing through;
- **flicker**: what is fast with no cycle, such as a firefly, a sparkle in a reflection, or two faces at one depth.
Each kind has its own limit: boiling rms 1.5% with its worst square under three times that, jitter and flicker worst
5%, and drift 0.05 stops. steady-kinds.png maps them: red is jitter or flicker, green is boiling, blue is settling.
Before, a single number mixed them, and the fixes differ.
What each turned out to be on MALL RAT:
| hold | before | change | after |
|---|---|---|---|
| t1 1699 (silhouettes against the sky) | jitter worst 73%, all 3.73 | the denoiser after the sky and forward meshes (`late`) | jitter worst 3.8%, all 0.76: STEADY |
| t2 1188 (the court, 4 paths) | jitter worst 10% on the shop signs | `late` + emissive "taa" | jitter 0.09%, worst 2.8% |
| t2 1188 | boiling 1.27%, worst 5-7% at the frame's right edge | ReSTIR's spatial neighbours reflected back into the frame, not clamped to its border (restir.wesl) | boiling 1.21%, worst 4.25%: STEADY (t1 425: 0.58) |
| kitchen | 0.63 all, grain 1.38 | `late` | 0.40 all, grain 0.55 |
- **The edges stepping with the jitter: the sky and forward meshes were drawn after the denoiser.** MetalFX ran
before Bevy's main opaque pass (metalfx.rs `denoise`). That pass then drew the Environment's background and every
forward mesh with the jittered camera, and nothing resolved them. Each silhouette against the sky stepped a pixel
a frame on the 8-frame Halton cycle. `SolariSettings.late` (TSX `late`, RAEA_SOLARI_DENOISE_LATE) runs it after
the main pass instead. The guides pass already marks a pixel with no G-buffer (sky, forward meshes) undenoised
(mask 1) but still gathered.
- **The shop signs' edges: MALL RAT's `emissive="split"`** puts each emitter's light back after the denoiser frame by
frame, so emissive edges keep the jitter. The default "taa" mode gathers them over frames.
- **A soft knee around MetalFX** (`knee`, RAEA_METALFX_KNEE; logarithmic above the white at preexposure/16) was
tried first, on the theory that the resolve averaged bright edges in linear light. It changed nothing at t1 1699
(73% either way), because the sky wasn't going through the resolve at all. It keeps the kitchen's mean within
0.004 stops. It's kept for now, default 1.
- **Not the cache's update rate or cell life.** Every cell updated every frame (`cache.updates` 2,000,000) read 1.98
and 1.88 against 1.89. Cells kept for 600 frames unqueried (`cache.life`, RAEA_SOLARI_CELL_LIFE) read 1.34 against
1.27. A 600-frame hold settles by about frame 300-450, but over a longer window the boiling reads higher, so the
detector now fixes its window at 75 frames.
- **Offline, a 64-frame average of a frozen cache's frames reads 0.50**, the kitchen's level. Of a live cache's, it
reads no better than as rendered. So what boils is slow: the light wanders over tens of frames, longer than
MetalFX's history.
## Fireflies that linger, the frame's border, and dark squares (11-25, evening)
A baseline of every MALL RAT take at three frames (27 holds) had the frame-wide boiling under 1.5% on all but one,
and still failed most of them on a single worst square of 5 to 25%. Three different things were in that number.
- **A firefly that lingers.** A hot square's level is flat for 40 frames, jumps 30% in one frame, and takes about 30
frames to fall back. One very bright sample (a bounce landing beside a small lamp) gets a large weight, temporal
reuse keeps it, and spatial reuse spreads it to its neighbours. Whether a hold passed depended on whether one
landed in its 75 frames: t7 187 read 0.88% (worst 10.1%) and, minutes later with nothing changed, 0.39% (worst
2.0%). The party room (t5 1440), lit by small bulbs, has them all the time. This is the case RTXDI's boiling filter
is for, and ReSTIR PT Enhanced (2026) describes the cause. raea's version is `SolariLighting.firefly_cap` (TSX
`firefly`, RAEA_SOLARI_FIREFLY): after temporal reuse, a reservoir whose contribution is over N times the mean of
its 8x8 block has its weight cut to that (restir.wesl, a `var<workgroup>` array and a barrier). On t5 1440:
| firefly | boiling | worst square | frame's mean |
|---|---|---|---|
| off | 1.63% | 7.4% | 0 stops |
| 32 | 1.42% | 4.9% | -0.003 |
| 12 | 1.06% | 6.3% | -0.15 |
| 6 | 0.73% | 3.0% | -0.29: STEADY |
| 3 | 0.69% | 3.9% | -0.38 |
It costs the light those samples carried, so it is off by default and a composition asks for it. Cutting the
sample's confidence, not its weight (ReSTIR PT Enhanced's adaptive cap), lost nearly as much light (-0.22 at 6) and
held less still (0.89%).
- **The frame's border boils more, in a band as wide as the spatial reuse radius.** By distance from the border, in
8 px steps: 0.94, 0.79, 0.67, 0.62, 0.57, then 0.5 from 48 px in (t7 187). A border pixel has half a disc of
neighbours to reuse from. Reflecting the neighbours into the frame helped the first few pixels (above); permuting
the 3 px border strip that `permute_pixel` leaves unpermuted changed nothing (kept, it is harmless). What production
renderers do is overscan: render a margin and crop it. raea has no overscan yet.
- **Dark squares read high as a plain ratio.** The detector divided each square's deviation by its level, so the
darkest corners led (12% of nearly nothing). The eye's contrast threshold is constant in bright light (Weber) and
rises as the square root of falling luminance in dim light (de Vries-Rose; Barten's model has both). kinds.rs now
divides by sqrt(level x 0.05) below a level of 0.05 (linear; about 5 cd/m2 on a 100 cd/m2 display). t5 1440 read
2.03% before and 1.59% after on the same frames.
What was looked up and already there: the world cache's lookups are jittered in the tangent plane (GI-1.0 and
world-space ReSTIR name hash-cell blotches and this cure), and its blend is the adaptive one (Boissé's, in Bevy 0.18).
For moving shots, ReVQ (No-Reference Rendered Video Quality Assessment, arXiv 2510.13349) is the design to follow:
windows of 5 frames warped onto their last with motion vectors, pixels without a correspondence masked, differences
over spans of 1 to 4 frames. A first try that chained 32 frames of motion vectors read 10% on a clean shot from the
warp's own error.
With the firefly filter at 6 on every take, 19 of 24 holds read STEADY (8 of 22 before). What was left, by cause:
- **Emitters thinner than a pixel flickered: the emitter history's clamp.** MALL RAT's ceiling tubes seen edge-on are
1 to 3 px tall and changed shape every frame (t6 211 and t8 204: jitter 7.7% and 7.0% in their squares). With the
history always taken (RAEA_EMIT_TAA_DEBUG=3) the jitter read 0.01%. emit_taa.wgsl held a still pixel's history
inside the range of this frame's samples about it, so a lamp switched off goes dark at once; a tube that some of the
jitter's positions miss altogether was cut to black on those frames. Eased (a quarter of the way to those bounds a
frame) both holds read STEADY (jitter 2.2% and 1.2%), but lightbench's orb switched off then left +2.52 stops on its
tile where it left +0.17 (RT32). Eased only where the history is thin (dark two pixels to both sides, across or
down) the tubes read 3.6% and 2.1% and the orb +0.30, its rim. Two stricter tests of "thin" kept the rim out and
lost the tubes (5.2 to 6.5%). So the engine's default is as it was (STILL_HOLD 1) and MALL RAT asks for it
(`constants={{ emissiveClamp: { stillHold: 0.25 } }}`); the fix for every scene is a count, kept with the history,
of the frames a pixel was missed. A softer gather kernel made it worse (11 to 13% at emissiveSharpness 3 and 1.5).
- **The border** (above): t3 1320's wall at the frame's right edge is lit in 8 px blocks that change each frame, and
the corner squares of t5 900 and the court boil past the worst-square limit on some runs. Overscan
(docs/raytracing.feature RT40) is built, off by default: `<SolariLighting overscan={k}>` (RAEA_SOLARI_OVERSCAN) widens
the camera's sub view by k a side (raea-sys-viewbox), the main pass draws that at 1 / (1 + 2k) of the view's size at
most, MetalFX's denoiser brings it up to a texture (1 + 2k) the view's size, the emission goes back in there, and the
middle is copied over the colour; FramePass's depth() and normal() read the middle of the wider prepass (and now read
the right texels under a render scale below 1, which they didn't). Measured 11-25: lightbench's window draws the
same picture with and without it (no shift, no zoom, mean difference 0.006). t3 1320 held: jitter's worst square
16.06% without, 5.61% at 0.05 and 6.07% at 0.08 (limit 5), boiling's worst 2.32%, 3.51% and 6.1%. So it takes most
of the border's share away and no margin clears this hold: what's left in the last two columns isn't the border.
- A hold near the limit passes on one run and fails on the next (t2 922 and t2 2304 failed in the baseline and read
STEADY minutes later): what's left there is chance, a firefly landing in the 75 frames or not.
The moving detector (scratch moving3.py, ReVQ's design on raea's own motion vectors and depth) reads 0.5% a frame on
the court's door swing where the 32-frame chain read 10%, and tells one path a pixel from four (worst square 9.3%
against 5.8% over 4 frames). It did not tell `late` and emissive "taa" from the settings before them on that shot,
which has no sky edge or sign in it and whose light changes as the doors open. It needs a moving shot under steady
light to be judged on before it gates anything.
-2
View File
@@ -20,8 +20,6 @@ rolldown = "=1.2.12"
# CSS imports and CSS modules (A2): @imports inlined, nesting and newer syntax lowered for Stylo
lightningcss = { version = "=1.0.0-alpha.72", features = ["bundler"] }
anyhow = "1"
# imported files carried in a playable's script as data (inline.rs)
base64 = "0.22"
# the Z3 compile (z3.rs, a live bundle's TSX): oxc as Rolldown 1.2.12 uses it
oxc = { version = "=0.152.0", features = ["transformer", "codegen", "semantic", "ast_visit"] }
tokio = { version = "1", features = ["rt-multi-thread"] }
-72
View File
@@ -1,72 +0,0 @@
//! A bundle that carries its files (docs/playables.feature PA13): a picture, sound or model a module imports becomes a
//! data URL in the script, and a `.bin` table its bytes, so the one page loads nothing (an ad network refuses a page
//! that makes a request). Ahead of the script resolver, which otherwise hands media back as their paths.
use rolldown_common::ModuleType;
use rolldown_plugin::{HookLoadArgs, HookLoadOutput, HookLoadReturn, HookUsage, Plugin, SharedLoadPluginContext};
use std::borrow::Cow;
use std::path::Path;
/// The files carried, by extension, with their media type
const TYPES: &[(&str, &str)] = &[
("png", "image/png"),
("jpg", "image/jpeg"),
("jpeg", "image/jpeg"),
("webp", "image/webp"),
("gif", "image/gif"),
("svg", "image/svg+xml"),
("mp3", "audio/mpeg"),
("m4a", "audio/mp4"),
("ogg", "audio/ogg"),
("wav", "audio/wav"),
("glb", "model/gltf-binary"),
("woff2", "font/woff2"),
("woff", "font/woff"),
("ttf", "font/ttf"),
("otf", "font/otf"),
];
#[derive(Debug)]
pub struct Inline;
/// Standard base64, padded (the base64 crate, as raea's other crates use it)
pub fn base64(bytes: &[u8]) -> String {
use base64::Engine;
base64::engine::general_purpose::STANDARD.encode(bytes)
}
impl Plugin for Inline {
fn name(&self) -> Cow<'static, str> {
Cow::Borrowed("raea:inline")
}
fn register_hook_usage(&self) -> HookUsage {
HookUsage::Load
}
async fn load(&self, _ctx: SharedLoadPluginContext, args: &HookLoadArgs<'_>) -> HookLoadReturn {
let path = args.id.split(['?', '#']).next().unwrap_or(args.id);
let Some(ext) = Path::new(path).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase) else { return Ok(None) };
let code = if ext == "bin" {
let b = std::fs::read(path)?;
format!("export default Uint8Array.from(atob({:?}), (c) => c.charCodeAt(0));\n", base64(&b))
} else if let Some((_, mime)) = TYPES.iter().find(|(e, _)| *e == ext) {
let b = std::fs::read(path)?;
format!("export default {:?};\n", format!("data:{mime};base64,{}", base64(&b)))
} else {
return Ok(None);
};
Ok(Some(HookLoadOutput { code: code.into(), module_type: Some(ModuleType::Js), ..Default::default() }))
}
}
#[cfg(test)]
mod tests {
#[test]
fn base64_pads_as_the_standard_does() {
assert_eq!(super::base64(b""), "");
assert_eq!(super::base64(b"f"), "Zg==");
assert_eq!(super::base64(b"fo"), "Zm8=");
assert_eq!(super::base64(b"foo"), "Zm9v");
assert_eq!(super::base64(b"foobar"), "Zm9vYmFy");
}
}
+2 -12
View File
@@ -16,7 +16,6 @@ use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
pub mod edit;
pub mod inline;
pub mod script;
pub mod stamp;
pub mod z3;
@@ -42,10 +41,6 @@ pub struct Options {
pub edit: Option<edit::Edit>,
/// each element the edit's own files write stamped with its place in the code (stamp.rs; the app's editor asks)
pub stamps: bool,
/// minified (a playable's page, which ad networks cap at 5 MB)
pub minify: bool,
/// imported pictures, sounds, models and .bin tables carried in the script (inline.rs), not named by path
pub inline: bool,
}
/// `entry` bundled into one browser script and its CSS.
@@ -66,7 +61,6 @@ pub fn bundle_with(entry: &Path, o: Options) -> Result<Bundle, String> {
// no `//#region <path>` before each module: its path names the work folder (raea-motion-b<pid>), so every
// process's bundle differed and the incremental bake saw every function change (lightspeed T3)
experimental: Some(ExperimentalOptions { attach_debug_info: Some(AttachDebugInfo::None), ..Default::default() }),
minify: o.minify.then_some(rolldown_common::RawMinifyOptions::Bool(true)),
..Default::default()
};
let stamps = if o.stamps {
@@ -90,9 +84,6 @@ pub fn bundle_with(entry: &Path, o: Options) -> Result<Bundle, String> {
s.spawn(move || {
rt.block_on(async move {
let mut plugins = vec![Pluginable::new_shared(css)];
if o.inline {
plugins.push(Pluginable::new_shared(inline::Inline));
}
if let Some(s) = stamps {
plugins.push(Pluginable::new_shared(s));
}
@@ -329,7 +320,7 @@ pub mod ffi {
1
}
/// `entry` (a path, UTF-8) bundled with `opts` (JSON: {"z3": bool, "edit": {"dir", "js"}, "script": {..}, "defines", "stamps": bool, "minify": bool, "inline": bool}); returns JSON, {"js","css"} or {"error"}, to
/// `entry` (a path, UTF-8) bundled with `opts` (JSON: {"z3": bool, "edit": {"dir", "js"}, "script": {..}, "defines", "stamps": bool}); returns JSON, {"js","css"} or {"error"}, to
/// be freed with raea_bundle_free
///
/// # Safety
@@ -353,8 +344,7 @@ pub mod ffi {
js: path(&e["js"]),
work: std::path::absolute(&entry).ok().and_then(|p| p.parent().map(|d| d.to_path_buf())).unwrap_or_default(),
});
let (minify, inline) = (opts["minify"].as_bool().unwrap_or(false), opts["inline"].as_bool().unwrap_or(false));
let o = super::Options { z3: opts["z3"].as_bool().unwrap_or(false), script, defines, edit, stamps: opts["stamps"].as_bool().unwrap_or(false), minify, inline };
let o = super::Options { z3: opts["z3"].as_bool().unwrap_or(false), script, defines, edit, stamps: opts["stamps"].as_bool().unwrap_or(false) };
match super::bundle_with(std::path::Path::new(&entry), o) {
Ok(b) => serde_json::json!({"js": b.js, "css": b.css}),
Err(e) => serde_json::json!({"error": e}),
+4 -14
View File
@@ -23,8 +23,7 @@ pub struct Script {
pub motion: PathBuf,
/// sdk/shell/src/index.ts
pub shell: PathBuf,
/// `--alias SPEC=PATH`; a SPEC ending in `/` (`three/=DIR`) is a package and every subpath of it, resolved from DIR
/// (a folder whose node_modules holds it) wherever it's imported, so the bundle has one copy
/// `--alias SPEC=PATH`
pub aliases: HashMap<String, PathBuf>,
/// `--node-stub a,b`
pub stubs: Vec<String>,
@@ -37,9 +36,8 @@ const NODE: &[&str] = &[
];
const STUB: &str = "\0raea-node-stub:";
/// Files a script imports as their path (sdk/react's MEDIA_EXTS, as a composition imports them), plus models and fonts
/// (an @font-face's url(), so a playable can carry the same font: inline.rs).
const MEDIA: &[&str] = &["mp4", "mov", "m4v", "mp3", "wav", "m4a", "png", "jpg", "jpeg", "webp", "gif", "glb", "gltf", "ttf", "otf", "woff", "woff2"];
/// Files a script imports as their path (sdk/react's MEDIA_EXTS, as a composition imports them), plus models.
const MEDIA: &[&str] = &["mp4", "mov", "m4v", "mp3", "wav", "m4a", "png", "jpg", "webp", "gif", "glb", "gltf"];
#[derive(Debug)]
@@ -48,12 +46,7 @@ pub struct ScriptResolve(pub Script);
impl ScriptResolve {
/// `spec` as the engine's node_modules resolves it (Rolldown's resolver, from a file in sdk/react/js)
async fn from_engine(&self, ctx: &PluginContext, spec: &str) -> anyhow::Result<Option<HookResolveIdOutput>> {
self.from_dir(ctx, spec, &self.0.js).await
}
/// `spec` as `dir`'s node_modules resolves it
async fn from_dir(&self, ctx: &PluginContext, spec: &str, dir: &Path) -> anyhow::Result<Option<HookResolveIdOutput>> {
let importer = dir.join("_raea.js");
let importer = self.0.js.join("_raea.js");
let opts = rolldown_plugin::PluginContextResolveOptions { skip_self: true, ..Default::default() };
match ctx.resolve(spec, Some(&importer.to_string_lossy()), Some(opts)).await? {
Ok(r) => Ok(Some(HookResolveIdOutput::from_id(r.id.as_str()))),
@@ -91,9 +84,6 @@ impl Plugin for ScriptResolve {
if let Some(p) = s.aliases.get(spec) {
return Ok(path_id(p));
}
if let Some((_, dir)) = s.aliases.iter().find(|(k, _)| k.strip_suffix('/').is_some_and(|pkg| spec == pkg || spec.starts_with(k.as_str()))) {
return self.from_dir(ctx, spec, dir).await;
}
match spec {
"bun:test" | "vitest" | "@jest/globals" => return Ok(path_id(&s.js.join("shims/test.ts"))),
"@raea/shell" => return Ok(path_id(&s.shell)),
+2 -2
View File
@@ -133,7 +133,7 @@ import { version } from "react";
aliases: [("~lib".to_string(), d.join("lib/aliased.ts"))].into_iter().collect(),
stubs: vec!["fs".into()],
};
let o = raea_bundle::Options { z3: false, script: Some(script.clone()), defines: vec![("FLAG".into(), "\"ON\"".into())], edit: None, stamps: false, ..Default::default() };
let o = raea_bundle::Options { z3: false, script: Some(script.clone()), defines: vec![("FLAG".into(), "\"ON\"".into())], edit: None, stamps: false };
let b = raea_bundle::bundle_with(&d.join("work/entry.ts"), o).expect("bundles");
for want in ["MOTION_INDEX", "MOTION_ECS", "MOTION_PRELUDE", "TEST_SHIM:", "ZLIB_SHIM", "ALIASED", "ENGINE_REACT", "isn't available in raea's V8", "\"ON\""] {
assert!(b.js.contains(want), "{want} in the bundle: {}", b.js);
@@ -141,7 +141,7 @@ import { version } from "react";
assert!(!b.js.contains("OTHER_REACT"), "one React: the engine's");
// a Node built-in raea doesn't carry, not listed as a stub: the bundle fails, naming it
w("work/bad.ts", "import { createServer } from \"http\";\nconsole.log(createServer);\n");
let e = raea_bundle::bundle_with(&d.join("work/bad.ts"), raea_bundle::Options { z3: false, script: Some(script), defines: vec![], edit: None, stamps: false, ..Default::default() }).expect_err("http isn't carried");
let e = raea_bundle::bundle_with(&d.join("work/bad.ts"), raea_bundle::Options { z3: false, script: Some(script), defines: vec![], edit: None, stamps: false }).expect_err("http isn't carried");
assert!(e.contains("\"http\" is a Node built-in") && e.contains("--node-stub http"), "{e}");
let _ = std::fs::remove_dir_all(&d);
}
-2
View File
@@ -85,8 +85,6 @@ raea-app-media = { path = "../../apps/media" }
# `raea app run|check|bundle` and `raea rune` on either target (docs/targets.feature T0b)
raea-app-targets = { path = "../../apps/targets" }
raea-app-game = { path = "../../apps/game" }
# `raea playable`: a game as a playable ad for each network (docs/playables.feature PA13)
raea-app-playable = { path = "../../apps/playable" }
raea-app-capcut = { path = "../../apps/capcut" }
raea-app-layers = { path = "../../apps/layers" }
raea-app-play = { path = "../../apps/play", features = ["ml"] }
-72
View File
@@ -110,75 +110,3 @@ describe("labelsIn", () => {
expect(() => labelsIn('{"text":"a"}', "l.json")).toThrow(/--labels l.json is a list of labels/);
});
});
// Shane 11-28: "some things I'm not approving, I'm just acknowledging"; "the agent can go 'let me add a label here'".
// --fyi and --group go to the host (apps/app host/show.ts ShowBody.intent, .groups), which hands them to the review.
describe("raea show --fyi and --group", () => {
const run = (args: string[]) => {
const ops: [string, Record<string, unknown>][] = [];
const ask = (op: string, b: Record<string, unknown>) => {
ops.push([op, b]);
if (op === "harness") return { name: "Claude Code", pid: 7 };
return { kind: "item", id: "i-1", type: "look", title: "Lobby", project: "shop", workspace: "Work", inbox: "/inbox.jsonl" };
};
const out = showVerb(ask, args, "/work/shop", { CLAUDECODE: "1", CLAUDE_CODE_SESSION_ID: "abcdef123" });
return { out, body: ops.find(([op]) => op === "show")?.[1] };
};
test("--fyi sends a look-only show, and says nothing waits on it", () => {
const { out, body } = run(["lobby.png", "--fyi"]);
expect(body).toMatchObject({ intent: "fyi", files: ["/work/shop/lobby.png"] });
expect(out).toContain(`{"kind":"seen"}`);
expect(run(["lobby.png"]).body?.intent).toBeUndefined();
});
test("each --group holds the files after it, titled before the colon and said after it", () => {
const { body } = run(["--group", "Day: sun through the doors", "a.png", "b.png", "--group", "Night", "c.png", "--title", "Lobby"]);
expect(body?.files).toEqual(["/work/shop/a.png", "/work/shop/b.png", "/work/shop/c.png"]);
expect(body?.groups).toEqual([
{ title: "Day", says: "sun through the doors", files: ["/work/shop/a.png", "/work/shop/b.png"] },
{ title: "Night", files: ["/work/shop/c.png"] },
]);
expect(run(["a.png"]).body?.groups).toBeUndefined();
});
test("a group with no files, or --fyi on a question, is refused", () => {
expect(() => run(["a.png", "--group", "Empty"])).toThrow(/has no files/);
expect(() => run(["--group", ": no title", "a.png"])).toThrow(/is a title/);
expect(() => run(["--question", "Which?", "--choice", "A", "--choice", "B", "--fyi"])).toThrow(/--fyi/);
});
});
// --playable exports a game's preview (native.ts playable: raea playable --networks preview) and shows that page, which
// the app plays in a phone (apps/app host/playable.ts, docs/playables.feature PA16)
describe("raea show --playable", () => {
const run = (args: string[]) => {
const ops: [string, Record<string, unknown>][] = [];
const ask = (op: string, b: Record<string, unknown>) => {
ops.push([op, b]);
if (op === "harness") return { name: "Claude Code", pid: 7 };
if (op === "playable") return { page: "/tmp/raea-playable-x/acana-preview.html" };
return { kind: "item", id: "i-1", type: "play", title: "Acana", project: "ads", workspace: "Work", inbox: "/inbox.jsonl" };
};
showVerb(ask, args, "/work/ads", { CLAUDECODE: "1", CLAUDE_CODE_SESSION_ID: "abcdef123" });
return { exported: ops.find(([op]) => op === "playable")?.[1], body: ops.find(([op]) => op === "show")?.[1] };
};
test("the game is exported, and its preview page is what's shown, titled from it", () => {
const { exported, body } = run(["compositions/acana.tsx", "--playable"]);
expect(exported).toMatchObject({ file: "/work/ads/compositions/acana.tsx" });
expect(body).toMatchObject({ files: ["/tmp/raea-playable-x/acana-preview.html"], title: "Acana" });
expect(run(["acana.tsx", "--playable", "--title", "ACANA catch"]).body?.title).toBe("ACANA catch");
});
test("it takes one game's .tsx and nothing else", () => {
expect(() => run(["a.tsx", "b.tsx", "--playable"])).toThrow(/one game's \.tsx/);
expect(() => run(["cut.mp4", "--playable"])).toThrow(/one game's \.tsx/);
});
test("without it a .tsx is shown as it is", () => {
const { exported, body } = run(["picker.tsx"]);
expect(exported).toBeUndefined();
expect(body?.files).toEqual(["/work/ads/picker.tsx"]);
});
});
+5 -5
View File
@@ -134,7 +134,7 @@ pub fn run(args: &[String]) -> R<String> {
IN_HELP.set(was);
// `raea library` (engine/cli/src/library.ts) and `raea show` (show.ts: in the raea app, not Preview, Shane 11-09), under render's usage
let usage = format!("{usage}\n raea library [new NAME [--cloud] | add LIBRARY PATH | files LIBRARY | tag SHA TAGS | status | scan ...] | raea library search \"WORDS\" [--library LIBRARY] [--kind KIND] [--limit N] [--sound] (the person's libraries in the raea app: folders and drives indexed on this machine, searched by meaning; a folder an agent adds waits for the person's yes)");
let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --label \"PLACE TAG\" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)");
let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), or questions, all of them one item; --label \"PLACE TAG\" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)");
// clothes for SOMA's body, sewn or laid on the skin (docs/character.feature CH45c): engine/cli/src/clothes.ts, wardrobe.ts and sewn.ts
let usage = format!("{usage}\n raea clothes [make NAME [\"WHAT IT IS\"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB] | settings | cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] [--hard [--sole MM] [--sole-colour #RRGGBB] [--panels #RRGGBB,...]] | wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR]] (clothes for SOMA's body from words: make sews a garment: a sewing pattern (GarmentCode, MIT) from the words, or the plain base with --plain, its settings changed by --set PATH=VALUE (settings lists them and what each may be), cut to SOMA's measurements, draped by raea's own cloth and baked, as assets/clothes/NAME.json and its .glb, in --colour or the palette's next; the first make sets up GarmentCode and its Python in raea's models folder; cover makes one by procedure in the same file, no picture: the skin of the parts named (hips, waist, torso, chest, neck, head, upperArm, foreArm, hand, thigh, shin, foot, toes; a limb's SHARE is how far along it from its top), in one colour, MM off the skin (6 unless said), --over a garment already made as the one under it; wear puts garments on a body, innermost first (each GARMENT a name or its .json): OUT_DIR/NAME.glb each, with OUT_DIR/body.glb the body without the skin wholly under cloth; --body DIR another SOMA body folder (a headless one for a head part); --head HEAD_DIR the head that joins it (head.json), whose skin the body's is graded to at the collar; alone, the project's garments. The first use fetches SOMA's body (NVlabs/SOMA-X, Apache-2.0) into raea's models folder and needs Blender: raea setup blender)");
// body motion made by Kimodo, on MLX on a Mac and on PyTorch elsewhere (docs/character.feature CH15c):
@@ -147,7 +147,7 @@ pub fn run(args: &[String]) -> R<String> {
let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|parts] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, NAME.parts.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] [--client NAME] | raea project tag [NAME] [--client NAME] [--no-client] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; its client, what raea.app files every card shown from it under (raea cloud's tags: projects don't nest); split and join keep its history)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {} ({})\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, tools::motion::SETUP_USAGE, tools::motion::SETUP_ABOUT, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);
let (export_game, capcut, layers, xml, scene, physics, splat, wear, bake) = (raea_app_game::USAGE, raea_app_capcut::USAGE, raea_app_layers::USAGE, raea_app_layers::USAGE_XML, raea_app_scene::USAGE, motion::physics::USAGE, tools::splat::USAGE, raea_runtime_wear::USAGE, raea_app_lightbake::USAGE);
let apps = format!(" {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n", raea_app_direction::check::USAGE, raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_ask::USAGE, raea_app_make::USAGE, raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::USAGE, raea_app_fingerprint::USAGE, raea_sys_index::cli::USAGE);
return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea component list | raea component add NAME ... [--shared] [--force] | raea part list | raea part add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; raea part is its old name)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {} ({})\n {capcut}\n {layers}\n {xml}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n {} (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)", raea_app_playable::USAGE, raea_app_playable::ABOUT, raea_denoise_bench::USAGE));
return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea component list | raea component add NAME ... [--shared] [--force] | raea part list | raea part add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; raea part is its old name)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {capcut}\n {layers}\n {xml}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n {} (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)", raea_denoise_bench::USAGE));
}
// `--version`: the release's version, which a skill's front matter names (docs/skills.feature SK6)
if args.len() == 1 && matches!(args[0].as_str(), "--version" | "-V") {
@@ -228,9 +228,9 @@ pub fn run(args: &[String]) -> R<String> {
// `export capcut EDIT.tsx` (a CapCut draft) and `render ... -o OUT.mov --alpha` (a transparent movie): apps/capcut
if let Some(done) = raea_app_capcut::cli(args, |a| raea_app_sound::render(a).unwrap_or_else(|| raea_runtime_export::render(a))) { return done; }
// `export-game EDIT.tsx -o OUT`: the game as a program of its own (game.rs, sdk/react/docs/game-export.md)
if args[0] == "export-game" { return raea_app_game::export(args); }
// `playable GAME.tsx -o DIR`: the game as a playable ad, a page or ZIP per network (apps/playable, docs/playables.feature)
if args[0] == "playable" { return raea_app_playable::cli(args); }
if args.first().map(String::as_str) == Some("export-game") {
return raea_app_game::export(args);
}
// `add PKG... [--dev] | remove NAME... | install [--offline] [--in DIR]`: npm packages for the project (its
// package.json and raea.lock, a pnpm-style node_modules from one verified store; install scripts never run), which
// a composition, an app screen or a legacy-app panel imports (io/npm)
-14
View File
@@ -416,8 +416,6 @@ const host: Host = (op, a) => {
return library(a);
case "show":
return show(a);
case "playable":
return playable(a as { file: string });
case "clothes":
return clothesHost(raea, cwd, process.env, a);
case "bug":
@@ -447,15 +445,3 @@ const r = await raeaHandler(host, engine)(args, { cwd, fs });
process.stdout.write(r.stdout);
process.stderr.write(r.stderr);
process.exitCode = r.exitCode;
/** `raea show GAME.tsx --playable` (show.ts): the game's preview page, exported by `raea playable` into a folder of its
* own (the show copies it into the app's media) */
function playable(a: { file: string }): { page: string } {
const out = mkdtempSync(`${tmpdir()}/raea-playable-`);
const r = spawnSync(raea, ["playable", a.file, "-o", out, "--networks", "preview"], { encoding: "utf8" });
if (r.status !== 0) throw new Error(`raea playable refused ${basename(a.file)}: ${`${r.stdout ?? ""}${r.stderr ?? ""}`.trim().slice(0, 1200)}`);
const page = readdirSync(out).find((f) => f.endsWith("-preview.html"));
if (!page) throw new Error(`raea playable made no preview page for ${basename(a.file)}`);
return { page: `${out}/${page}` };
}
+7 -38
View File
@@ -23,18 +23,10 @@ raea show [--title T] --question Q1 [--preview FILE] --choice A [--preview FILE]
It lands in the person's feed with a notice and the window stays where they are; --open brings the window up on it
(only when they're waiting on it).
FILE: stills (several make a storyboard), a video, a sound, a NAME.script.ts or .md, or a .tsx (an interactive
artifact; one of the project's compositions opens in its editor), or a playable ad's .html (raea playable's
NAME-preview.html: it plays in a phone, sandboxed). --playable takes a game's .tsx, exports its preview with
\`raea playable\` and shows that page. P: Workspace/id (ids as raea workspace --json
artifact; one of the project's compositions opens in its editor). P: Workspace/id (ids as raea workspace --json
lists them), a folder in the project, or a Copy reference from the app; a title only when it's the only one and
this folder isn't in another project. Else the one this folder is in. Who's showing it: --as NAME [--role ROLE]
[--inbox NAME], else your harness's.
raea show FILE... --fyi
Only for the person to look at, nothing to approve: they say Got it (you hear {"kind":"seen"}), and anything they
want to say back comes through the chat. Without it a show is a version for them to approve or send notes on.
raea show --group "Day: sun through the doors" A.png B.png --group "Night: practicals only" C.png [--title T]
Lay the files out in groups the person sees side by side, each titled before the colon and said after it in a plain
line (never shorthand); the files after a --group are its own. Keep it short: enough to know what each group is.
raea show FILE... --despite CHECK "why"
A render that still holds an error (raea findings --open lists them) isn't shown: fix it and render again, or say
why it goes anyway, once per check; the person reads the why on the item. One let through at the render (raea render
@@ -58,8 +50,8 @@ raea show FILE... --replaces ITEM --done ID...
closes when the person retires it, never with --done. raea notes post sends all of these from the notes.
`;
const WITH_VALUE = new Set(["--group", "--despite", "--label", "--detail", "--labels", "--title", "--ask", "--project", "--replaces", "--as", "--role", "--inbox", "--question", "--choice", "--preview", "--on", "--working", "--done", "--note", "--sub", "--status", "--states", "--sign", "--clip", "--render"]);
const FLAGS = new Set(["--open", "--fyi", "--playable"]);
const WITH_VALUE = new Set(["--despite", "--label", "--detail", "--labels", "--title", "--ask", "--project", "--replaces", "--as", "--role", "--inbox", "--question", "--choice", "--preview", "--on", "--working", "--done", "--note", "--sub", "--status", "--states", "--sign", "--clip", "--render"]);
const FLAGS = new Set(["--open"]);
/** The harness an agent runs in, named as the feed shows it, from the program that started this command (native.ts
* walks up its parents): any harness, not only the ones that mark their shells. */
@@ -92,8 +84,6 @@ const hash = (s: string) => {
return h.toString(36);
};
const marking = (args: string[]) => args.includes("--working") || args.includes("--done");
export function parseShow(args: string[], cwd: string) {
const one = (name: string) => {
const i = args.lastIndexOf(name);
@@ -105,19 +95,7 @@ export function parseShow(args: string[], cwd: string) {
if (unknown) throw new Error(`no ${unknown} here\n${SHOW_USAGE}`);
const abs = (f: string) => fromCwd(cwd, f);
// --despite takes two: the check, then why
const isFile = (a: string, i: number) => !a.startsWith("--") && !WITH_VALUE.has(args[i - 1] ?? "") && args[i - 2] !== "--despite";
const files = args.filter(isFile).map(abs);
// the groups in order: each --group "Title: what it is" holds the files after it, up to the next --group
const groups: { title: string; says?: string; files: string[] }[] = [];
args.forEach((a, i) => {
if (a === "--group" && args[i + 1] !== undefined) {
const [title, ...rest] = args[i + 1].split(":");
if (!title.trim()) throw new Error(`--group "${args[i + 1]}" is a title, then what it is after a colon: --group "Night: practicals only"\n${SHOW_USAGE}`);
groups.push({ title: title.trim(), ...(rest.join(":").trim() ? { says: rest.join(":").trim() } : {}), files: [] });
} else if (groups.length && isFile(a, i)) groups.at(-1)!.files.push(abs(a));
});
const empty = groups.find((g) => !g.files.length);
if (empty) throw new Error(`the group "${empty.title}" has no files: put its files after its --group\n${SHOW_USAGE}`);
const files = args.filter((a, i) => !a.startsWith("--") && !WITH_VALUE.has(args[i - 1] ?? "") && args[i - 2] !== "--despite").map(abs);
const despite = args.flatMap((a, i) => {
if (a !== "--despite") return [];
const [check, why] = [args[i + 1], args[i + 2]];
@@ -156,8 +134,7 @@ export function parseShow(args: string[], cwd: string) {
if ((labels.length || args.includes("--labels")) && (!files.length || questions || asked.length)) throw new Error(`labels go on the files you show: raea show FILE --label "PLACE TAG"\n${SHOW_USAGE}`);
if (labels.length && args.includes("--labels")) throw new Error(`--label or --labels, not both\n${SHOW_USAGE}`);
if (questions && files.length) throw new Error(`with several questions or previews, each file is a --preview of the question or choice it shows\n${SHOW_USAGE}`);
if (args.includes("--fyi") && (asked.length || marking(args))) throw new Error(`--fyi shows files only to be looked at: a question, or marking comments, is answered\n${SHOW_USAGE}`);
return { groups, fyi: args.includes("--fyi"), labels, labelsFile: one("--labels"), files, despite, choices, questions, open: args.includes("--open"), playable: args.includes("--playable"), title: one("--title"), ask: one("--ask"), asks: many("--ask"), project: one("--project"), replaces: one("--replaces"), question: questions ? undefined : one("--question"), as: one("--as"), role: one("--role"), inbox: one("--inbox"), on: one("--on"), working: many("--working"), done: many("--done"), note: one("--note"), sub: one("--sub"), status: one("--status"), states: one("--states")?.split(",").map((s) => s.trim()).filter(Boolean), sign: one("--sign"), clip: one("--clip"), render: one("--render") };
return { labels, labelsFile: one("--labels"), files, despite, choices, questions, open: args.includes("--open"), title: one("--title"), ask: one("--ask"), asks: many("--ask"), project: one("--project"), replaces: one("--replaces"), question: questions ? undefined : one("--question"), as: one("--as"), role: one("--role"), inbox: one("--inbox"), on: one("--on"), working: many("--working"), done: many("--done"), note: one("--note"), sub: one("--sub"), status: one("--status"), states: one("--states")?.split(",").map((s) => s.trim()).filter(Boolean), sign: one("--sign"), clip: one("--clip"), render: one("--render") };
}
/** A --labels file's labels, as feed_post takes them: a list, or { "labels": [...] } (raea media sheet's OUT.labels.json). */
@@ -212,13 +189,7 @@ export function showVerb(ask: Ask, args: string[], cwd: string, env: Record<stri
if (a.done.length && !a.replaces) throw new Error(`--done with files settles comments on the item they replace: add --replaces ITEM\n${SHOW_USAGE}`);
if (a.labelsFile !== undefined && !listed) throw new Error(`--labels ${a.labelsFile}: its labels weren't read (raea's own handler reads the file)`);
const labels = a.labels.length ? a.labels : listed;
// --playable: the game's preview exported (raea playable --networks preview) and that page shown (docs/playables.feature PA16)
if (a.playable) {
if (a.files.length !== 1 || !/\.tsx$/.test(a.files[0]) || a.question || a.questions) throw new Error(`--playable shows one game's .tsx as its playable: raea show GAME.tsx --playable\n${SHOW_USAGE}`);
a.files = [(ask("playable", { file: a.files[0], cwd }) as { page: string }).page];
a.title ??= a.files[0].replace(/^.*[\\/]/, "").replace(/-preview\.html$/, "").replace(/[-_]+/g, " ").replace(/^\w/, (c) => c.toUpperCase());
}
const r = ask("show", { ...(labels?.length ? { labels } : {}), ...(a.fyi ? { intent: "fyi" } : {}), ...(a.groups.length ? { groups: a.groups } : {}), files: a.files, despite: a.despite, title: a.title, ask: askWith(a.ask, a.despite), question: a.question, choices: a.choices, questions: a.questions, open: a.open, project: a.project, replaces: a.replaces, cwd, by }) as
const r = ask("show", { ...(labels?.length ? { labels } : {}), files: a.files, despite: a.despite, title: a.title, ask: askWith(a.ask, a.despite), question: a.question, choices: a.choices, questions: a.questions, open: a.open, project: a.project, replaces: a.replaces, cwd, by }) as
| { opened: string[] }
| { kind: "item" | "composition"; id: string; type: string; title: string; project: string; workspace: string; inbox: string; brought?: boolean };
if ("opened" in r) return `The raea app isn't on this Mac, so ${r.opened.length === 1 ? "it opened" : `${r.opened.length} files opened`} in the Mac's own viewer: nothing was posted and nothing comes back. Install raea (raea.io) to show work as items the person can answer.\n`;
@@ -242,9 +213,7 @@ export function showVerb(ask: Ask, args: string[], cwd: string, env: Record<stri
? `Shown in the raea app: "${r.title}" (${r.type}, item ${r.id}, project ${r.project} in ${r.workspace}); the window is on it.`
: `Posted in the raea app: "${r.title}" (${r.type}, item ${r.id}, project ${r.project} in ${r.workspace}), with a notice; the window stayed where the person is.`,
...settled,
a.fyi
? `Only to look at: when they've seen it, {"kind":"seen"} comes to ${inbox}; nothing to wait for.`
: `What the person sends on it (notes, edits, picks, answers, results) comes to ${inbox}, one JSON line each. Follow it (tail -n0 -F ${inbox}, or your harness's monitor) and answer each; a next version is raea show --replaces ${r.id} FILE.`,
`What the person sends on it (notes, edits, picks, answers, results) comes to ${inbox}, one JSON line each. Follow it (tail -n0 -F ${inbox}, or your harness's monitor) and answer each; a next version is raea show --replaces ${r.id} FILE.`,
"",
].join("\n");
}
+1 -1
View File
@@ -32,7 +32,7 @@ fn help_lists_every_verb() {
let listed = |v: &str| [format!("raea {v} "), format!("raea {v}\n"), format!("| {v} ")].iter().any(|l| help.contains(l.as_str()));
let missing: Vec<_> = verbs.iter().filter(|v| !listed(v) && !unlisted.contains(&v.as_str())).collect();
assert!(missing.is_empty(), "not in raea help: {missing:?}");
for usage in [raea_app_check::USAGE, raea_app_ask::USAGE, raea_app_direction::check::USAGE, raea_app_direction::USAGE, raea_app_notes::USAGE, raea_app_game::USAGE, raea_app_playable::USAGE, raea_app_scene::USAGE, raea_app_voice::USAGE, motion::physics::USAGE, raea_runtime_wear::USAGE, tools::splat::USAGE, tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_make::USAGE, tools::blender::USAGE, raea_app_lightbake::USAGE] {
for usage in [raea_app_check::USAGE, raea_app_ask::USAGE, raea_app_direction::check::USAGE, raea_app_direction::USAGE, raea_app_notes::USAGE, raea_app_game::USAGE, raea_app_scene::USAGE, raea_app_voice::USAGE, motion::physics::USAGE, raea_runtime_wear::USAGE, tools::splat::USAGE, tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_make::USAGE, tools::blender::USAGE, raea_app_lightbake::USAGE] {
assert!(help.contains(usage), "{usage}");
}
}
-4
View File
@@ -13,7 +13,3 @@ serde_json = "1"
raea-runtime-bundle = { path = "../../runtime/bundle" }
# the home folder on every OS (HOME, then USERPROFILE)
raea-io-home = { path = "../../io/home" }
# a held frame's findings kept in its project's record, where raea check and raea findings read them
raea-core-facts = { path = "../../core/facts" }
# the record's UTC stamp, as raea render's
raea-io-trace = { path = "../../io/trace" }
-176
View File
@@ -1,176 +0,0 @@
//! What moves in a held frame, told apart (steady.rs measures how much). One number hid four things that have
//! different causes and different fixes (MALL RAT, 11-25: take 1 failed on edges, take 2 on patches):
//!
//! - **settling**: a square whose level climbs or falls steadily through the window. The light is still building (a
//! world cache lit a ray a cell a frame takes hundreds of frames in a closed court): hold longer before measuring,
//! and give a render the same lead-in.
//! - **boiling**: a square that wanders slowly about its level (each frame close to the last: lag-1 correlation over
//! SLOW). Traced light's patches: too few rays behind a denoiser. More paths, a cache that converges.
//! - **jitter**: a square that repeats on a short cycle (the camera's sub-pixel jitter is 8 frames long). An edge the
//! temporal resolve isn't holding: a silhouette against the sky or a clipped-bright doorway steps a pixel a frame.
//! Doors, walls and beams look as if they shake.
//! - **flicker**: fast and without a cycle. A firefly, a sparkle in a reflection, two faces fighting for one depth.
//!
//! Each is each LARGE square's deviation in time over its mean, with its straight-line trend taken out first, counted
//! to the kind the square's own series shows, and reported as the rms over every lit square (the others counting as
//! zero, so the four add in squares to the whole), with the worst square and where it is.
use crate::metric::Luma;
use serde_json::{json, Value};
/// A square whose deviation is under this (a fraction of its level) isn't moving: no kind.
const QUIET: f64 = 0.0015;
/// Lag-1 correlation from which a square's movement is slow.
const SLOW: f64 = 0.5;
/// The correlation with itself a cycle later from which a square repeats.
const REPEATS: f64 = 0.6;
/// The longest cycle looked for, frames (the jitter's is 8; a 16-frame sequence is the longest raea uses).
const CYCLE: usize = 16;
/// Below this level (linear, a twentieth of white: about 5 cd/m2 on a 100 cd/m2 display) a change shows less than its
/// ratio to the level says. The eye's contrast threshold is constant in bright light (Weber) and rises as the square
/// root of falling luminance in dim light (de Vries-Rose; Barten's contrast sensitivity model has both). Measured as a
/// plain ratio, MALL RAT's worst squares were its darkest corners (t5 1440, t8 510: 12% and 6% of nearly nothing).
const DIM: f64 = 0.05;
/// The level a square's deviation is a fraction of: its mean in bright light, and sqrt(mean x DIM) below DIM, so a
/// dark square's movement counts by how much of it shows.
pub fn shown_level(mean: f64, lit: f64) -> f64 {
let m = mean.max(lit);
if m >= DIM { m } else { (m * DIM).sqrt() }
}
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Kind {
Still,
Boiling,
Jitter,
Flicker,
}
/// One square's series read: its kind, its deviation over its level (trend out), its trend across the window over its
/// level, and the cycle it repeats on (0: none).
pub fn read(series: &[f64], lit: f64) -> (Kind, f64, f64, usize) {
let n = series.len();
let mean = series.iter().sum::<f64>() / n as f64;
let mid = (n as f64 - 1.0) / 2.0;
let slope = series.iter().enumerate().map(|(t, v)| (t as f64 - mid) * v).sum::<f64>() / (0..n).map(|t| (t as f64 - mid).powi(2)).sum::<f64>().max(1e-12);
let r: Vec<f64> = series.iter().enumerate().map(|(t, v)| v - mean - slope * (t as f64 - mid)).collect();
let var = r.iter().map(|v| v * v).sum::<f64>() / n as f64;
let level = shown_level(mean, lit);
let (dev, trend) = (var.sqrt() / level, slope.abs() * (n as f64 - 1.0) / level);
if dev < QUIET {
return (Kind::Still, dev, trend, 0);
}
// the series against itself p frames later, as a correlation
let corr = |p: usize| r[p..].iter().zip(&r).map(|(a, b)| a * b).sum::<f64>() / (n - p) as f64 / var.max(1e-18);
let slow = corr(1) >= SLOW;
let (mut cycle, mut best) = (0, 0.0);
for p in 2..=CYCLE.min(n / 3) {
let c = corr(p);
if c > best {
(cycle, best) = (p, c);
}
}
if !slow && best >= REPEATS {
(Kind::Jitter, dev, trend, cycle)
} else if slow {
(Kind::Boiling, dev, trend, 0)
} else {
(Kind::Flicker, dev, trend, 0)
}
}
/// The kinds of a window of held frames: the report's fields, and a picture at the frame's size (red: jitter and
/// flicker, green: boiling, blue: settling; each white at `shown` percent).
pub fn kinds(frames: &[Luma], k: usize, lit: f64, shown: f64) -> (Value, image::RgbImage) {
let blocks: Vec<Luma> = frames.iter().map(|f| f.blocks(k)).collect();
let (w, h) = (blocks[0].w, blocks[0].h);
let pct = |v: f64| (v * 1e4).round() / 100.0;
let mut sums = [0.0f64; 4];
let mut counts = [0usize; 4];
let mut worst = [(0.0f64, 0usize); 4];
let mut cycles = vec![0usize; CYCLE + 1];
let (mut trends, mut lit_n) = (Vec::new(), 0usize);
let mut px = vec![[0u8; 3]; w * h];
let level = |v: f64| (v * 100.0 / shown * 255.0).min(255.0) as u8;
for i in 0..w * h {
let series: Vec<f64> = blocks.iter().map(|b| b.y[i] as f64).collect();
if series.iter().sum::<f64>() / series.len() as f64 <= lit {
continue;
}
lit_n += 1;
let (kind, dev, trend, cycle) = read(&series, lit);
trends.push(trend);
let j = kind as usize;
sums[j] += dev * dev;
counts[j] += 1;
if dev > worst[j].0 {
worst[j] = (dev, i);
}
cycles[cycle] += usize::from(kind == Kind::Jitter);
px[i] = match kind {
Kind::Still => [0, 0, level(trend)],
Kind::Boiling => [0, level(dev), level(trend)],
Kind::Jitter | Kind::Flicker => [level(dev), 0, level(trend)],
};
}
trends.sort_by(|a, b| a.total_cmp(b));
let at = |q: f64| trends.get(((trends.len() as f64 - 1.0) * q).round() as usize).copied().unwrap_or(0.0);
let one = |j: usize| json!({ "rms": pct((sums[j] / lit_n.max(1) as f64).sqrt()), "squares": counts[j], "worst": pct(worst[j].0), "worst_at": [worst[j].1 % w * k, worst[j].1 / w * k] });
let cycle = cycles.iter().enumerate().max_by_key(|c| *c.1).filter(|c| *c.1 > 0).map_or(0, |c| c.0);
let report = json!({
"boiling": one(Kind::Boiling as usize), "jitter": one(Kind::Jitter as usize), "flicker": one(Kind::Flicker as usize),
"cycle": cycle, "settling": { "median": pct(at(0.5)), "p95": pct(at(0.95)) },
});
let picture = image::RgbImage::from_fn((w * k) as u32, (h * k) as u32, |x, y| image::Rgb(px[y as usize / k * w + x as usize / k]));
(report, picture)
}
#[cfg(test)]
mod tests {
use super::*;
fn rnd(seed: &mut u32) -> f64 {
*seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
(*seed >> 8) as f64 / (1u32 << 24) as f64 * 2.0 - 1.0
}
#[test]
fn each_kind_of_movement_is_told_from_the_others() {
let mut s = 3u32;
// a level that climbs 10% and nothing else: still, with its trend
let climb: Vec<f64> = (0..75).map(|t| 0.3 * (1.0 + 0.1 * t as f64 / 74.0)).collect();
let (kind, dev, trend, _) = read(&climb, 0.004);
assert_eq!(kind, Kind::Still);
assert!(dev < 1e-6 && (trend - 0.0952).abs() < 0.01, "{dev} {trend}");
// a slow wander: each frame a small step from the last
let mut v = 0.0;
let wander: Vec<f64> = (0..75).map(|_| { v = 0.92 * v + 0.01 * rnd(&mut s); 0.3 * (1.0 + v) }).collect();
assert_eq!(read(&wander, 0.004).0, Kind::Boiling);
// the jitter's cycle: eight levels, again and again, with a little grain on top
let phase = [7.5, 1.7, 2.6, 10.4, 1.7, 5.6, 11.3, 1.7];
let cycle: Vec<f64> = (0..75).map(|t| 0.02 * phase[t % 8] * (1.0 + 0.02 * rnd(&mut s))).collect();
let (kind, dev, _, p) = read(&cycle, 0.004);
assert_eq!((kind, p), (Kind::Jitter, 8));
assert!(dev > 0.5, "{dev}");
// new every frame: flicker
let fast: Vec<f64> = (0..75).map(|_| 0.3 * (1.0 + 0.05 * rnd(&mut s))).collect();
assert_eq!(read(&fast, 0.004).0, Kind::Flicker);
// and a climb under a wander is still boiling, its trend kept apart
let both: Vec<f64> = wander.iter().enumerate().map(|(t, v)| v + 0.03 * t as f64 / 74.0).collect();
let (kind, _, trend, _) = read(&both, 0.004);
assert_eq!(kind, Kind::Boiling);
assert!(trend > 0.05, "{trend}");
}
#[test]
fn a_dark_squares_movement_counts_for_less_than_its_ratio() {
let mut s = 5u32;
let series = |level: f64, s: &mut u32| -> Vec<f64> { (0..75).map(|_| level * (1.0 + 0.05 * rnd(s))).collect() };
let (lit, dark) = (read(&series(0.3, &mut s), 0.004).1, read(&series(0.005, &mut s), 0.004).1);
// the same 5% ratio: counted whole at a lit level, and by sqrt(0.005 / 0.05) at a dark one
assert!((dark / lit - (0.005f64 / 0.05).sqrt()).abs() < 0.05, "{dark} {lit}");
assert_eq!(shown_level(0.05, 0.004), 0.05);
}
}
+4 -6
View File
@@ -13,7 +13,6 @@
//! live stage, 1920x1080 by default) }.
pub mod metric;
mod kinds;
pub mod steady;
use raea_runtime_bundle::{flag, R};
@@ -115,10 +114,9 @@ pub fn render_with(scene: &Scene, label: &str, env: &[(&str, String)], at: &[i64
let run = cmd
.args(["render", &scene.file, "--composition", &scene.composition, "--at", &at.join(","), "-o"])
.arg(format!("{}/", out.display()))
// a light check measures light, not placement or camera: a set's clip (11-24: FLOOR3's fit-2 1 cm into
// grid-bay) and a contact sheet's cuts read as a lurching camera (11-25: gambit-street refused, every scene
// after it unmeasured) are the piece's to fix and stay in its record, but don't stop the measure
.args(["--despite", "all", "raea light check measures light, not placement or camera"])
// a light check measures light, not placement: a set's clip (11-24: FLOOR3's fit-2 1 cm into grid-bay) is the
// set's to fix and stays in its record, but doesn't stop the measure
.args(["--despite", "clips", "raea light check measures light, not placement"])
.output()
.map_err(|e| e.to_string())?;
if !run.status.success() {
@@ -353,7 +351,7 @@ pub fn light(args: &[String]) -> R<String> {
// won't be the same the next time
let moved: Vec<String> = reports.iter().flat_map(|r| r["paths"].as_object().into_iter().flatten().filter(|(_, p)| p["steady"]["steady"] == json!(false)).map(|(path, p)| format!("{} on {path}: {}", r["name"].as_str().unwrap_or(""), steady::line(&p["steady"])))).collect();
if !moved.is_empty() {
return Err(format!("{said}\nthe light boils ({}). {}", moved.join("; "), steady::WHY));
return Err(format!("{said}\nthe light doesn't hold still ({}). {}", moved.join("; "), steady::WHY));
}
Ok(said)
}
+11 -101
View File
@@ -35,15 +35,6 @@ const MAX: f64 = 1.5;
const MAX_ENERGY: f64 = 0.25;
/// How far the held frame's level may move between the first and the last quarter of the measured frames, in stops.
const MAX_DRIFT: f64 = 0.05;
/// The frames measured: the last WINDOW of a hold (or its second half, if that's shorter). Fixed, because a slow
/// wander reads larger over a longer window, so two holds of different lengths wouldn't compare.
const WINDOW: usize = 75;
/// What the worst square that moves with the jitter, or flickers, may show, percent: an edge stepping a pixel a frame
/// reads 20 to 70; a resolved one under 2.
const MAX_FAST: f64 = 5.0;
/// The trend across the window a hold's squares may still have (the 95th percentile), percent: over it the light was
/// still building when it was measured, and what reads as boiling is partly that.
const MAX_SETTLING: f64 = 5.0;
/// Each square's mean and deviation in time over `frames`, side `k`: (w, h, [(mean, deviation / mean)]).
fn squares(frames: &[Luma], k: usize) -> (usize, usize, Vec<(f64, f64)>) {
@@ -66,7 +57,7 @@ fn rms(v: impl Iterator<Item = f64>) -> f64 {
}
/// The measure of held frames (the module's doc), and steady.png's picture: the large squares' deviation.
pub fn measure(frames: &[Luma]) -> R<(Value, image::GrayImage, image::RgbImage)> {
pub fn measure(frames: &[Luma]) -> R<(Value, image::GrayImage)> {
if frames.len() < 8 {
return Err(format!("{} held frames: 8 at least say whether the light holds still", frames.len()));
}
@@ -94,14 +85,12 @@ pub fn measure(frames: &[Luma]) -> R<(Value, image::GrayImage, image::RgbImage)>
let level = |f: &[Luma]| f.iter().map(|f| f.y.iter().map(|&v| v as f64).sum::<f64>() / f.y.len().max(1) as f64).sum::<f64>() / f.len() as f64;
let q = (frames.len() / 4).max(1);
let drift = (level(&frames[frames.len() - q..]).max(1e-6) / level(&frames[..q]).max(1e-6)).log2();
let (kinds, kinds_map) = crate::kinds::kinds(frames, LARGE, LIT, MAX_SHOWN);
let report = json!({
"kinds": kinds,
"drift": (drift * 1e3).round() / 1e3,
"frames": frames.len(), "blotch": pct(blotch), "grain": pct(grain), "spread": ((blotch / grain.max(1e-9)) * 100.0).round() / 100.0,
"worst": pct(worst.0), "worst_at": [worst.1, worst.2], "lit": ((large.iter().filter(lit).count() as f64 / large.len().max(1) as f64) * 100.0).round() / 100.0,
});
Ok((report, map, kinds_map))
Ok((report, map))
}
/// The PNG frames of a folder, in order.
@@ -152,26 +141,12 @@ pub fn report(dir: &Path, max: Option<f64>) -> R<Value> {
let max = max.unwrap_or(MAX);
// the second half: the first is the light building from nothing, which a render's lead-in covers
let files = held(dir)?;
let frames: Vec<Luma> = files[files.len() - WINDOW.min(files.len() - files.len() / 2)..].iter().map(|p| metric::load(p)).collect::<R<_>>()?;
let (mut report, map, kinds_map) = measure(&frames)?;
let frames: Vec<Luma> = files[files.len() / 2..].iter().map(|p| metric::load(p)).collect::<R<_>>()?;
let (mut report, map) = measure(&frames)?;
let png = dir.join("steady.png");
map.save(&png).map_err(|e| format!("{}: {e}", png.display()))?;
let kinds_png = dir.join("steady-kinds.png");
kinds_map.save(&kinds_png).map_err(|e| format!("{}: {e}", kinds_png.display()))?;
let get = |k: &str| report[k].as_f64().unwrap_or(0.0);
let kind = |k: &str, f: &str| report["kinds"][k][f].as_f64().unwrap_or(0.0);
// each kind against its own limit, and what failed named: the fixes differ
let mut failed: Vec<&str> = Vec::new();
if kind("boiling", "rms") > max || kind("boiling", "worst") > max * 3.0 { failed.push("boiling"); }
if kind("jitter", "worst") > MAX_FAST { failed.push("jitter"); }
if kind("flicker", "worst") > MAX_FAST { failed.push("flicker"); }
if get("drift").abs() > MAX_DRIFT { failed.push("drift"); }
let ok = failed.is_empty();
let unsettled = kind("settling", "p95") > MAX_SETTLING;
let failed: Vec<String> = failed.into_iter().map(String::from).collect();
report["failed"] = json!(failed);
report["unsettled"] = json!(unsettled);
report["kinds_picture"] = json!(kinds_png);
let ok = get("blotch") <= max && get("worst") <= max * 3.0 && get("drift").abs() <= MAX_DRIFT;
report["max"] = json!(max);
report["max_drift"] = json!(MAX_DRIFT);
report["steady"] = json!(ok);
@@ -182,74 +157,14 @@ pub fn report(dir: &Path, max: Option<f64>) -> R<Value> {
/// A report as one line.
pub fn line(r: &Value) -> String {
let k = &r["kinds"];
let one = |name: &str| format!("{name} {}% (worst {}% at {},{})", k[name]["rms"], k[name]["worst"], k[name]["worst_at"][0], k[name]["worst_at"][1]);
format!(
"{}{}, {}{}, {}, settling {}% (p95 {}%){}, drift {} stops (max {}); all movement {}% (blotch), grain {}%, spread {} over {} held frames; {}",
one("boiling"), format_args!(" (max {})", r["max"]), one("jitter"), if k["cycle"].as_u64().unwrap_or(0) > 0 { format!(" on a {}-frame cycle", k["cycle"]) } else { String::new() }, one("flicker"),
k["settling"]["median"], k["settling"]["p95"], if r["unsettled"] == json!(true) { " STILL SETTLING: hold longer (--frames) before reading the rest" } else { "" },
r["drift"], r["max_drift"], r["blotch"], r["grain"], r["spread"], r["frames"], r["kinds_picture"].as_str().unwrap_or("")
"drift {} stops (max {}), blotch {}% (max {}), worst {}% at {},{}, grain {}%, spread {} over {} held frames; {}",
r["drift"], r["max_drift"], r["blotch"], r["max"], r["worst"], r["worst_at"][0], r["worst_at"][1], r["grain"], r["spread"], r["frames"], r["picture"].as_str().unwrap_or("")
)
}
/// What a held frame that moves is told, by what moved.
pub fn why(r: &Value) -> String {
let failed: Vec<&str> = r["failed"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
let mut says: Vec<String> = Vec::new();
if failed.contains(&"boiling") || failed.contains(&"drift") { says.push(WHY.to_string()); }
if failed.contains(&"jitter") { says.push("Jitter: squares that repeat on a short cycle are edges stepping with the camera's sub-pixel jitter, which the temporal resolve should have held: a silhouette against the sky or a clipped-bright opening. Hold it with RAEA_SOLARI_AA=0 to confirm (it goes), then keep the bright side under the resolve's range (exposure, the sky's level) or report it".to_string()); }
if failed.contains(&"flicker") { says.push("Flicker: fast and without a cycle is a firefly, a sparkle in a reflection or two faces at one depth: look at the worst square in steady-kinds.png (red), and run raea scene lint for faces in one plane".to_string()); }
says.join(" ")
}
/// What a light that boils is told (boiling: the trade's word for low-frequency patches that crawl on a held frame).
pub const WHY: &str = "Boiling: patches this size are light built over frames that hasn't settled. On Solari, paths (SolariLighting paths={4}) first, then the world cache, ReSTIR's reuse or the denoiser. Hold the frame with each switched off in turn (cache.steady or a baked cache, RAEA_SOLARI_DENOISE=0, RAEA_SOLARI_PSR=0) to see which; DIR/render.log holds what each render said";
/// The check a held frame's findings carry in the project's record, which `raea check` reads for a traced composition.
pub const CHECK: &str = "light-steady";
/// A held frame's report as findings, one a kind that failed: about the composition, on the frame held.
pub fn findings(r: &Value, composition: Option<&str>, frame: i64) -> Vec<raea_core_facts::Finding> {
use raea_core_facts::{Finding, Level};
let k = &r["kinds"];
let num = |v: &Value| v.as_f64().unwrap_or(0.0);
let at = |name: &str| format!("{},{}", k[name]["worst_at"][0], k[name]["worst_at"][1]);
let mut out = Vec::new();
let mut push = |kind: &str, level: Level, says: String, value: f64, limit: f64, fix: &str| {
let mut f = Finding::new(CHECK, level, says, "raea light steady").frames(frame, frame + 1).measure(kind, value, "%", Some(limit)).fix(fix);
if let Some(c) = composition {
f = f.about(c, None);
}
out.push(f);
};
let failed: Vec<&str> = r["failed"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
let max = num(&r["max"]);
if failed.contains(&"boiling") {
push("boiling", Level::Error, format!("the light boils on frame {frame} held: {}% (worst square {}% at {}; max {max}, worst {})", k["boiling"]["rms"], k["boiling"]["worst"], at("boiling"), max * 3.0), num(&k["boiling"]["worst"]), max * 3.0, WHY);
}
if failed.contains(&"jitter") {
push("jitter", Level::Error, format!("edges step with the camera's jitter on frame {frame} held: worst square {}% at {} on a {}-frame cycle (max {MAX_FAST})", k["jitter"]["worst"], at("jitter"), k["cycle"]), num(&k["jitter"]["worst"]), MAX_FAST, "an edge against the sky, a forward mesh or an emitter left out of the denoiser's history: SolariLighting late and emissive=\"taa\" (the Solari guide)");
}
if failed.contains(&"flicker") {
push("flicker", Level::Error, format!("a square flickers on frame {frame} held: {}% at {} (max {MAX_FAST})", k["flicker"]["worst"], at("flicker")), num(&k["flicker"]["worst"]), MAX_FAST, "a firefly, a sparkle in a reflection or two faces in one plane: look at the square in steady-kinds.png, and run raea scene lint for faces in one plane");
}
if failed.contains(&"drift") {
push("drift", Level::Error, format!("the held frame's light drifts {} stops (max {MAX_DRIFT})", r["drift"]), num(&r["drift"]).abs(), MAX_DRIFT, WHY);
}
if failed.is_empty() {
push("steady", Level::Note, format!("the light holds still on frame {frame} held: {}", line(r)), num(&r["blotch"]), max, "");
}
if r["unsettled"] == json!(true) {
push("settling", Level::Note, format!("the light was still building on frame {frame} held (settling p95 {}%): hold longer, or give the shot a lead-in", k["settling"]["p95"]), num(&k["settling"]["p95"]), MAX_SETTLING, "a still lead-in before the shot, as long as the hold took to settle");
}
out
}
/// A held frame's findings kept in `file`'s project's record (nothing outside a project).
fn keep(file: &str, out: &Path, r: &Value, composition: Option<&str>, frame: i64) {
let stamp = raea_io_trace::utc(std::time::SystemTime::now()).1;
raea_core_facts::record::keep("raea light steady", Path::new(file), Some(out), &findings(r, composition, frame), Vec::new(), &stamp);
}
/// What a light that doesn't hold still is told.
pub const WHY: &str = "Patches this size are light built over frames that hasn't settled: on Solari the world cache, ReSTIR's reuse or the denoiser. Hold the frame with each switched off in turn (cache.steady or a baked cache, RAEA_SOLARI_DENOISE=0, RAEA_SOLARI_PSR=0) to see which; DIR/render.log holds what each render said";
pub fn steady(args: &[String]) -> R<String> {
let first = args.first().ok_or(format!("usage: {USAGE}"))?;
@@ -264,10 +179,6 @@ pub fn steady(args: &[String]) -> R<String> {
out
};
let mut r = report(&dir, max)?;
let held_frame = flag(args, "--frame").and_then(|f| f.parse::<i64>().ok());
if let (false, Some(f)) = (Path::new(first).is_dir(), held_frame) {
keep(first, dir.parent().unwrap_or(&dir), &r, flag(args, "--composition").as_deref(), f);
}
// --run M: the frame cold against the same frame at the end of M frames played up to it. A cache that gains or
// loses energy over minutes (MALL RAT's court, 11-24: 7 times brighter inside the long render) shows here and not
// in a hold
@@ -290,9 +201,9 @@ pub fn steady(args: &[String]) -> R<String> {
}
std::fs::write(dir.join("steady.json"), serde_json::to_string_pretty(&r).unwrap_or_default()).map_err(|e| e.to_string())?;
let said = format!("energy {} stops after {m} frames against the frame cold (max {MAX_ENERGY}), {}", r["energy"], line(&r));
return if r["steady"] == json!(true) { Ok(format!("STEADY {said}")) } else { Err(format!("the held frame moves ({}): {said}. {}", r["failed"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(", ")).unwrap_or_default(), why(&r))) };
return if r["steady"] == json!(true) { Ok(format!("STEADY {said}")) } else { Err(format!("the light doesn't hold still: {said}. {WHY}")) };
}
if r["steady"] == json!(true) { Ok(format!("STEADY {}", line(&r))) } else { Err(format!("the held frame moves ({}): {}. {}", r["failed"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(", ")).unwrap_or_default(), line(&r), why(&r))) }
if r["steady"] == json!(true) { Ok(format!("STEADY {}", line(&r))) } else { Err(format!("the light doesn't hold still: {}. {WHY}", line(&r))) }
}
#[cfg(test)]
@@ -320,7 +231,6 @@ mod tests {
#[test]
fn grain_is_steady_and_blotches_are_not() {
let still = measure(&frames(0.0, 0.0)).unwrap().0;
assert_eq!(still["kinds"]["boiling"]["rms"], 0.0);
assert_eq!(still["blotch"], 0.0);
assert_eq!(still["drift"], 0.0);
// a light that doubles over the held frames: about 0.8 of a stop between the first and the last quarter
-2
View File
@@ -11,8 +11,6 @@ description = "raea-render's ray tracing: Bevy's Solari for a scene whose camera
raea-io-trace = { path = "../../../io/trace" }
# the jitter's Halton places (a facility of raea-sys-post's steady)
raea-sys-post = { path = "../../../systems/post" }
# Overscan, the camera's wider view (the denoiser crops it back)
raea-sys-viewbox = { path = "../../../systems/viewbox" }
serde_json = "1"
# its own wgpu shaders read from a project's engine-shaders/ or the checkout (RAEA_ENGINE_SHADERS), as the embedded ones
raea-sys-engine-shaders = { path = "../../../systems/engine-shaders" }
+2 -28
View File
@@ -18,16 +18,6 @@ const HISTORY_CAP: f32 = 16.0;
// a still pixel's history held within what's about it now, its darkest and brightest times these
const STILL_LOW: f32 = 0.95;
const STILL_HIGH: f32 = 1.05;
// how far a still pixel's history goes toward those bounds a frame where it's thin (THIN). At 1, the default, it's held
// to them at once, and an emitter under a pixel tall, which some of the jitter's positions miss altogether, is cut to
// black on those frames and built again on the others: MALL RAT's ceiling tubes seen edge-on changed shape every frame
// (raea light steady: jitter 7% and 8% in their squares, 0.01% with the history always taken). At a quarter
// (<SolariLighting constants={{ emissiveClamp: { stillHold: 0.25 } }} />) they read 2.1% and 3.6%, and a 30000-nit
// orb switched off leaves its rim behind: +0.30 stops on its tile against +0.17, +0.26 eight frames on (lightbench
// window-still-off-q against -one). So it's a scene's choice until a pixel can count the frames it was missed
const STILL_HOLD: f32 = 1.0;
// a history counts as thin where the brighter of its two sides, two pixels off, is under this much of it
const THIN: f32 = 0.25;
// a moving pixel's history held under this many times the brightest about it, plus this
const MOVING_GAIN: f32 = 4.0;
const MOVING_FLOOR: f32 = 0.02;
@@ -200,23 +190,7 @@ fn restore_taa(@builtin(global_invocation_id) id: vec3<u32>) {
// them (a lamp switched off goes dark at once, rim and all, not over a second)
let reach = select(1.5, 1.05, still);
if (hd.b * reach >= zlo && hd.a <= zhi * reach && params[0].w != 3.0) {
// eased only where the history is a thin line or a point: an emitter under a pixel wide is all the jitter can miss outright. A lamp's or an orb's
// face and rim have light to one side, and go dark at once (RT32: eased everywhere, a 30000-nit orb
// switched off left +2.5 stops on its tile for 8 frames and +0.8 at 16; eased on thin histories, +0.30
// against +0.17 clamped at once, the orb's rim where it's dark to both sides)
var hold = 1.0;
if (still) {
let px = 2.0 / out_size;
let lw = vec3<f32>(0.2126, 0.7152, 0.0722);
let l0 = dot(hrgb, lw) * THIN;
let lx = max(dot(textureSampleLevel(hist_in, hist_sampler, was + vec2<f32>(px.x, 0.0), 0.0).rgb, lw), dot(textureSampleLevel(hist_in, hist_sampler, was - vec2<f32>(px.x, 0.0), 0.0).rgb, lw));
let ly = max(dot(textureSampleLevel(hist_in, hist_sampler, was + vec2<f32>(0.0, px.y), 0.0).rgb, lw), dot(textureSampleLevel(hist_in, hist_sampler, was - vec2<f32>(0.0, px.y), 0.0).rgb, lw));
// stricter tests of "thin" kept the orb's rim out (+0.18 by the second frame) and lost the tubes:
// a line alike along itself, 5.2 and 5.8%; a ring of eight with each lit place lit across, 6.2 and
// 6.5% (the tubes hang in rows, so a tube's neighbours light one side of it)
if (min(lx, ly) < l0) { hold = STILL_HOLD; }
}
hrgb = mix(hrgb, clamped, hold);
hrgb = clamped;
dbg_f += 8.0;
}
}
@@ -258,5 +232,5 @@ fn restore_taa(@builtin(global_invocation_id) id: vec3<u32>) {
textureStore(color, p, vec4<f32>(weight, hist.a / HISTORY_CAP, f32(hist.a > 0.0), c.a));
return;
}
textureStore(color, p, vec4<f32>(uncompress(c.rgb) + e, c.a));
textureStore(color, p, vec4<f32>(c.rgb + e, c.a));
}
-18
View File
@@ -58,16 +58,6 @@ pub struct SolariSettings {
/// what MetalFX divides the colour by before it denoises and multiplies it by after: bright light kept, at the cost
/// of fireflies past 16 (metalfx.rs pre_exposure; RAEA_METALFX_PREEXPOSURE)
pub preexposure: f32,
/// where the denoiser's soft knee starts, in its white (the colour at `preexposure / 16`); 0 turns it off
/// (RAEA_METALFX_KNEE). Above it a pixel's light goes in as its log: W (1 + ln(m / W)), its colour scaled to match,
/// and comes out undone after the denoiser. MetalFX averages a silhouette against bright sky or a lit doorway in
/// linear light, so its jittered edge pixel swung with the sky's share, 8 frames a cycle (MALL RAT t1 frame 1699:
/// steady 3.72, 0.81 with the jitter off). Light under the knee is untouched, so it isn't biased
pub knee: f32,
/// a full-size view denoised after the main pass instead of before it, so the sky and the forward meshes (drawn
/// there, with the jittered camera) are gathered over frames too and their edges stop stepping with the jitter
/// (metalfx.rs denoise_late; RAEA_SOLARI_DENOISE_LATE)
pub late: bool,
/// a full-size view jittered too, so the denoiser anti-aliases its edges as it gathers frames (RAEA_SOLARI_AA=0)
pub aa: bool,
/// which of MetalFX's passes is told the jitter: "" the denoiser, "scaler", "both", "flip", "0" none (and none is
@@ -84,11 +74,6 @@ pub struct SolariSettings {
/// the traced scene follows what moves: a skinned mesh's traced twin posed each frame (RT5, a trial;
/// RAEA_SOLARI_DYNAMIC). A hidden part leaves the traced scene with or without it (SG9)
pub dynamic: bool,
/// overscan: the main pass draws this much of the view more on every side (0.05 is a twentieth), and the denoiser
/// crops the middle back out, so the light at the frame's border has neighbours and history to gather from as the
/// camera moves (RT40; RAEA_SOLARI_OVERSCAN). 0, the default, is off. The view then draws at 1 / (1 + 2 x overscan)
/// of its size at most and is brought up; with the denoiser off, or `upscale` "two", it does nothing
pub overscan: f32,
}
impl Default for SolariSettings {
@@ -100,14 +85,11 @@ impl Default for SolariSettings {
emissive: "taa".into(),
upscale: "one".into(),
preexposure: 16.0,
knee: 1.0,
late: false,
aa: true,
jitter: String::new(),
emissive_sharpness: 6.0,
jitter_frames: 8.0,
dynamic: false,
overscan: 0.0,
}
}
}
+16 -85
View File
@@ -59,7 +59,6 @@ pub(crate) fn add(app: &mut App) {
};
core.add_systems(denoise.after(solari).before(main_opaque_pass_3d).in_set(Core3dSystems::MainPass));
core.add_systems(denoise_up.before(super::upscale::upscale).in_set(Core3dSystems::EarlyPostProcess));
core.add_systems(denoise_late.before(super::upscale::upscale).in_set(Core3dSystems::EarlyPostProcess));
// Solari's own guides (primary surface replacement: a mirror's pixel takes what it reflects, and a glossy one is as
// far off as what it reflects, RT34), written for every view; a view's `guides` and `reflection_depth` choose whether
// its denoiser reads them
@@ -89,15 +88,13 @@ struct View {
/// the split emission's history (RAEA_SOLARI_EMISSIVE=taa, emit_taa.rs)
taa: Option<super::emit_taa::History>,
fresh: bool,
/// overscan: the output is wider than the colour, and `run` copies its middle over once the emission is back in
cropped: bool,
}
#[derive(Default)]
struct Kit {
/// the guides (and the emissive out), the emissive back in, from this frame or gathered over frames (emit_taa.rs),
/// and the sampler that reads the gathered emission's history
pipeline: Option<(wgpu::ComputePipeline, wgpu::ComputePipeline, wgpu::ComputePipeline, wgpu::Sampler, wgpu::ComputePipeline, wgpu::ComputePipeline)>,
pipeline: Option<(wgpu::ComputePipeline, wgpu::ComputePipeline, wgpu::ComputePipeline, wgpu::Sampler, wgpu::ComputePipeline)>,
views: HashMap<Entity, View>,
off: bool,
}
@@ -164,7 +161,7 @@ impl View {
mask: texture(dev, size, wgpu::TextureFormat::R32Float, guide, "metalfx denoise strength"),
out: texture(dev, out_size, wgpu::TextureFormat::Rgba16Float, guide | U::RENDER_ATTACHMENT | U::COPY_SRC, "metalfx output"),
taa: taa.then(|| super::emit_taa::History::new(dev, out_size)),
fresh: true, cropped: false,
fresh: true,
})
}
}
@@ -207,28 +204,13 @@ impl View {
s.setShouldResetHistory(reset || self.fresh);
matrices(s, view.world_from_view.to_matrix().inverse(), view.clip_from_view);
s.encodeToCommandBuffer(cb);
if !self.cropped {
let blit = cb.blitCommandEncoder().ok_or("no blit encoder")?;
let o = MTLOrigin { x: 0, y: 0, z: 0 };
let size = MTLSize { width: self.out_size.x as _, height: self.out_size.y as _, depth: 1 };
blit.copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin(&out, 0, 0, o, size, &color, 0, 0, o);
blit.endEncoding();
}
}
self.fresh = false;
Ok(())
}
/// Overscan: the `full` middle of the wider output, from `at`, over the colour.
fn crop_onto(&self, cb: &ProtocolObject<dyn MTLCommandBuffer>, color: &wgpu::Texture, at: UVec2, full: UVec2) -> Result<(), &'static str> {
let (out, color) = (mtl(&self.out).ok_or("a texture isn't a Metal one")?, mtl(color).ok_or("a texture isn't a Metal one")?);
unsafe {
let blit = cb.blitCommandEncoder().ok_or("no blit encoder")?;
let from = MTLOrigin { x: at.x as _, y: at.y as _, z: 0 };
let size = MTLSize { width: full.x as _, height: full.y as _, depth: 1 };
blit.copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin(&out, 0, 0, from, size, &color, 0, 0, MTLOrigin { x: 0, y: 0, z: 0 });
let o = MTLOrigin { x: 0, y: 0, z: 0 };
let size = MTLSize { width: self.out_size.x as _, height: self.out_size.y as _, depth: 1 };
blit.copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin(&out, 0, 0, o, size, &color, 0, 0, o);
blit.endEncoding();
}
self.fresh = false;
Ok(())
}
}
@@ -258,7 +240,7 @@ fn matrices(s: &ProtocolObject<dyn MTLFXTemporalDenoisedScaler>, world_to_view:
}
}
type Viewed = (&'static ViewTarget, &'static ViewPrepassTextures, &'static ExtractedView, &'static ExtractedCamera, &'static SolariLighting, Option<&'static MainPassResolutionOverride>, Option<&'static TemporalJitter>, Has<super::upscale::Upscaled>, Option<&'static SolariGuideTextures>, Option<&'static super::SolariSettings>, Option<&'static raea_sys_viewbox::Overscan>);
type Viewed = (&'static ViewTarget, &'static ViewPrepassTextures, &'static ExtractedView, &'static ExtractedCamera, &'static SolariLighting, Option<&'static MainPassResolutionOverride>, Option<&'static TemporalJitter>, Has<super::upscale::Upscaled>, Option<&'static SolariGuideTextures>, Option<&'static super::SolariSettings>);
/// Before the forward meshes: a view at its full size, or one drawn small whose settings upscale in "two" (its corner).
/// Each view's settings go into the run's trace here, once and on a change.
@@ -268,23 +250,8 @@ fn denoise(view: ViewQuery<Viewed>, device: Res<RenderDevice>, mut kit: Local<Ki
let st = super::settings::of(item.9);
let scale = item.5.map_or(1.0, |p| p.0.x as f32 / item.0.main_texture().width() as f32);
super::settings::record(entity, &st, scale, &mut seen);
// a view drawn small is denoised and brought up in one pass, unless its upscale is "two"; one whose settings say
// `late` after the forward meshes and the sky (denoise_late)
if !st.denoise || (item.7 && st.upscale != "two") || (st.late && !item.7) {
return;
}
run(entity, item, &st, &device, &mut kit, &mut ctx, false);
}
/// After the main pass: a view at its full size whose settings say `late`, so the sky and the forward meshes, drawn with
/// the jittered camera after Solari, are gathered over frames with the rest. Drawn after the denoiser, they kept the
/// jitter: a silhouette against the sky stepped a pixel a frame on its 8-frame cycle (MALL RAT t1 frame 1699, steady's
/// jitter worst square 73%)
fn denoise_late(view: ViewQuery<Viewed>, device: Res<RenderDevice>, mut kit: Local<Kit>, mut ctx: RenderContext) {
let entity = view.entity();
let item = view.into_inner();
let st = super::settings::of(item.9);
if !st.denoise || item.7 || !st.late {
// a view drawn small is denoised and brought up in one pass, unless its upscale is "two"
if !st.denoise || (item.7 && st.upscale != "two") {
return;
}
run(entity, item, &st, &device, &mut kit, &mut ctx, false);
@@ -301,7 +268,7 @@ fn denoise_up(view: ViewQuery<Viewed>, device: Res<RenderDevice>, mut kit: Local
run(entity, item, &st, &device, &mut kit, &mut ctx, true);
}
type Item<'a> = (&'a ViewTarget, &'a ViewPrepassTextures, &'a ExtractedView, &'a ExtractedCamera, &'a SolariLighting, Option<&'a MainPassResolutionOverride>, Option<&'a TemporalJitter>, bool, Option<&'a SolariGuideTextures>, Option<&'a super::SolariSettings>, Option<&'a raea_sys_viewbox::Overscan>);
type Item<'a> = (&'a ViewTarget, &'a ViewPrepassTextures, &'a ExtractedView, &'a ExtractedCamera, &'a SolariLighting, Option<&'a MainPassResolutionOverride>, Option<&'a TemporalJitter>, bool, Option<&'a SolariGuideTextures>, Option<&'a super::SolariSettings>);
/// The guides from the G-buffer and the emissive out, at the main pass's size; MetalFX's denoiser, out to the whole
/// view when `up`; its output over the colour and the emissive back in.
@@ -309,7 +276,7 @@ fn run(entity: Entity, item: Item, st: &super::SolariSettings, device: &RenderDe
if kit.off {
return;
}
let (target, pre, ext, cam, solari, part, jitter, _, guides, _, over) = item;
let (target, pre, ext, cam, solari, part, jitter, _, guides, _) = item;
// Solari wrote its guides for every view; this one reads them unless its settings say the G-buffer's
let guides = guides.filter(|_| st.guides);
let (Some(depth), Some(motion), Some(gbuf)) = (pre.depth.as_ref(), pre.motion_vectors.as_ref(), pre.deferred.as_ref()) else { return };
@@ -319,12 +286,7 @@ fn run(entity: Entity, item: Item, st: &super::SolariSettings, device: &RenderDe
let color: &wgpu::Texture = target.main_texture();
let full = UVec2::new(color.width(), color.height());
let size = part.map_or(full, |p| p.0);
// overscan: the main pass drew the view wider, so the denoised frame is wider than the colour, and its middle is
// what the colour takes (below)
let k = if up { raea_sys_viewbox::Overscan::drawn(over) } else { 0.0 };
let wide = (full.as_vec2() * (1.0 + 2.0 * k)).round().as_uvec2();
let crop = (k > 0.0).then(|| (wide - full) / 2);
let out_size = if !up { size } else if crop.is_some() { wide } else { full };
let out_size = if up { full } else { size };
let jitter = jitter.map_or(Vec2::ZERO, |j| -j.offset * super::upscale::jitter_gain(&st.jitter, true, true));
let dev = device.wgpu_device().clone();
// with Solari's guides, the denoiser's depth is theirs: a mirror's pixel as far off as what it reflects, so when what
@@ -340,13 +302,12 @@ fn run(entity: Entity, item: Item, st: &super::SolariSettings, device: &RenderDe
}
Err(e) => {
kit.off = true;
super::upscale::NO_DENOISER.store(true, std::sync::atomic::Ordering::Relaxed);
eprintln!("raea: <SolariLighting>: no MetalFX denoiser ({e}); the lighting draws un-denoised (docs/raytracing.feature RT4)");
return;
}
}
}
let (pipeline, restore, restore_taa, hist_sampler, pipeline_psr, expand) = kit
let (pipeline, restore, restore_taa, hist_sampler, pipeline_psr) = kit
.pipeline
.get_or_insert_with(|| {
// read from a project's engine-shaders/ or the checkout when one has them (docs/nobuild.feature NB5b)
@@ -355,19 +316,18 @@ fn run(entity: Entity, item: Item, st: &super::SolariSettings, device: &RenderDe
let source = format!("{guides}{taa}");
let module = dev.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("metalfx guides"), source: wgpu::ShaderSource::Wgsl(source.into()) });
let make = |entry: &str| dev.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("metalfx guides"), layout: None, module: &module, entry_point: Some(entry), compilation_options: Default::default(), cache: None });
(make("main"), make("restore"), make("restore_taa"), super::emit_taa::sampler(&dev), make("main_psr"), make("expand"))
(make("main"), make("restore"), make("restore_taa"), super::emit_taa::sampler(&dev), make("main_psr"))
})
.clone();
let color_view = color.create_view(&Default::default());
let back = ext.world_from_view.back();
let reset = solari.reset || kit.views.get(&entity).is_none_or(|v| v.fresh);
// the jitter's cycle at this render scale, how long a twig glimpsed through it can stay away (emit_taa.wgsl)
let cycle = super::upscale::cycle(size.x as f32 / out_size.x.max(full.x) as f32, st.jitter_frames) as f32;
let words: [f32; 16] = [cam.exposure, if split { 1.0 } else { 0.0 }, if reset { 1.0 } else { 0.0 }, super::emit_taa::debug(), out_size.x as f32, out_size.y as f32, size.x as f32, size.y as f32, back.x, back.y, back.z, st.emissive_sharpness, jitter.x, jitter.y, cycle, st.knee.max(0.0) * st.preexposure / 16.0];
let cycle = super::upscale::cycle(size.x as f32 / full.x as f32, st.jitter_frames) as f32;
let words: [f32; 16] = [cam.exposure, if split { 1.0 } else { 0.0 }, if reset { 1.0 } else { 0.0 }, super::emit_taa::debug(), out_size.x as f32, out_size.y as f32, size.x as f32, size.y as f32, back.x, back.y, back.z, st.emissive_sharpness, jitter.x, jitter.y, cycle, 0.0];
let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_ne_bytes()).collect();
let params = wgpu::util::DeviceExt::create_buffer_init(&dev, &wgpu::util::BufferInitDescriptor { label: Some("metalfx params"), contents: &bytes, usage: wgpu::BufferUsages::UNIFORM });
let v = kit.views.get_mut(&entity).unwrap();
v.cropped = crop.is_some();
let views = [&v.diffuse, &v.specular, &v.normal, &v.rough].map(|t| t.create_view(&Default::default()));
let mut entries = vec![wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&*gbuf.texture.default_view) }];
for (i, tv) in views.iter().enumerate() {
@@ -408,9 +368,6 @@ fn run(entity: Entity, item: Item, st: &super::SolariSettings, device: &RenderDe
})
};
ctx.add_command_buffer(raw.finish());
// overscan: the emission goes back into the denoiser's wider output, whose middle the colour then takes
let out_view = v.out.create_view(&Default::default());
let color_view = if crop.is_some() { out_view } else { color_view };
// the emissive back in, after the denoiser's command buffer (add_command_buffer flushed the encoder before it)
if split {
let mut entries = vec![
@@ -434,31 +391,6 @@ fn run(entity: Entity, item: Item, st: &super::SolariSettings, device: &RenderDe
pass.dispatch_workgroups(out_size.x.div_ceil(8), out_size.y.div_ceil(8), 1);
}
}
// the knee undone where no `restore` ran (emissive "mask")
if !split && st.knee > 0.0 {
let entries = [
wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(&color_view) },
wgpu::BindGroupEntry { binding: 6, resource: params.as_entire_binding() },
];
let bind = dev.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("metalfx knee undone"), layout: &expand.get_bind_group_layout(0), entries: &entries });
let mut pass = ctx.command_encoder().begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("metalfx knee undone"), timestamp_writes: None });
pass.set_pipeline(&expand);
pass.set_bind_group(0, &bind, &[]);
pass.dispatch_workgroups(out_size.x.div_ceil(8), out_size.y.div_ceil(8), 1);
}
// the middle of the wider output over the colour: a raw blit as the denoiser's own (the colour has no COPY_DST for
// wgpu's), in a command buffer after the emission's (add_command_buffer flushes the encoder before it)
let mut done = done;
if let (Some(at), true) = (crop, done.is_ok()) {
let mut raw = dev.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("metalfx overscan crop") });
done = unsafe {
raw.as_hal_mut::<Metal, _, _>(|e| match e.and_then(|e| e.raw_command_buffer()) {
Some(cb) => v.crop_onto(cb, color, at, full),
None => Err("wgpu gave no Metal command buffer"),
})
};
ctx.add_command_buffer(raw.finish());
}
use std::sync::atomic::Ordering::Relaxed;
super::upscale::DENOISED.store(done.is_ok(), Relaxed);
super::upscale::DENOISING.store(done.is_ok(), Relaxed);
@@ -467,7 +399,6 @@ fn run(entity: Entity, item: Item, st: &super::SolariSettings, device: &RenderDe
}
if let Err(e) = done {
kit.off = true;
super::upscale::NO_DENOISER.store(true, Relaxed);
eprintln!("raea: <SolariLighting>: the MetalFX denoiser stopped ({e}); the lighting draws un-denoised");
}
}
+3 -30
View File
@@ -22,28 +22,12 @@
@group(0) @binding(5) var color: texture_storage_2d<rgba16float, read_write>;
// [0].x: the camera's exposure, .y: 1 to split all emission out (RAEA_SOLARI_EMISSIVE=split); [1]: the output's size
// and the input's (the corner of the colour the main pass drew); [2].xyz: the camera's back, world-space; [3].xy: the
// jitter MetalFX is told, in input pixels, .w: where the soft knee starts in the colour (0: none; SolariSettings.knee)
// jitter MetalFX is told, in input pixels
@group(0) @binding(6) var<uniform> params: array<vec4<f32>, 4>;
// the emission `main` took out of the colour, at the input's size, for `restore` to put back
@group(0) @binding(7) var emit: texture_storage_2d<rgba16float, read_write>;
// MetalFX's denoise strength mask: 1 leaves a pixel undenoised
@group(0) @binding(8) var mask: texture_storage_2d<r32float, write>;
// The soft knee (SolariSettings.knee): above W a pixel's light m (its largest channel) goes in as W (1 + ln(m / W)),
// which meets the line at W with the same slope, and its colour is scaled to match; `expand` undoes it after the
// denoiser. Logarithmic rather than Reinhard's m / (1 + m): its half floats keep a bright pixel's light to about 0.5%,
// where Reinhard's curve crowds every highlight just under its ceiling and loses them
fn compress(c: vec3<f32>) -> vec3<f32> {
let w = params[3].w;
let m = max(c.r, max(c.g, c.b));
if (w <= 0.0 || m <= w) { return c; }
return c * (w * (1.0 + log(m / w)) / m);
}
fn uncompress(c: vec3<f32>) -> vec3<f32> {
let w = params[3].w;
let m = max(c.r, max(c.g, c.b));
if (w <= 0.0 || m <= w) { return c; }
return c * (w * exp(min(m / w - 1.0, 80.0)) / m);
}
fn rgb9e5(v: u32) -> vec3<f32> {
let scale = exp2(f32(i32(extractBits(v, 27u, 5u)) - 15 - 9));
return vec3<f32>(f32(extractBits(v, 0u, 9u)), f32(extractBits(v, 9u, 9u)), f32(extractBits(v, 18u, 9u))) * scale;
@@ -100,7 +84,6 @@ fn sky(p: vec2<i32>) {
textureStore(rough, p, vec4<f32>(1.0, 0.0, 0.0, 0.0));
textureStore(emit, p, vec4<f32>(0.0));
textureStore(mask, p, vec4<f32>(1.0, 0.0, 0.0, 0.0));
textureStore(color, p, vec4<f32>(compress(c), textureLoad(color, p).a));
}
fn store(p: vec2<i32>, g: vec4<u32>, s: Surface) {
textureStore(normal, p, vec4<f32>(s.normal, 0.0));
@@ -112,7 +95,7 @@ fn store(p: vec2<i32>, g: vec4<u32>, s: Surface) {
if (params[0].y > 0.5) {
let taken = min(e, c.rgb);
textureStore(diffuse, p, vec4<f32>(s.diffuse, 1.0));
textureStore(color, p, vec4<f32>(compress(c.rgb - taken), c.a));
textureStore(color, p, vec4<f32>(c.rgb - taken, c.a));
textureStore(emit, p, vec4<f32>(taken, 0.0));
textureStore(mask, p, vec4<f32>(0.0));
return;
@@ -121,7 +104,6 @@ fn store(p: vec2<i32>, g: vec4<u32>, s: Surface) {
let share = dot(e, luma) / max(dot(c.rgb, luma), 1e-4);
textureStore(diffuse, p, vec4<f32>(min(s.diffuse + e / (vec3<f32>(1.0) + e), vec3<f32>(1.0)), 1.0));
textureStore(mask, p, vec4<f32>(smoothstep(0.3, 0.7, share), 0.0, 0.0, 0.0));
textureStore(color, p, vec4<f32>(compress(c.rgb), c.a));
}
@compute @workgroup_size(8, 8, 1)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
@@ -160,14 +142,5 @@ fn restore(@builtin(global_invocation_id) id: vec3<u32>) {
let t = q - floor(q);
let e = mix(mix(emitted(i), emitted(i + vec2<i32>(1, 0)), t.x), mix(emitted(i + vec2<i32>(0, 1)), emitted(i + vec2<i32>(1, 1)), t.x), t.y);
let c = textureLoad(color, p);
textureStore(color, p, vec4<f32>(uncompress(c.rgb) + e, c.a));
}
// the knee undone, with no emission to put back (emissive "mask"): run after the denoiser whenever `restore` isn't
@compute @workgroup_size(8, 8, 1)
fn expand(@builtin(global_invocation_id) id: vec3<u32>) {
let size = vec2<u32>(params[1].xy);
if (id.x >= size.x || id.y >= size.y) { return; }
let p = vec2<i32>(id.xy);
let c = textureLoad(color, p);
textureStore(color, p, vec4<f32>(uncompress(c.rgb), c.a));
textureStore(color, p, vec4<f32>(c.rgb + e, c.a));
}
+1 -13
View File
@@ -13,13 +13,10 @@ struct Overrides {
emissive: Option<String>,
upscale: Option<String>,
preexposure: Option<f32>,
knee: Option<f32>,
late: Option<bool>,
aa: Option<bool>,
jitter: Option<String>,
emissive_sharpness: Option<f32>,
dynamic: Option<bool>,
overscan: Option<f32>,
}
fn overrides() -> &'static Overrides {
@@ -36,13 +33,10 @@ fn overrides() -> &'static Overrides {
emissive: var("RAEA_SOLARI_EMISSIVE").filter(|v| matches!(v.as_str(), "taa" | "split" | "mask")),
upscale: var("RAEA_SOLARI_UPSCALE").filter(|v| matches!(v.as_str(), "one" | "two")),
preexposure: num("RAEA_METALFX_PREEXPOSURE"),
late: switch("RAEA_SOLARI_DENOISE_LATE"),
knee: if var("RAEA_METALFX_KNEE").as_deref() == Some("0") { Some(0.0) } else { num("RAEA_METALFX_KNEE") },
aa: switch("RAEA_SOLARI_AA"),
jitter: var("RAEA_SOLARI_JITTER"),
emissive_sharpness: num("RAEA_EMIT_TAA_SHARP"),
dynamic: switch("RAEA_SOLARI_DYNAMIC"),
overscan: var("RAEA_SOLARI_OVERSCAN").and_then(|v| v.parse::<f32>().ok()).filter(|v| (0.0..=0.25).contains(v)),
}
})
}
@@ -57,13 +51,10 @@ pub(crate) fn of(s: Option<&SolariSettings>) -> SolariSettings {
if let Some(v) = &o.emissive { s.emissive = v.clone(); }
if let Some(v) = &o.upscale { s.upscale = v.clone(); }
if let Some(v) = o.preexposure { s.preexposure = v; }
if let Some(v) = o.knee { s.knee = v; }
if let Some(v) = o.late { s.late = v; }
if let Some(v) = o.aa { s.aa = v; }
if let Some(v) = &o.jitter { s.jitter = v.clone(); }
if let Some(v) = o.emissive_sharpness { s.emissive_sharpness = v; }
if let Some(v) = o.dynamic { s.dynamic = v; }
if let Some(v) = o.overscan { s.overscan = v; }
s
}
@@ -75,12 +66,9 @@ const VARS: &[(&str, &str)] = &[
("RAEA_SOLARI_EMISSIVE", "emissive"),
("RAEA_SOLARI_UPSCALE", "upscale"),
("RAEA_METALFX_PREEXPOSURE", "preexposure"),
("RAEA_METALFX_KNEE", "knee"),
("RAEA_SOLARI_DENOISE_LATE", "late"),
("RAEA_SOLARI_AA", "aa"),
("RAEA_SOLARI_JITTER", "jitter"),
("RAEA_SOLARI_DYNAMIC", "dynamic"),
("RAEA_SOLARI_OVERSCAN", "overscan"),
("RAEA_EMIT_TAA_SHARP", "emissiveSharpness"),
("RAEA_SOLARI_SCALE", "scale"),
];
@@ -101,7 +89,7 @@ pub(crate) fn record(view: Entity, s: &SolariSettings, scale: f32, seen: &mut Ha
"view": view.to_bits(),
"denoise": s.denoise, "guides": s.guides, "reflection_depth": s.reflection_depth, "emissive": s.emissive,
"upscale": s.upscale, "preexposure": s.preexposure, "aa": s.aa, "jitter": s.jitter,
"emissive_sharpness": s.emissive_sharpness, "jitter_frames": s.jitter_frames, "dynamic": s.dynamic, "overscan": s.overscan, "scale": (f64::from(scale) * 1000.0).round() / 1000.0,
"emissive_sharpness": s.emissive_sharpness, "jitter_frames": s.jitter_frames, "dynamic": s.dynamic, "scale": (f64::from(scale) * 1000.0).round() / 1000.0,
"env": env.iter().map(|(n, v, _)| format!("{n}={v}")).collect::<Vec<_>>(),
}),
);
+11 -50
View File
@@ -41,49 +41,18 @@ static NONE: AtomicBool = AtomicBool::new(false);
/// After app.finish(): the jitter and the main pass's size in the main world, the scaler after the main pass.
pub(crate) fn add(app: &mut App) {
app.add_systems(PostUpdate, (jitter, widen.before(raea_sys_viewbox::tag_row_view).before(bevy::camera::CameraUpdateSystems)));
app.add_systems(PostUpdate, jitter);
let Some(r) = app.get_sub_app_mut(RenderApp) else { return };
r.add_systems(ExtractSchedule, extract).add_systems(Core3d, upscale.in_set(Core3dSystems::EarlyPostProcess));
}
/// The fraction of the view's size a side its main pass draws at, 1/3 to 1: RAEA_SOLARI_SCALE on a Solari camera, else
/// its RenderScale; 1 where there's no scaler.
fn scale(rs: Option<&RenderScale>, solari: bool, k: f32) -> f32 {
fn scale(rs: Option<&RenderScale>, solari: bool) -> f32 {
static FORCED: std::sync::OnceLock<Option<f32>> = std::sync::OnceLock::new();
let forced = *FORCED.get_or_init(|| std::env::var("RAEA_SOLARI_SCALE").ok().and_then(|v| v.parse::<f32>().ok()));
let s = if solari && let Some(f) = forced { f } else { rs.map_or(1.0, |r| r.scale) };
let s = if NONE.load(Ordering::Relaxed) || !s.is_finite() || s >= 0.999 { 1.0 } else { s.clamp(1.0 / 3.0, 1.0) };
// overscan: the wider main pass has to fit the view's textures
if k > 0.0 { s.min(1.0 / (1.0 + 2.0 * k)) } else { s }
}
/// The denoiser stopped (metalfx.rs): nothing crops a wider view back, so no view is drawn wider.
pub(crate) static NO_DENOISER: AtomicBool = AtomicBool::new(false);
/// A Solari camera's overscan as it applies: its settings', where the denoiser brings the view up in one pass (it does
/// the cropping); none otherwise.
fn overscan(solari: bool, st: &super::SolariSettings) -> f32 {
if !solari || !st.denoise || st.upscale == "two" || NONE.load(Ordering::Relaxed) || NO_DENOISER.load(Ordering::Relaxed) || !st.overscan.is_finite() {
return 0.0;
}
st.overscan.clamp(0.0, 0.25)
}
/// Each Solari camera's Overscan from its settings, for the view it draws (raea-sys-viewbox widens it).
#[allow(clippy::type_complexity)]
fn widen(mut cmd: Commands, cams: Query<(Entity, Has<SolariLighting>, Option<&super::SolariSettings>, Option<&raea_sys_viewbox::Overscan>), With<Camera3d>>) {
for (e, solari, st, has) in &cams {
let k = overscan(solari, &super::settings::of(st));
match (k > 0.0, has) {
(true, has) if has.map(|o| o.margin) != Some(k) => {
cmd.entity(e).insert(raea_sys_viewbox::Overscan { margin: k, drawn: 0.0 });
}
(false, Some(_)) => {
cmd.entity(e).remove::<raea_sys_viewbox::Overscan>();
}
_ => {}
}
}
if NONE.load(Ordering::Relaxed) || !s.is_finite() || s >= 0.999 { 1.0 } else { s.clamp(1.0 / 3.0, 1.0) }
}
/// The denoiser ran on the view this frame (metalfx.rs sets it; the scaler, after it, reads and clears it).
@@ -125,10 +94,10 @@ pub(crate) fn cycle(s: f32, frames: f32) -> u32 {
/// gathers frames: photo 2's frame 95 had stepped edges held still, and jittered it came 15.9 -> 15.6 off the path
/// tracer.
#[allow(clippy::type_complexity)]
fn jitter(mut cmd: Commands, frame: Res<FrameCount>, mut cams: Query<(Entity, Option<&RenderScale>, Has<SolariLighting>, Option<&mut TemporalJitter>, Has<Jittered>, Option<&super::SolariSettings>, Option<&raea_sys_viewbox::Overscan>), With<Camera3d>>) {
for (e, rs, solari, j, mine, st, over) in &mut cams {
fn jitter(mut cmd: Commands, frame: Res<FrameCount>, mut cams: Query<(Entity, Option<&RenderScale>, Has<SolariLighting>, Option<&mut TemporalJitter>, Has<Jittered>, Option<&super::SolariSettings>), With<Camera3d>>) {
for (e, rs, solari, j, mine, st) in &mut cams {
let s = scale(rs, solari);
let st = super::settings::of(st);
let s = scale(rs, solari, raea_sys_viewbox::Overscan::drawn(over));
if s < 1.0 || (solari && st.aa && st.denoise && DENOISING.load(Ordering::Relaxed)) {
let n = cycle(s, st.jitter_frames);
let i = frame.0 % n + 1;
@@ -151,24 +120,16 @@ fn jitter(mut cmd: Commands, frame: Res<FrameCount>, mut cams: Query<(Entity, Op
pub(crate) struct Upscaled;
/// Each drawn-small camera's main pass size onto its view; taken off when its scale goes back to 1.
#[allow(clippy::type_complexity)]
fn extract(mut cmd: Commands, cams: Extract<Query<(RenderEntity, &Camera, Option<&RenderScale>, Has<SolariLighting>, Option<&raea_sys_viewbox::Overscan>), With<Camera3d>>>, upscaled: Query<(), With<Upscaled>>) {
for (re, cam, rs, solari, over) in &cams {
// as wide as the camera's view was drawn (raea-sys-viewbox's tag_row_view): the main pass matches that
let k = raea_sys_viewbox::Overscan::drawn(over);
let s = scale(rs, solari, k);
fn extract(mut cmd: Commands, cams: Extract<Query<(RenderEntity, &Camera, Option<&RenderScale>, Has<SolariLighting>), With<Camera3d>>>, upscaled: Query<(), With<Upscaled>>) {
for (re, cam, rs, solari) in &cams {
let s = scale(rs, solari);
match cam.physical_viewport_size() {
Some(size) if s < 1.0 && cam.is_active => {
let part = (size.as_vec2() * s * (1.0 + 2.0 * k)).round().as_uvec2().clamp(UVec2::ONE, size);
let part = (size.as_vec2() * s).round().as_uvec2().max(UVec2::ONE);
cmd.entity(re).insert((MainPassResolutionOverride(part), Upscaled));
if k > 0.0 {
cmd.entity(re).insert(raea_sys_viewbox::Overscan { margin: k, drawn: k });
} else {
cmd.entity(re).remove::<raea_sys_viewbox::Overscan>();
}
}
_ if upscaled.contains(re) => {
cmd.entity(re).remove::<(MainPassResolutionOverride, Upscaled, raea_sys_viewbox::Overscan)>();
cmd.entity(re).remove::<(MainPassResolutionOverride, Upscaled)>();
}
_ => {}
}
-40
View File
@@ -126,9 +126,6 @@ pub fn apply_rows(world: &mut World, dir: &Path, rows: &[Tup]) -> Result<bool, S
}
}
}
if world.resource::<FrameRows>().cols.id.len() != store::rows(world).len() {
name_rows(world);
}
// a <BevyComponent> or <BevyResource> whose value a live frame changed (or a new one): set on its part
plugins::apply_live_rows(world, &reflected)?;
// a mesh spawned here with a shader over its surface: put on now that this frame's rows are in (scene3d's
@@ -172,27 +169,10 @@ pub fn remove_rows_from(world: &mut World, rows: &[(String, String)]) -> Result<
// the rows after a dropped one moved up: their places again, from the store's order
let ix: bevy::ecs::entity::EntityHashMap<usize> = store::rows(world).iter().enumerate().map(|(r, &e)| (e, r)).collect();
world.resource_mut::<FrameRows>().ix = ix;
name_rows(world);
}
if gone.is_empty() { Ok(()) } else { Err(gone.join("; ")) }
}
/// The frame's row names (`cols.kind`, `cols.id`) as the store holds its rows now. A live scene's rows move up when one
/// before them is dropped and new ones join at the end, and a <FramePass>'s or a <Compute>'s `follow` finds its row
/// by `cols.id`: left as the scene opened, a pass read another row from the first drop on and kept the uniforms it
/// opened with for the rest of a video (11-25: MALL RAT's exposure stood still, its daylight blown out).
fn name_rows(world: &mut World) {
let (mut kinds, mut ids) = (Vec::<String>::new(), Vec::<String>::new());
for &e in store::rows(world).iter() {
if let Some(k) = store::key(world, e) {
kinds.push(k.kind.clone());
ids.push(k.id.clone());
}
}
let mut fr = world.resource_mut::<FrameRows>();
(fr.cols.kind, fr.cols.id) = (kinds.into(), ids.into());
}
/// Where a plain App's 3D camera draws when its camera row arrives through apply_rows (an Engine's draws into its frame).
#[derive(Resource, Clone)]
pub struct SceneTarget {
@@ -402,23 +382,3 @@ pub(crate) fn spawn_3d(world: &mut World, e: Entity, t: &Tup, inserted: &[Tup],
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_live_rows_name_follows_the_rows_dropped_before_it() {
let row = |kind: &str, id: &str, k: f64| Tup { kind: kind.into(), id: id.into(), vals: [("k".into(), V::N(k))].into() };
let mut s = store::Store::new(&[row("mesh", "a", 0.0), row("mesh", "b", 1.0), row("frame_pass", "frame_pass0", 2.0)]);
let mut fr = FrameRows::new(store::rows(&s.world).iter().enumerate().map(|(r, &e)| (e, r)).collect());
fr.cols = s.gather();
fr.live = Some(s.tups().into_iter().map(|t| t.vals).collect());
s.world.insert_resource(fr);
remove_rows_from(&mut s.world, &[("mesh".into(), "a".into())]).unwrap();
// the pass's row is one place up, and found there by its name (a FramePass's `follow`)
let fr = s.world.resource::<FrameRows>();
let r = fr.cols.id.iter().position(|i| i == "frame_pass0").unwrap();
assert_eq!((r, fr.at(r, "k")), (1, Some(V::N(2.0))));
}
}
-115
View File
@@ -1,115 +0,0 @@
// record: playable-brick-rush
// A playable ad's shape in raea (docs/playables.feature): a hand shows the move until the first touch, the player drags
// the paddle, three misses or a cleared wall ends it on an EndCard that opens the store. One game, two compositions
// (portrait and landscape) so each network's either orientation gets its own layout. Rendered with `raea render`, no
// one touches it: the paddle follows the ball, and the same file is the video ad.
import { AbsoluteFill, Composition, registerRoot, useCurrentFrame, useGameState, useVideoConfig, type FrameInput } from "raea";
import { Sphere } from "raea/3d";
import { LinearRgba, Srgba } from "raea/color";
import { StandardMaterial } from "raea/pbr";
import { Cuboid, Mesh3d } from "raea/mesh";
import { AmbientLight, DirectionalLight } from "raea/light";
import { Transform } from "raea/transform";
import { Camera3d } from "raea/camera";
import { EndCard } from "raea/playable";
const FPS = 30;
const COLS = 6, ROWS = 4, LIVES = 3;
const W = 6, TOP = 6; // field: x in [-W/2, W/2], y from 0 (paddle) to TOP
const FOV = 0.733; // radians, vertical
const COLORS = ["#ef476f", "#f78c6b", "#06d6a0", "#118ab2"];
interface Game { px: number; bx: number; by: number; vx: number; vy: number; alive: boolean[]; broke: number[]; hit: number; missed: number; lives: number; touched: boolean; over: "" | "won" | "lost" }
const INITIAL: Game = { px: 0, bx: 0, by: 0.6, vx: 0.06, vy: 0.1, alive: Array(COLS * ROWS).fill(true), broke: Array(COLS * ROWS).fill(-99), hit: -99, missed: -99, lives: LIVES, touched: false, over: "" };
const brickPos = (i: number): [number, number] => [(i % COLS - (COLS - 1) / 2) * (W / COLS), TOP - 0.5 - Math.floor(i / COLS) * 0.5];
/** The camera's distance that fits the whole field on a screen of this aspect */
const distance = (aspect: number) => Math.max((TOP + 1.5) / 2, (W + 1) / 2 / aspect) / Math.tan(FOV / 2);
/** A pointer's x on screen, in field units at the paddle's depth */
function fieldX(input: FrameInput, width: number, height: number): number | undefined {
if (!input.pointer) return undefined;
const d = distance(width / height);
const halfH = Math.tan(FOV / 2) * d;
return ((input.pointer.x / width) * 2 - 1) * halfH * (width / height);
}
const stepFor = (width: number, height: number) => (s: Game, input: FrameInput, frame: number): Game => {
if (s.over) return s;
const touched = s.touched || !!input.pointer?.down || !!input.touches?.length;
const want = touched ? fieldX(input, width, height) ?? s.px : s.bx; // before the first touch, the paddle plays itself
const px = Math.max(-W / 2 + 0.7, Math.min(W / 2 - 0.7, s.px + Math.max(-0.35, Math.min(0.35, want - s.px))));
let { bx, by, vx, vy, hit, missed, lives } = s;
bx += vx; by += vy;
if (bx < -W / 2 + 0.12 || bx > W / 2 - 0.12) vx = -vx;
if (by > TOP) vy = -Math.abs(vy);
if (by < 0.15 && by > -0.2 && vy < 0 && Math.abs(bx - px) < 0.8) { vy = Math.abs(vy); vx += (bx - px) * 0.05; hit = frame; }
if (by < -1.2) { lives -= 1; missed = frame; bx = px; by = 0.6; vx = 0.06; vy = 0.1; }
const alive = s.alive.slice(), broke = s.broke.slice();
for (let i = 0; i < alive.length; i++) {
if (!alive[i]) continue;
const [x, y] = brickPos(i);
if (Math.abs(bx - x) < W / COLS / 2 && Math.abs(by - y) < 0.22) { alive[i] = false; broke[i] = frame; vy = -vy; break; }
}
const over = !alive.some(Boolean) ? "won" : lives <= 0 ? "lost" : "";
return { px, bx, by, vx, vy, alive, broke, hit, missed, lives, touched, over };
};
const steps = new Map<string, ReturnType<typeof stepFor>>();
const stepOf = (w: number, h: number) => steps.get(`${w}x${h}`) ?? steps.set(`${w}x${h}`, stepFor(w, h)).get(`${w}x${h}`)!;
function BrickRush() {
const { width, height } = useVideoConfig();
const g = useGameState(INITIAL, stepOf(width, height));
const now = useCurrentFrame();
const last = g.broke.reduce((m, b) => Math.max(m, b), -99);
const kick = Math.max(0, 1 - (now - last) / 8);
const shake = kick * kick * 0.08 * Math.sin(now * 2.7);
const squash = Math.max(0, 1 - (now - g.hit) / 6);
const flash = Math.max(0, 1 - (now - g.missed) / 12);
const d = distance(width / height);
const s = width / 1080; // page sizes scale with the composition
return (
<AbsoluteFill style={{ background: `rgb(${16 + 90 * flash}, 20, 34)` }}>
<Camera3d transform={Transform.fromXyz(shake, TOP / 2 + shake, d).lookingAt([0, TOP / 2, 0])} projection={{ Perspective: { fov: FOV } }} />
<AmbientLight brightness={180} />
<DirectionalLight transform={Transform.fromXyz(2, 8, 6).lookingAt([0, 0, 0])} illuminance={9600} shadow_maps_enabled />
<Mesh3d transform={Transform.fromXyz(g.px, 0, 0).withScale([1 + 0.25 * squash, 1 - 0.35 * squash, 1])} name="paddle">
<Cuboid half_size={[0.7, 0.1, 0.2]} />
<StandardMaterial base_color="#f0ebd8" perceptual_roughness={0.4} />
</Mesh3d>
<Mesh3d transform={Transform.fromXyz(g.bx, g.by, 0)} name="ball">
<Sphere radius={0.14} />
<StandardMaterial base_color="#ffd166" emissive={LinearRgba.from(Srgba.hex("#ffd166")).mul(0.6)} />
</Mesh3d>
{g.alive.map((on, i) => {
const [x, y] = brickPos(i);
const t = (now - g.broke[i]) / 10;
if (!on && t > 1) return null;
const pop = on ? 1 : 1 + 0.6 * t;
return (
<Mesh3d key={i} transform={Transform.fromXyz(x, y, on ? 0 : t * 0.8).withScale([pop, on ? 1 : 1 - t, on ? 1 : 1 - t])} name={`brick-${i}`}>
<Cuboid half_size={[(W / COLS - 0.08) / 2, 0.2, 0.2]} />
<StandardMaterial base_color={on ? COLORS[Math.floor(i / COLS)] : "#ffffff"} perceptual_roughness={0.5} />
</Mesh3d>
);
})}
<div style={{ position: "absolute", left: 40 * s, top: 36 * s, fontFamily: "Inter, system-ui, sans-serif", fontWeight: 800, fontSize: 56 * s, color: "#f0ebd8" }}>
{"♥".repeat(Math.max(0, g.lives))}
</div>
{!g.touched ? (
<div style={{ position: "absolute", left: 0, right: 0, bottom: height * 0.12, textAlign: "center", fontFamily: "Inter, system-ui, sans-serif", fontWeight: 900, fontSize: 64 * s, color: "#ffffff", opacity: 0.6 + 0.4 * Math.sin(now / 5) ** 2 }}>
{`👆 Drag to play`}
</div>
) : null}
<EndCard show={!!g.over} title={g.over === "won" ? "Wall cleared!" : "So close!"} subtitle={g.over === "won" ? "300 more levels inside" : "Can you clear the wall?"} cta={g.over === "won" ? "Keep playing" : "Try again"} />
</AbsoluteFill>
);
}
registerRoot(() => (
<>
<Composition id="brick-rush-portrait" component={BrickRush} width={1080} height={1920} fps={FPS} durationInFrames={FPS * 45} />
<Composition id="brick-rush-landscape" component={BrickRush} width={1920} height={1080} fps={FPS} durationInFrames={FPS * 45} />
</>
));
+2 -8
View File
@@ -34,8 +34,6 @@ pub fn device() -> Result<Handles, String> {
/// Intel's and AMD's PCI vendor ids, as DXGI and Vulkan report them.
const INTEL: u32 = 0x8086;
const AMD: u32 = 0x1002;
/// Qualcomm's (Adreno, on a Windows on ARM PC): DXGI reports "QCOM" as its vendor, some drivers 0x5143
const QUALCOMM: [u32; 2] = [0x4D4F_4351, 0x5143];
/// Whether the shared device runs on DX12 alone: on Windows, when WGPU_BACKEND isn't set and DX12 lists Intel's or
/// AMD's own hardware among its GPUs (`dx12`: each one's vendor and kind; WARP, Windows' software DirectX, is a Cpu),
@@ -43,12 +41,10 @@ const QUALCOMM: [u32; 2] = [0x4D4F_4351, 0x5143];
/// 0.1.3's app crashed before its window in AMD's OpenGL driver (atio6axx.dll, 0xc0000005) on a laptop with an AMD
/// 780M beside an RTX 5060, under wgpu's every-backend default and under Vulkan alike (#155); both ran with
/// WGPU_BACKEND=dx12. On that laptop DX12's high-performance pick is the NVIDIA GPU, so the rule looks at every GPU,
/// not the pick. A Snapdragon PC's Adreno too (#82): under Vulkan Vello's 2D pages came out striped and with grey boxes
/// behind fading text on an Adreno X1-85, and on DX12 they were clean. A PC with only NVIDIA's GPUs, a PC with no GPU,
/// a Mac or Linux, and a WGPU_BACKEND someone set
/// not the pick. A PC with only NVIDIA's GPUs, a PC with no GPU, a Mac or Linux, and a WGPU_BACKEND someone set
/// (Windows' check sets vulkan, for lavapipe) keep wgpu's own pick.
pub fn dx12_first(windows: bool, env: Option<wgpu::Backends>, dx12: &[(u32, wgpu::DeviceType)]) -> bool {
windows && env.is_none() && dx12.iter().any(|&(vendor, kind)| (matches!(vendor, INTEL | AMD) || QUALCOMM.contains(&vendor)) && kind != wgpu::DeviceType::Cpu)
windows && env.is_none() && dx12.iter().any(|&(vendor, kind)| matches!(vendor, INTEL | AMD) && kind != wgpu::DeviceType::Cpu)
}
/// The backends every wgpu instance of raea's asks for (the shared device's, Bevy's own when it isn't there, systems/k's
@@ -151,8 +147,6 @@ mod tests {
assert!(dx12_first(true, None, &[(AMD, igpu), (0x10de, dgpu), warp]), "#155: an AMD 780M beside an RTX 5060 (DX12 picks the NVIDIA)");
assert!(dx12_first(true, None, &[(0x10de, dgpu), (AMD, igpu)]), "the same laptop listed NVIDIA first");
assert!(dx12_first(true, None, &[(AMD, dgpu)]), "an AMD Radeon card");
assert!(dx12_first(true, None, &[(0x4D4F_4351, igpu), warp]), "#82: a Snapdragon's Adreno (DXGI's QCOM)");
assert!(dx12_first(true, None, &[(0x5143, igpu)]), "#82: an Adreno reported by its PCI id");
assert!(dx12_first(true, None, &[(INTEL, igpu), (0x10de, dgpu)]), "an Intel laptop with an NVIDIA GPU");
assert!(!dx12_first(true, Some(Backends::VULKAN), &[(INTEL, igpu)]), "WGPU_BACKEND=vulkan is kept");
assert!(!dx12_first(true, Some(Backends::DX12), &[(AMD, igpu)]), "WGPU_BACKEND set: wgpu's own read of it");
+1 -7
View File
@@ -11,11 +11,5 @@ raea-io-codec = { path = "../codec", features = ["mux"] }
raea-io-soft = { path = "../soft" }
muxide = "0.2"
# from the v1.1.0 tag: the crates.io package leaves out src/arm/asm-offsets.h, which its arm assembly includes
rav1d = { git = "https://github.com/memorysafety/rav1d", tag = "v1.1.0", default-features = false, features = ["bitdepth_8", "bitdepth_16"] }
rav1d = { git = "https://github.com/memorysafety/rav1d", tag = "v1.1.0" }
rav1e = { version = "0.8", default-features = false, features = ["threading"] }
# rav1d's assembly everywhere but Windows on ARM (#82): there its arm64 .S files are GNU syntax, which MSVC's cl.exe
# skips (the link then fails), and building them with clang-cl instead breaks metis-sys's GKlib headers. The Rust and
# C paths decode the same frames, slower.
[target.'cfg(not(all(windows, target_arch = "aarch64")))'.dependencies]
rav1d = { git = "https://github.com/memorysafety/rav1d", tag = "v1.1.0", features = ["asm", "asm_arm64_dotprod", "asm_arm64_i8mm", "asm_arm64_sve2"] }
+2 -33
View File
@@ -35,7 +35,7 @@ pub fn decode_audio_symphonia(path: &Path) -> R<Audio> {
.find(|t| t.codec_params.sample_rate.is_some())
.ok_or("no audio track")?
.clone();
let mut dec = crate::opusdec::codecs()
let mut dec = symphonia::default::get_codecs()
.make(&track.codec_params, &DecoderOptions::default())
.map_err(|e| format!("symphonia: {e}"))?;
let mut rate = track.codec_params.sample_rate.unwrap_or(0);
@@ -129,7 +129,7 @@ pub fn decode_audio_window_symphonia(path: &Path, start: f64, secs: f64) -> R<Au
.map_err(|e| format!("symphonia: {e}"))?;
let mut format = probed.format;
let track = format.tracks().iter().find(|t| t.codec_params.sample_rate.is_some()).ok_or("no audio track")?.clone();
let mut dec = crate::opusdec::codecs().make(&track.codec_params, &DecoderOptions::default()).map_err(|e| format!("symphonia: {e}"))?;
let mut dec = symphonia::default::get_codecs().make(&track.codec_params, &DecoderOptions::default()).map_err(|e| format!("symphonia: {e}"))?;
let rate = track.codec_params.sample_rate.unwrap_or(0);
if rate == 0 {
return Err(format!("{}: the sound track has no sample rate", path.display()));
@@ -356,34 +356,3 @@ mod window_tests {
}
}
}
#[cfg(test)]
mod opus_tests {
use raea_io_codec::Audio;
/// Opus packets as this backend writes them decode back here (#242: no decoder took them, so raea's own MP4s read
/// as silent off the Mac): a 440 Hz tone, mono and stereo, comes back at its length and its level.
#[test]
fn opus_written_here_reads_back() {
for channels in [1usize, 2] {
let tone: Vec<f32> = (0..48_000).map(|i| 0.5 * (i as f32 * 440.0 * std::f32::consts::TAU / 48_000.0).sin()).collect();
let a = Audio { rate: 48_000, channels: vec![tone; channels] };
let packets = super::opus_packets(&a).unwrap();
let mut dec = crate::packets::AudioPacketDecoder::new("opus", None, 48_000, channels as u32).unwrap();
let mut out = vec![Vec::new(); channels];
for (_, p) in &packets {
let (rate, planes) = dec.decode(p).unwrap();
assert_eq!(rate, 48_000);
assert_eq!(planes.len(), channels);
for (o, p) in out.iter_mut().zip(&planes) {
o.extend_from_slice(p);
}
}
let n = out[0].len();
assert!((47_000..=49_500).contains(&n), "{channels} channel(s): {n} samples back from 48000");
// past the coder's start, the tone's level (0.5 peak is 0.354 RMS)
let rms = (out[0][4800..n - 4800].iter().map(|v| v * v).sum::<f32>() / (n - 9600) as f32).sqrt();
assert!((rms - 0.354).abs() < 0.03, "{channels} channel(s): RMS {rms}");
}
}
}
-2
View File
@@ -12,8 +12,6 @@
mod audio;
#[cfg(feature = "h264")]
mod h264;
/// Opus read back (libopus) as a Symphonia decoder, and the registry every decoder here is made from
mod opusdec;
/// packet-level audio decoding (Symphonia), for coders handed packets
pub mod packets;
mod probe;
-103
View File
@@ -1,103 +0,0 @@
//! Opus read back (libopus), as a Symphonia decoder: Symphonia's MP4 reader finds an Opus track and has no decoder for
//! it, so the MP4s this backend writes itself (H.264 + Opus) came back without their sound wherever no platform reader
//! stood in front (raea #242: on Windows `raea media probe` listed no audio and `raea media share` wrote a silent copy).
//! `codecs()` is Symphonia's registry with this one added; every decoder here is made from it.
use std::sync::{Mutex, OnceLock};
use symphonia::core::audio::{AsAudioBufferRef, AudioBuffer, AudioBufferRef, Channels, Signal, SignalSpec};
use symphonia::core::codecs::{CODEC_TYPE_OPUS, CodecDescriptor, CodecParameters, CodecRegistry, Decoder, DecoderOptions, FinalizeResult};
use symphonia::core::errors::{Result, decode_error, unsupported_error};
use symphonia::core::formats::Packet;
use symphonia::core::support_codec;
/// Opus always decodes at 48 kHz, and a packet holds at most 120 ms of it
const RATE: u32 = 48_000;
const MAX_FRAMES: usize = 5760;
pub struct OpusDecoder {
params: CodecParameters,
/// (behind a lock only because a Symphonia decoder must be Sync, which libopus's state isn't: one caller at a time)
dec: Mutex<opus::Decoder>,
channels: usize,
pcm: Vec<f32>,
buf: AudioBuffer<f32>,
}
/// Symphonia's own codecs and Opus.
pub fn codecs() -> &'static CodecRegistry {
static ALL: OnceLock<CodecRegistry> = OnceLock::new();
ALL.get_or_init(|| {
let mut r = CodecRegistry::new();
symphonia::default::register_enabled_codecs(&mut r);
r.register_all::<OpusDecoder>();
r
})
}
/// How many channels an Opus track has: its identification header's count (OpusHead, as an MP4's dOps box and an Ogg
/// stream's first packet both carry it: 8 bytes of magic, a version, the count), else what the container said.
fn channel_count(p: &CodecParameters) -> usize {
let head = p.extra_data.as_deref().filter(|d| d.len() > 9 && d.starts_with(b"OpusHead")).map(|d| d[9] as usize);
let said = p.channels.map(|c| c.count()).or(p.channel_layout.map(|l| l.into_channels().count()));
head.or(said).unwrap_or(2)
}
impl Decoder for OpusDecoder {
fn try_new(params: &CodecParameters, _: &DecoderOptions) -> Result<Self> {
if params.codec != CODEC_TYPE_OPUS {
return unsupported_error("opus: not an Opus track");
}
// mono and stereo (what raea writes, and nearly every Opus file): a surround stream is several coupled streams
// under a mapping, which this isn't
let (channels, layout, how) = match channel_count(params) {
1 => (1, Channels::FRONT_LEFT, opus::Channels::Mono),
2 => (2, Channels::FRONT_LEFT | Channels::FRONT_RIGHT, opus::Channels::Stereo),
_ => return unsupported_error("opus: more than two channels"),
};
let dec = match opus::Decoder::new(RATE, how) {
Ok(d) => d,
Err(_) => return unsupported_error("opus: the decoder didn't start"),
};
let mut params = params.clone();
params.with_sample_rate(RATE).with_channels(layout);
Ok(OpusDecoder { params, dec: Mutex::new(dec), channels, pcm: vec![0.0; MAX_FRAMES * channels], buf: AudioBuffer::new(MAX_FRAMES as u64, SignalSpec::new(RATE, layout)) })
}
fn supported_codecs() -> &'static [CodecDescriptor] {
&[support_codec!(CODEC_TYPE_OPUS, "opus", "Opus")]
}
fn reset(&mut self) {
if let Ok(d) = self.dec.get_mut() {
let _ = d.reset_state();
}
}
fn codec_params(&self) -> &CodecParameters {
&self.params
}
fn decode(&mut self, packet: &Packet) -> Result<AudioBufferRef<'_>> {
self.buf.clear();
let n = match self.dec.get_mut().map(|d| d.decode_float(packet.buf(), &mut self.pcm, false)) {
Ok(Ok(n)) => n,
_ => return decode_error("opus: a packet didn't decode"),
};
self.buf.render_reserved(Some(n));
for c in 0..self.channels {
for (o, i) in self.buf.chan_mut(c).iter_mut().zip(self.pcm.iter().skip(c).step_by(self.channels)) {
*o = *i;
}
}
Ok(self.buf.as_audio_buffer_ref())
}
fn finalize(&mut self) -> FinalizeResult {
FinalizeResult::default()
}
fn last_decoded(&self) -> AudioBufferRef<'_> {
self.buf.as_audio_buffer_ref()
}
}
+3 -4
View File
@@ -1,5 +1,5 @@
//! Packet-level audio decoding (Symphonia), for coders handed compressed packets one at a time: AAC (with its
//! AudioSpecificConfig), MP3, FLAC, PCM, as Symphonia reads them, and Opus (opusdec.rs). Planar f32 out.
//! AudioSpecificConfig), MP3, FLAC, PCM, as Symphonia reads them. Planar f32 out.
use symphonia::core::audio::{AudioBufferRef, Signal};
use symphonia::core::codecs::{CodecParameters, Decoder, DecoderOptions};
@@ -19,8 +19,7 @@ fn codec_type(codec: &str) -> R<symphonia::core::codecs::CodecType> {
"mp4a" | "aac" => CODEC_TYPE_AAC,
"mp3" => CODEC_TYPE_MP3,
"flac" => CODEC_TYPE_FLAC,
"opus" => CODEC_TYPE_OPUS,
o => return Err(format!("{o}: audio decodes here as aac, mp3, flac or opus")),
o => return Err(format!("{o}: audio decodes here as aac, mp3 or flac")),
})
}
@@ -38,7 +37,7 @@ impl AudioPacketDecoder {
} {
p.with_channel_layout(layout);
}
let dec = crate::opusdec::codecs().make(&p, &DecoderOptions::default()).map_err(|e| format!("symphonia: {e}"))?;
let dec = symphonia::default::get_codecs().make(&p, &DecoderOptions::default()).map_err(|e| format!("symphonia: {e}"))?;
Ok(AudioPacketDecoder { dec, ts: 0 })
}
-1
View File
@@ -24,7 +24,6 @@ use std::time::{Instant, SystemTime, UNIX_EPOCH};
use serde_json::{Value, json};
pub mod once;
mod crash;
mod look;
mod props;
-59
View File
@@ -1,59 +0,0 @@
//! An error that repeats, said once (#239): a failing audio device calls its stream's error callback without pause.
/// A device's error said once, then only how often it came back (at its 10th, 100th, ... time, and never more than once
/// a second): a failing ALSA device calls a stream's error callback without pause, and every call printed a line: #239's
/// app.log reached 40 GB of one line in two days.
pub fn said_once<E: std::fmt::Display>(what: &'static str) -> impl FnMut(E) + Send + 'static {
let mut seen = Repeats::default();
move |e| {
let m = e.to_string();
match seen.hit(&m, std::time::Instant::now()) {
Some(1) => eprintln!("{what}: {m}"),
Some(n) => eprintln!("{what}: {m} ({n} times now)"),
None => {}
}
}
}
/// Which of an error's repeats get said: `hit` answers with the count to print, or nothing.
#[derive(Default)]
struct Repeats {
last: String,
n: u64,
next: u64,
at: Option<std::time::Instant>,
}
impl Repeats {
fn hit(&mut self, m: &str, now: std::time::Instant) -> Option<u64> {
if m != self.last || self.n == 0 {
(self.last, self.n, self.next) = (m.to_string(), 0, 1);
}
self.n += 1;
let soon = self.at.is_some_and(|t| now.duration_since(t).as_secs() < 1);
if self.n < self.next || (soon && self.n > 1) {
return None;
}
self.next = self.n.saturating_mul(10);
self.at = Some(now);
Some(self.n)
}
}
#[cfg(test)]
mod tests {
use super::Repeats;
use std::time::{Duration, Instant};
/// #239: half a billion repeats of one ALSA error were half a billion lines. Two days of them are a handful.
#[test]
fn a_repeating_error_is_a_handful_of_lines() {
let (mut r, t0) = (Repeats::default(), Instant::now());
// 5,000 a second for a minute
let said = (0..300_000u64).filter(|i| r.hit("alsa::poll() returned POLLERR", t0 + Duration::from_micros(i * 200)).is_some()).count();
assert!(said <= 8, "{said} lines for 300,000 repeats");
assert_eq!(Repeats::default().hit("x", t0), Some(1), "the first is always said");
// another error is said at once, when a second has gone by
assert_eq!(r.hit("the device went away", t0 + Duration::from_secs(120)), Some(1));
}
}
+2 -8
View File
@@ -24,13 +24,12 @@ pub fn bundle_module(ts: &Path, out: &Path, body: &str) -> R<()> {
/// A path as an entry's import specifier. On Windows a canonical path is a verbatim one (\\?\C:\...), which Rolldown
/// can't resolve as an import (`raea run` on windows-latest, PT20); dunce drops the prefix where the plain path means the
/// same file, and changes nothing elsewhere.
pub fn spec(p: &Path) -> String {
fn spec(p: &Path) -> String {
dunce::simplified(p).display().to_string()
}
/// `entry` (TypeScript source) bundled into `out` by raea-bundle's library (engine/bundle/src/script.rs's resolution); `extra`
/// are bundle.ts's flags (--define K=V, --alias SPEC=PATH, --node-stub a,b), and --minify 1 and --inline 1 (a page that
/// carries its files: engine/bundle inline.rs).
/// are bundle.ts's flags (--define K=V, --alias SPEC=PATH, --node-stub a,b).
pub fn bundle_entry(entry: &str, out: &Path, extra: &[&str]) -> R<()> {
let out = &std::path::absolute(out).map_err(|e| format!("{}: {e}", out.display()))?;
let work = std::env::temp_dir().join(format!("raea-cli-e{}-{:?}", std::process::id(), std::thread::current().id()));
@@ -42,7 +41,6 @@ pub fn bundle_entry(entry: &str, out: &Path, extra: &[&str]) -> R<()> {
// in process by raea-bundle's library: the engine's resolution (engine/bundle/src/script.rs) and the flags
{
let (mut defines, mut aliases, mut stubs) = (serde_json::Map::new(), serde_json::Map::new(), Vec::new());
let (mut minify, mut inline) = (false, false);
let mut it = extra.iter();
while let Some(flag) = it.next() {
let Some(v) = it.next() else { break };
@@ -58,8 +56,6 @@ pub fn bundle_entry(entry: &str, out: &Path, extra: &[&str]) -> R<()> {
}
}
"--node-stub" => stubs.extend(v.split(',').filter(|s| !s.is_empty()).map(|s| Value::from(s))),
"--minify" => minify = *v != "0",
"--inline" => inline = *v != "0",
_ => {}
}
}
@@ -68,8 +64,6 @@ pub fn bundle_entry(entry: &str, out: &Path, extra: &[&str]) -> R<()> {
"script": {"js": js, "motion": root.join("sdk/raea/src"), "shell": root.join("sdk/shell/src/index.ts"),
"aliases": aliases, "stubs": stubs},
"defines": defines,
"minify": minify,
"inline": inline,
});
let r = inproc::bundle(&work.join("entry.ts"), opts);
let _ = std::fs::remove_dir_all(&work);
+1 -3
View File
@@ -35,9 +35,7 @@ pub fn drop_tsconfigs(dir: &Path, depth: usize) {
}
}
/// Files an edit imports as their path, as engine/bundle's script.rs MEDIA: media, models, and fonts (an @font-face's
/// url(), which a playable carries as a data URL)
pub const MEDIA_EXTS: &[&str] = &["mp4", "mov", "m4v", "mp3", "wav", "m4a", "png", "jpg", "jpeg", "webp", "gif", "glb", "gltf", "ttf", "otf", "woff", "woff2"];
pub const MEDIA_EXTS: [&str; 12] = ["mp4", "mov", "m4v", "mp3", "wav", "m4a", "png", "jpg", "webp", "gif", "glb", "gltf"];
/// The edit's source with its imports pointed at the bundle's copy of the SDK (its package name, a subpath such as /3d,
/// or a relative path into raea/motion/src), and media imported as modules turned into their paths (spec: "Media
Loaded 100 of 418 files, more files were not shown because too many files have changed in this diff. Show more