mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-01 06:53:19 -10:00
Compare commits
68
Commits
v0.1.10
...
render-memory
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
609a22c9ec | ||
|
|
4c25a4263d | ||
|
|
2835c1478a | ||
|
|
ac9e2f9ba6 | ||
|
|
3cd075ae08 | ||
|
|
0909761d60 | ||
|
|
b589826e7c | ||
|
|
64c1e06ea9 | ||
|
|
e5f4743dee | ||
|
|
4aff22e31a | ||
|
|
c863adef82 | ||
|
|
8627ba7ab4 | ||
|
|
456fd1e153 | ||
|
|
3afc53d45b | ||
|
|
7d79a24f33 | ||
|
|
6af8bfa5bb | ||
|
|
4b2225163e | ||
|
|
57373a9901 | ||
|
|
9ce8f53466 | ||
|
|
28af820668 | ||
|
|
ea5640de8f | ||
|
|
3ac738884c | ||
|
|
096f87d153 | ||
|
|
845f7438d5 | ||
|
|
6f96c78a8b | ||
|
|
e70d9c79c1 | ||
|
|
f4db12c1d0 | ||
|
|
cd159fe0be | ||
|
|
316b612d70 | ||
|
|
aa40a2fa86 | ||
|
|
48705982b6 | ||
|
|
7580433cd2 | ||
|
|
28f3fd814b | ||
|
|
1905dc723c | ||
|
|
c41dd64516 | ||
|
|
1fc3a07655 | ||
|
|
986bd33463 | ||
|
|
c41ec580a9 | ||
|
|
7e25dcc56e | ||
|
|
561e7a569c | ||
|
|
0649788f7f | ||
|
|
1a77da4980 | ||
|
|
1a913e6b06 | ||
|
|
7db0e7e149 | ||
|
|
ab63120653 | ||
|
|
8938819947 | ||
|
|
79cda1dc8c | ||
|
|
f0a266718e | ||
|
|
c8af179033 | ||
|
|
a0f6a95fe7 | ||
|
|
afaeaa0a7a | ||
|
|
65f2a6ae1e | ||
|
|
00deff035c | ||
|
|
7611a96e34 | ||
|
|
6fb27ef9e8 | ||
|
|
0c0de9b3d6 | ||
|
|
84f6c59dd0 | ||
|
|
96adb3ecfb | ||
|
|
4e12541984 | ||
|
|
4cc8f58e0a | ||
|
|
1873676251 | ||
|
|
374426411e | ||
|
|
e435bff43e | ||
|
|
4b2b39edd3 | ||
|
|
063ae93f30 | ||
|
|
2a63d75e1b | ||
|
|
2a005e0e30 | ||
|
|
04098af5af |
No files matched your search
@@ -0,0 +1,175 @@
|
||||
# raea built natively for Windows on ARM (#82: a Snapdragon X runs the x64 build under emulation, and asked for its
|
||||
# own). GitHub's windows-11-arm runner builds what release.yml's windows job builds, for aarch64-pc-windows-msvc, runs
|
||||
# `raea --version`, packs and checks raea-VERSION-windows-arm64.zip with tools/release.sh (RAEA_WIN_ARCH=arm64)
|
||||
# without drawing (RAEA_CHECK_NO_GPU=1: WARP segfaults in Bevy's compute shaders here as on x64, and Mesa's lavapipe has
|
||||
# no ARM64 build; a Snapdragon PC is what draws, #82), and on a v* tag attaches it to that
|
||||
# release. It runs beside release.yml, not in it, so a release never waits on or fails with the ARM64 build; a
|
||||
# promoted release (release-go.sh) builds it again from the tag. install.ps1 takes it on an ARM64 PC when it's there.
|
||||
name: windows-arm
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
ref:
|
||||
description: "commit, branch or tag to build"
|
||||
required: false
|
||||
version:
|
||||
description: "the version the zip is named for (raea-VERSION-windows-arm64.zip)"
|
||||
required: false
|
||||
push:
|
||||
branches: [windows-arm64]
|
||||
tags: ["v*"]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: windows-11-arm
|
||||
timeout-minutes: 350
|
||||
env:
|
||||
# the release builds' compile cache (tools/release/compile-cache.sh), under this OS and architecture's own prefix
|
||||
RELEASE_CACHE_ENDPOINT: ${{ secrets.RELEASE_CACHE_ENDPOINT }}
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.RELEASE_CACHE_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.RELEASE_CACHE_SECRET }}
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ inputs.ref || github.sha }}
|
||||
submodules: true
|
||||
lfs: false
|
||||
- name: Toolchain (rust-toolchain.toml's pin)
|
||||
run: |
|
||||
if ! command -v rustup >/dev/null; then
|
||||
curl -fsSL --retry 3 -o "$RUNNER_TEMP/rustup-init.exe" https://static.rust-lang.org/rustup/dist/aarch64-pc-windows-msvc/rustup-init.exe
|
||||
"$RUNNER_TEMP/rustup-init.exe" -y --default-toolchain none --profile minimal
|
||||
echo "$USERPROFILE/.cargo/bin" >> "$GITHUB_PATH"
|
||||
export PATH="$USERPROFILE/.cargo/bin:$PATH"
|
||||
fi
|
||||
rustup show active-toolchain || rustup toolchain install
|
||||
rustc -vV
|
||||
# ring builds its aarch64 assembly with clang (and only clang) on Windows
|
||||
- name: clang (ring's assembly)
|
||||
run: |
|
||||
if ! command -v clang >/dev/null; then
|
||||
for d in "/c/Program Files/LLVM/bin" "/c/Program Files/Microsoft Visual Studio"/*/*/VC/Tools/Llvm/ARM64/bin; do
|
||||
[ -x "$d/clang.exe" ] && { echo "$d" >> "$GITHUB_PATH"; export PATH="$d:$PATH"; break; }
|
||||
done
|
||||
fi
|
||||
command -v clang >/dev/null || { winget install -e --id LLVM.LLVM --accept-source-agreements --accept-package-agreements --silent; echo "/c/Program Files/LLVM/bin" >> "$GITHUB_PATH"; export PATH="/c/Program Files/LLVM/bin:$PATH"; }
|
||||
clang --version
|
||||
- name: jq that writes LF
|
||||
run: |
|
||||
mkdir -p "$RUNNER_TEMP/jq"
|
||||
printf '#!/bin/bash\nexec "%s" -b "$@"\n' "$(command -v jq)" > "$RUNNER_TEMP/jq/jq"
|
||||
chmod +x "$RUNNER_TEMP/jq/jq"
|
||||
echo "$RUNNER_TEMP/jq" >> "$GITHUB_PATH"
|
||||
- uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.4.2
|
||||
- name: The runtime's packages
|
||||
run: for d in sdk/react/js sdk/react/tw; do (cd "$d" && bun install --frozen-lockfile); done
|
||||
# (an sccache the action can't fetch for ARM64 Windows leaves the build uncached, as compile-cache.sh does)
|
||||
- name: Compile cache (sccache, as release.yml's)
|
||||
if: env.AWS_ACCESS_KEY_ID != ''
|
||||
continue-on-error: true
|
||||
uses: mozilla-actions/[email protected]
|
||||
- name: Use the compile cache
|
||||
if: env.AWS_ACCESS_KEY_ID != ''
|
||||
run: bash tools/release/compile-cache.sh
|
||||
- name: Build
|
||||
run: |
|
||||
feat=$(bash tools/bevy-plugins.sh features sdk/raea/bench/bevy-plugins)
|
||||
t() { s=$SECONDS; "$@"; echo "::notice::Windows ARM64 $(( (SECONDS - s) / 60 )) min: ${*:7}"; }
|
||||
t cargo build --profile dist --locked -p raea-cli --bin raea --no-default-features --features "$feat"
|
||||
t cargo build --profile dist --locked -p raea-rune-host
|
||||
t cargo build --profile dist --locked -p raea-page-host --features window
|
||||
t cargo build --profile dist --locked -p raea-perceive
|
||||
- name: What raea.exe is and imports
|
||||
run: |
|
||||
file target/dist/raea.exe || true
|
||||
dumpbin=$(ls "/c/Program Files/Microsoft Visual Studio"/*/*/VC/Tools/MSVC/*/bin/Hostarm64/arm64/dumpbin.exe 2>/dev/null | head -1)
|
||||
[ -n "$dumpbin" ] && "$dumpbin" -nologo -headers -dependents target/dist/raea.exe | grep -iE 'machine|\.dll$' | sed 's/^ *//' | tee -a "$GITHUB_STEP_SUMMARY" || true
|
||||
target/dist/raea.exe --version | tee -a "$GITHUB_STEP_SUMMARY"
|
||||
- name: Models (pinned by URL and sha256 in tools/release/models.tsv)
|
||||
run: |
|
||||
while IFS=$'\t' read -r path url sha; do
|
||||
case $path in ''|'#'*) continue ;; esac
|
||||
mkdir -p "$HOME/.local/share/raea-models/$(dirname "$path")"
|
||||
curl -fsSL "$url" -o "$HOME/.local/share/raea-models/$path"
|
||||
echo "$sha $HOME/.local/share/raea-models/$path" | sha256sum -c -
|
||||
done < <(tr -d '\r' < tools/release/models.tsv)
|
||||
# bin\ as release.yml's windows job fills it, with the ARM64 runtime, uv and DXC (RAEA_WIN_ARCH=arm64), then the
|
||||
# zip packed and checked by tools/release.sh as raea-VERSION-windows-arm64.zip. The skills gate is this commit's
|
||||
# (public raea has no feed app; cli.md is still checked against this build's help); nothing is drawn
|
||||
- name: Pack and check (tools/release.sh)
|
||||
env:
|
||||
RAEA_WIN_ARCH: arm64
|
||||
RAEA_CHECK_DIR: ${{ runner.temp }}/release-check
|
||||
RAEA_CHECK_NO_GPU: "1"
|
||||
run: |
|
||||
bash tools/release/onnxruntime.sh target/dist
|
||||
bash tools/release/win-bundle.sh target/dist
|
||||
v="${{ inputs.version }}"
|
||||
case $GITHUB_REF in
|
||||
refs/tags/v*)
|
||||
v=${v:-${GITHUB_REF_NAME#v}}
|
||||
# where the skills gate passed, as release.yml reads it (the tag's skills-passed line)
|
||||
eval "$(GITHUB_ENV= bash tools/release/skills-passed.sh "$GITHUB_REF_NAME" | grep '^RAEA_SKILLS_PASSED=')" ;;
|
||||
*) RAEA_SKILLS_PASSED=$(git rev-parse HEAD) ;;
|
||||
esac
|
||||
export RAEA_SKILLS_PASSED
|
||||
bash tools/release.sh "${v:-0.0.0-arm64}" target/dist HEAD
|
||||
# on a v* tag, beside release.yml's archives (the release made here if release.yml hasn't yet)
|
||||
- name: Attach to the release
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
pre=; case $GITHUB_REF_NAME in *-*) pre=--prerelease ;; esac
|
||||
gh release view "$GITHUB_REF_NAME" -R "$GITHUB_REPOSITORY" >/dev/null 2>&1 ||
|
||||
gh release create "$GITHUB_REF_NAME" -R "$GITHUB_REPOSITORY" $pre --title "raea ${GITHUB_REF_NAME#v}" --notes "Built by .github/workflows/release.yml; notes follow." ||
|
||||
gh release view "$GITHUB_REF_NAME" -R "$GITHUB_REPOSITORY" >/dev/null
|
||||
gh release upload "$GITHUB_REF_NAME" -R "$GITHUB_REPOSITORY" dist/raea-*-windows-arm64.zip dist/raea-*-windows-arm64.zip.sha256 --clobber
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: windows-arm64-zip
|
||||
path: dist/raea-*-windows-arm64.zip*
|
||||
retention-days: 7
|
||||
compression-level: 0
|
||||
if-no-files-found: ignore
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: windows-arm64-bins
|
||||
path: |
|
||||
target/dist/raea.exe
|
||||
target/dist/raea_bundle.dll
|
||||
target/dist/raea-rune-host.exe
|
||||
target/dist/raea-page-host.exe
|
||||
target/dist/raea-perceive.exe
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
|
||||
# vendor/metis-sys's header change reaches release.yml's x64 build too (windows-latest's Visual Studio): metis-sys
|
||||
# alone, in a scratch crate, compiled there
|
||||
metis-x64:
|
||||
runs-on: windows-latest
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ inputs.ref || github.sha }}
|
||||
sparse-checkout: vendor/metis-sys
|
||||
- name: metis-sys on x64 MSVC
|
||||
run: |
|
||||
c="$RUNNER_TEMP/metis-x64"; mkdir -p "$c/src" && : > "$c/src/lib.rs"
|
||||
printf '[package]\nname = "metis-x64"\nversion = "0.0.0"\nedition = "2021"\n[dependencies]\nmetis-sys = { path = "%s" }\n[workspace]\n' "$(cygpath -m "$GITHUB_WORKSPACE/vendor/metis-sys")" > "$c/Cargo.toml"
|
||||
cl 2>&1 | head -1 || true
|
||||
cd "$c" && cargo build
|
||||
Generated
+150
-13
@@ -8490,6 +8490,15 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "intel_tex_2"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7980d359170e7da4bc2421aa74c49d338a3153313e006d732a3430f1af375a60"
|
||||
dependencies = [
|
||||
"ispc_rt",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "interpolate_name"
|
||||
version = "0.2.4"
|
||||
@@ -8573,6 +8582,16 @@ version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
|
||||
|
||||
[[package]]
|
||||
name = "ispc_rt"
|
||||
version = "2.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a396f76fd253fab9945bb4c6080f515d0c4036bc30219462d199b58886fd37b4"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"num_cpus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.10.5"
|
||||
@@ -10263,8 +10282,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "metis-sys"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "769ee6be814b21c52afcc631f07051f578487d642f3e89a45f2a086fd94fffa9"
|
||||
dependencies = [
|
||||
"cc",
|
||||
]
|
||||
@@ -13897,6 +13914,7 @@ dependencies = [
|
||||
"raea-core-review",
|
||||
"raea-io-home",
|
||||
"raea-runtime-cut-plan",
|
||||
"raea-runtime-goal-plan",
|
||||
"raea-runtime-lod-plan",
|
||||
"resvg 0.48.1",
|
||||
"serde_json",
|
||||
@@ -13920,6 +13938,7 @@ dependencies = [
|
||||
name = "raea-app-motion"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"glam 0.33.12",
|
||||
"raea-io-home",
|
||||
"raea-runtime-bundle",
|
||||
"raea-sys-kimodo",
|
||||
@@ -13957,6 +13976,18 @@ dependencies = [
|
||||
"winit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-playable"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"raea-io-home",
|
||||
"raea-runtime-bundle",
|
||||
"regex",
|
||||
"serde_json",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-registry"
|
||||
version = "0.1.0"
|
||||
@@ -14241,6 +14272,7 @@ name = "raea-bundle"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.22.1",
|
||||
"dunce",
|
||||
"lightningcss",
|
||||
"oxc",
|
||||
@@ -14293,6 +14325,7 @@ dependencies = [
|
||||
"raea-app-media",
|
||||
"raea-app-notes",
|
||||
"raea-app-play",
|
||||
"raea-app-playable",
|
||||
"raea-app-scene",
|
||||
"raea-app-solid",
|
||||
"raea-app-sound",
|
||||
@@ -14456,6 +14489,7 @@ version = "0.1.0"
|
||||
name = "raea-core-shape"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"manifold-rust",
|
||||
"raea-core-fonts",
|
||||
"raea-core-grow",
|
||||
@@ -14474,6 +14508,15 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-core-tables"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-core-wire"
|
||||
version = "0.1.0"
|
||||
@@ -15015,29 +15058,62 @@ dependencies = [
|
||||
"raea-gpu-device",
|
||||
"raea-io-media",
|
||||
"raea-io-trace",
|
||||
"raea-render-plugins",
|
||||
"raea-render-raytrace",
|
||||
"raea-runtime-gpuframe",
|
||||
"raea-runtime-plugins",
|
||||
"raea-runtime-scene3d",
|
||||
"raea-runtime-view",
|
||||
"raea-sys-compose",
|
||||
"raea-sys-compute",
|
||||
"raea-sys-engine-shaders",
|
||||
"raea-sys-environment",
|
||||
"raea-sys-fog",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-grass",
|
||||
"raea-sys-grid",
|
||||
"raea-sys-hold",
|
||||
"raea-sys-look",
|
||||
"raea-sys-matchmove",
|
||||
"raea-sys-material",
|
||||
"raea-sys-memtally",
|
||||
"raea-sys-meshseq",
|
||||
"raea-sys-page",
|
||||
"raea-sys-post",
|
||||
"raea-sys-procmat",
|
||||
"raea-sys-screen",
|
||||
"raea-sys-shader",
|
||||
"raea-sys-splat",
|
||||
"raea-sys-sprite",
|
||||
"raea-sys-text3d",
|
||||
"raea-sys-three-shader",
|
||||
"raea-sys-toon",
|
||||
"raea-sys-viewbox",
|
||||
"serde_json",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-render-plugins"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-runtime-plugins",
|
||||
"raea-runtime-scene3d",
|
||||
"raea-sys-compose",
|
||||
"raea-sys-compute",
|
||||
"raea-sys-environment",
|
||||
"raea-sys-fog",
|
||||
"raea-sys-fog-half",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-framepass",
|
||||
"raea-sys-gi",
|
||||
"raea-sys-grass",
|
||||
"raea-sys-grid",
|
||||
"raea-sys-hold",
|
||||
"raea-sys-lod",
|
||||
"raea-sys-look",
|
||||
"raea-sys-matchmove",
|
||||
"raea-sys-material",
|
||||
"raea-sys-meshseq",
|
||||
"raea-sys-page",
|
||||
"raea-sys-parity",
|
||||
"raea-sys-phase",
|
||||
"raea-sys-post",
|
||||
@@ -15051,10 +15127,8 @@ dependencies = [
|
||||
"raea-sys-sprite",
|
||||
"raea-sys-text3d",
|
||||
"raea-sys-three-shader",
|
||||
"raea-sys-viewbox",
|
||||
"raea-sys-toon",
|
||||
"raea-sys-volume",
|
||||
"serde_json",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -15256,7 +15330,6 @@ name = "raea-runtime-calls"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bevy",
|
||||
"image",
|
||||
"manifold-rust",
|
||||
"parley",
|
||||
@@ -15267,6 +15340,7 @@ dependencies = [
|
||||
"raea-io-net",
|
||||
"raea-io-trace",
|
||||
"raea-native",
|
||||
"raea-runtime-ecs",
|
||||
"raea-runtime-plugins",
|
||||
"raea-runtime-wear",
|
||||
"raea-sys-fonts",
|
||||
@@ -15341,6 +15415,14 @@ dependencies = [
|
||||
"vello",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-ecs"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-edit"
|
||||
version = "0.1.0"
|
||||
@@ -15427,6 +15509,14 @@ 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"
|
||||
@@ -15493,6 +15583,17 @@ dependencies = [
|
||||
"rquickjs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-kinds"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-core-scene",
|
||||
"raea-runtime-look",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-live"
|
||||
version = "0.1.0"
|
||||
@@ -15616,6 +15717,7 @@ dependencies = [
|
||||
"raea-core-alloc",
|
||||
"raea-core-animate",
|
||||
"raea-core-scene",
|
||||
"raea-core-shape",
|
||||
"raea-core-wire",
|
||||
"raea-io-assets",
|
||||
"raea-io-media",
|
||||
@@ -15640,6 +15742,7 @@ dependencies = [
|
||||
"raea-sys-light-meter",
|
||||
"raea-sys-page",
|
||||
"serde_json",
|
||||
"xxhash-rust",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -15650,6 +15753,7 @@ dependencies = [
|
||||
"raea-core-program",
|
||||
"raea-core-review",
|
||||
"raea-core-scene",
|
||||
"raea-runtime-kinds",
|
||||
"raea-runtime-look",
|
||||
"raea-runtime-scene2d",
|
||||
"raea-sys-frame",
|
||||
@@ -15688,6 +15792,7 @@ dependencies = [
|
||||
"raea-sys-sampler",
|
||||
"raea-sys-shader",
|
||||
"raea-sys-share",
|
||||
"raea-sys-toon",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
@@ -16033,7 +16138,9 @@ dependencies = [
|
||||
"anyrender",
|
||||
"anyrender_vello",
|
||||
"blitz-paint",
|
||||
"png 0.18.1",
|
||||
"rustc-hash 2.1.3",
|
||||
"skrifa 0.44.0",
|
||||
"vello",
|
||||
"wgpu",
|
||||
]
|
||||
@@ -16162,6 +16269,7 @@ dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-core-scene",
|
||||
"raea-core-tables",
|
||||
"raea-io-media",
|
||||
"raea-sys-layers",
|
||||
"raea-sys-shots",
|
||||
@@ -16383,9 +16491,11 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bevy",
|
||||
"blake3",
|
||||
"image",
|
||||
"intel_tex_2",
|
||||
"raea-core-program",
|
||||
"raea-core-shape",
|
||||
"raea-io-home",
|
||||
"raea-io-net",
|
||||
"raea-io-trace",
|
||||
"raea-sys-frame",
|
||||
@@ -16399,6 +16509,13 @@ dependencies = [
|
||||
name = "raea-sys-measure"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-memtally"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-mesh"
|
||||
version = "0.1.0"
|
||||
@@ -16429,11 +16546,22 @@ dependencies = [
|
||||
"raea-io-home",
|
||||
"raea-io-media",
|
||||
"raea-io-trace",
|
||||
"raea-sys-mix-device",
|
||||
"raea-sys-mix-level",
|
||||
"raea-sys-tone",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-mix-device"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"audioadapter-buffers",
|
||||
"cpal 0.15.3",
|
||||
"firewheel",
|
||||
"raea-io-trace",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-mix-level"
|
||||
version = "0.1.0"
|
||||
@@ -16746,6 +16874,17 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-toon"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-core-shape",
|
||||
"raea-sys-frame",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-touch"
|
||||
version = "0.1.0"
|
||||
@@ -20409,8 +20548,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "taffy"
|
||||
version = "0.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3c8480887e8803986d96a7173729565520d4bbb721ad6b7ad6941a22897207aa"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"slotmap",
|
||||
|
||||
+17
@@ -12,6 +12,7 @@ members = [
|
||||
"core/ease",
|
||||
"core/fonts",
|
||||
"core/program",
|
||||
"core/tables",
|
||||
"core/scene",
|
||||
"core/shape",
|
||||
"core/meshcheck",
|
||||
@@ -30,6 +31,7 @@ members = [
|
||||
"systems/phase",
|
||||
"systems/shader/wgsl",
|
||||
"systems/sampler",
|
||||
"systems/memtally",
|
||||
"systems/parity",
|
||||
"systems/shader",
|
||||
"systems/three-shader",
|
||||
@@ -86,6 +88,7 @@ members = [
|
||||
"systems/tone",
|
||||
"systems/mix",
|
||||
"systems/mix/level",
|
||||
"systems/mix/device",
|
||||
"systems/ml",
|
||||
"systems/mlx",
|
||||
"systems/kimodo",
|
||||
@@ -148,6 +151,7 @@ members = [
|
||||
"systems/look",
|
||||
"systems/compose",
|
||||
"systems/material",
|
||||
"systems/toon",
|
||||
"systems/mesh",
|
||||
"systems/post",
|
||||
"systems/fog",
|
||||
@@ -169,6 +173,7 @@ members = [
|
||||
"tools/perceive",
|
||||
"engine/render",
|
||||
"engine/render/raytrace",
|
||||
"engine/render/plugins",
|
||||
"engine/render/denoise/bench",
|
||||
"engine/seedling",
|
||||
"engine/web",
|
||||
@@ -188,6 +193,7 @@ members = [
|
||||
"runtime/bundle/lib",
|
||||
"engine/shape-web",
|
||||
"runtime/calls",
|
||||
"runtime/ecs",
|
||||
"runtime/shots",
|
||||
"runtime/wear",
|
||||
"runtime/canvas",
|
||||
@@ -195,12 +201,14 @@ members = [
|
||||
"runtime/endchecks",
|
||||
"runtime/lod-plan",
|
||||
"runtime/cut-plan",
|
||||
"runtime/goal-plan",
|
||||
"runtime/live",
|
||||
"runtime/page",
|
||||
"runtime/appscreen",
|
||||
"runtime/sound",
|
||||
"runtime/look",
|
||||
"runtime/scene",
|
||||
"runtime/kinds",
|
||||
"runtime/scene2d",
|
||||
"runtime/shared",
|
||||
"apps/ask",
|
||||
@@ -237,6 +245,7 @@ members = [
|
||||
"apps/capcut",
|
||||
"apps/layers",
|
||||
"apps/play",
|
||||
"apps/playable",
|
||||
"tools/sdk-props",
|
||||
"tools/hands-audit",
|
||||
]
|
||||
@@ -345,6 +354,10 @@ split-debuginfo = "packed"
|
||||
[patch.crates-io]
|
||||
# the MP4 muxer, vendored
|
||||
muxide = { path = "vendor/muxide" }
|
||||
# metis-sys 0.3.2 (bevy_pbr's meshlets) with GKlib's own stdint.h and inttypes.h stand-ins used only before Visual
|
||||
# Studio 2013: Visual Studio 18's stdint.h types int_fast16_t differently, and every C file failed (raea#82; the change
|
||||
# is marked "raea:" in vendor/GKlib/gk_arch.h). Its test graphs, manual and programs are left out
|
||||
metis-sys = { path = "vendor/metis-sys" }
|
||||
# usvg 0.48.1 spacing a chunk's last letter as Chrome does (changes marked "raea:", docs/layout-reads.feature LR10)
|
||||
usvg = { path = "vendor/usvg" }
|
||||
# bevy_seedling 0.8.0 without its cpal 0.18 paths, ported to Bevy 0.20 (changes marked "raea:")
|
||||
@@ -401,6 +414,10 @@ vello_encoding = { path = "vendor/vello_encoding" }
|
||||
# (changes marked "raea:"): raea-page blends a bevy_ui page as Bevy does (bevy_ui on Blitz). No upstream
|
||||
# equivalent yet (linebender/vello blends the encoded values).
|
||||
vello_shaders = { path = "vendor/vello_shaders" }
|
||||
# taffy 0.15.0 (Blitz's, Bevy UI's, rune-taffy's) with a flex line whose items overflow its container by less than
|
||||
# Chrome's layout unit, 1/64 px, kept on one line: f32 rounding wrapped items that add up to the container's width
|
||||
# (changes marked "raea:", raea #252). Back to upstream once Taffy breaks flex lines with a tolerance.
|
||||
taffy = { path = "vendor/taffy" }
|
||||
# Firewheel 0.12 on Bevy 0.20: bevy_reflect 0.20 and a glam-33 feature (BillyDM/Firewheel#144; changes marked "raea:")
|
||||
firewheel = { path = "vendor/firewheel" }
|
||||
firewheel-core = { path = "vendor/firewheel-core" }
|
||||
|
||||
@@ -32,10 +32,10 @@
|
||||
|
||||
---
|
||||
|
||||
> **0.1.6** (17 November 2026) is the latest release: the engine and the desktop app on macOS (Apple Silicon), Linux
|
||||
> (x86_64) and, newest and least tested, Windows 10 and 11 (x86_64). raea is young and moves fast, with a release most
|
||||
> days since 0.1.1 on 11 November: expect rough edges, and tell us what you hit in an
|
||||
> [issue](https://github.com/shinyobjectz/raea/issues), or from your agent with `raea bug`.
|
||||
> raea releases experimentally and often, so the newest release is always on
|
||||
> [Releases](https://github.com/shinyobjectz/raea/releases). The app is unstable for now, especially on Linux and
|
||||
> Windows: expect rough edges, and tell us what you hit in an [issue](https://github.com/shinyobjectz/raea/issues), or
|
||||
> from your agent with `raea bug`.
|
||||
|
||||
## The app
|
||||
|
||||
|
||||
@@ -55,6 +55,11 @@ fn said(l: &Value) -> String {
|
||||
"result" => format!("a result{on}: {text}"),
|
||||
"correction" => format!("a correction{on}: {text}"),
|
||||
"sign" => format!("a sign-off{on} (ask {})", l["ask"]),
|
||||
// a show only to be looked at (raea show --fyi), looked at: Got it, with a word or none
|
||||
"seen" => {
|
||||
let word = text.strip_prefix("Seen").unwrap_or(&text).trim_start_matches(':').trim();
|
||||
if word.is_empty() { format!("seen{on}") } else { format!("seen{on}: {word}") }
|
||||
}
|
||||
k => format!("{}{on}: {text}", if k.is_empty() { "something" } else { k }),
|
||||
};
|
||||
format!("- {what}")
|
||||
@@ -68,6 +73,17 @@ pub fn told(agent: &str, v: &Value) -> Option<String> {
|
||||
return None;
|
||||
}
|
||||
let list = lines.iter().map(said).collect::<Vec<_>>().join("\n");
|
||||
// only Got it on what was shown to look at: nothing to take up
|
||||
if !lines.iter().any(|l| l["kind"] != "seen") {
|
||||
return Some(format!("raea: the person has looked at what you showed them (your inbox, ~/.raea/inbox/{inbox}.jsonl):\n{list}\nNothing to do about it; carry on."));
|
||||
}
|
||||
// a session started again (resumed) after the person wrote to it while it was closed (Shane 11-28: "notes reach
|
||||
// closed sessions"): what waited is handed over before anything else
|
||||
if v["hook_event_name"].as_str() == Some("SessionStart") {
|
||||
return Some(format!(
|
||||
"raea: while this session was closed, the person sent this from the raea app (your inbox, ~/.raea/inbox/{inbox}.jsonl; marked read, so the app shows it as read):\n{list}\nTake it up first, before anything else. Answer an item with raea show --on ITEM --note LINE, or post the next version with raea show FILE --replaces ITEM."
|
||||
));
|
||||
}
|
||||
Some(format!(
|
||||
"raea: the person just sent this from the raea app (your inbox, ~/.raea/inbox/{inbox}.jsonl; marked read, so the app shows it as read):\n{list}\nTake it up now, before going on: it may change what you're doing. What you say next shows under your session in their feed; answer an item with raea show --on ITEM --note LINE, or post the next version with raea show FILE --replaces ITEM."
|
||||
))
|
||||
@@ -78,11 +94,17 @@ mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn each_line_is_handed_over_once_and_a_half_written_one_waits() {
|
||||
let d = std::env::temp_dir().join(format!("raea-inbox-{}", std::process::id()));
|
||||
/// an empty inbox folder of the test's own
|
||||
fn scratch(tag: &str) -> std::path::PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("raea-inbox-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_line_is_handed_over_once_and_a_half_written_one_waits() {
|
||||
let d = scratch("once");
|
||||
let f = d.join("claude-code-abcd1234.jsonl");
|
||||
std::fs::write(&f, "{\"kind\":\"message\",\"text\":\"more epic\"}\n{\"kind\":\"no").unwrap();
|
||||
let first = unread(&d, "claude-code-abcd1234");
|
||||
@@ -97,6 +119,25 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seen_is_said_as_seen_and_asks_nothing() {
|
||||
assert_eq!(said(&json!({"kind": "seen", "item": "i-2", "title": "Lobby", "text": "Seen"})), "- seen on item i-2 \"Lobby\"");
|
||||
assert_eq!(said(&json!({"kind": "seen", "item": "i-2", "title": "Lobby", "text": "Seen: lovely"})), "- seen on item i-2 \"Lobby\": lovely");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_waited_while_it_was_closed_is_handed_over_as_it_starts_again() {
|
||||
let d = scratch("start");
|
||||
std::fs::write(d.join("claude-code-5e55a0ff.jsonl"), "{\"kind\":\"edits\",\"item\":\"i-9\",\"title\":\"Cut\",\"text\":\"tighter open\"}\n").unwrap();
|
||||
// SAFETY: tests in this crate don't read RAEA_INBOX_DIR concurrently
|
||||
unsafe { std::env::set_var("RAEA_INBOX_DIR", &d) };
|
||||
let start = told("claude", &json!({"hook_event_name": "SessionStart", "source": "resume", "session_id": "5e55a0ff-1"})).unwrap();
|
||||
assert!(start.starts_with("raea: while this session was closed") && start.contains("- edits on item i-9 \"Cut\":\ntighter open"), "{start}");
|
||||
assert_eq!(told("claude", &json!({"hook_event_name": "UserPromptSubmit", "session_id": "5e55a0ff-1"})), None, "handed over once");
|
||||
unsafe { std::env::remove_var("RAEA_INBOX_DIR") };
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_inbox_is_named_as_raea_show_names_it() {
|
||||
assert_eq!(name("claude", &json!({"session_id": "15cd6bb0-8829-466f-a28a-bbca3d35be92"})).as_deref(), Some("claude-code-15cd6bb0"));
|
||||
|
||||
@@ -148,7 +148,13 @@ pub fn hook(args: &[String]) -> R<String> {
|
||||
let event = v["hook_event_name"].as_str().unwrap_or("");
|
||||
// what the person sent from the raea app since the last look (inbox.rs): handed over after any tool, and a turn about
|
||||
// to end goes on to take it up
|
||||
let sent = if matches!(event, "PostToolUse" | "AfterTool" | "Stop") { crate::inbox::told(agent, &v) } else { None };
|
||||
let sent = if matches!(event, "PostToolUse" | "AfterTool" | "Stop" | "SessionStart" | "UserPromptSubmit") { crate::inbox::told(agent, &v) } else { None };
|
||||
// a session starting again, or the person writing to it in its terminal: what they sent from raea while it was
|
||||
// closed or idle goes in as context first (Claude Code's and Codex's SessionStart and UserPromptSubmit read
|
||||
// hookSpecificOutput.additionalContext)
|
||||
if matches!(event, "SessionStart" | "UserPromptSubmit") {
|
||||
return Ok(sent.map(|t| json!({"hookSpecificOutput": {"hookEventName": event, "additionalContext": t}}).to_string()).unwrap_or_default());
|
||||
}
|
||||
if event == "Stop" {
|
||||
// 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();
|
||||
|
||||
@@ -110,7 +110,7 @@ fn shape(expr: &str, out: &Path, meshes: &mut BTreeMap<String, String>) -> R<Val
|
||||
// a mesh given by its own vertices (a <BufferMesh>, a three.js geometry through raea/r3f): written as it
|
||||
// is, with its normals and texture coordinates, since it needn't be a closed solid
|
||||
Some(b) => {
|
||||
let (t, uv) = raea_core_shape::buffer_tris(b)?;
|
||||
let (t, uv) = raea_core_shape::buffer_tris(&raea_core_shape::buffer_json(b)?)?;
|
||||
raea_core_shape::export_tris(&t, uv.as_deref(), &glb, "glb")?;
|
||||
raea_core_shape::export_tris(&t, uv.as_deref(), &obj, "obj")?;
|
||||
}
|
||||
|
||||
@@ -15,6 +15,8 @@ raea-core-facts = { path = "../../core/facts" }
|
||||
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)
|
||||
|
||||
@@ -19,7 +19,8 @@ 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 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)
|
||||
pub const USAGE: &str = "raea make status [DIR] [--json] [--plan] (a scene, kit, shot, cut or goal held to its plan, `make` on brief.ts: what's missing, each gate (renders and checks, raea ask's calibrated questions, the critic on the kind's rubric), the judge's rounds, and whether it's done, decided in code; --plan writes the gates as check lines under the job's task in plan.org; the agent's Stop hook holds it there)
|
||||
raea make judge [DIR] [--by claude|kimi] (a goal job: a fresh critic, which only reads, judges each `says` rule; review/goal.judge.json)
|
||||
raea make plan [DIR] [--no-review] (the plan stop: review/plan/floor-plan.png, a grey-box blockout from the entrance and its review sheets, comparison.png beside reference 0)
|
||||
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)
|
||||
@@ -102,7 +103,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; 7] = ["--only", "--model", "--tripo", "--meshy", "--name", "--to", "--out"];
|
||||
const VALUED: [&str; 8] = ["--only", "--model", "--tripo", "--meshy", "--name", "--to", "--out", "--by"];
|
||||
|
||||
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)
|
||||
@@ -184,6 +185,7 @@ 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()),
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
//! 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};
|
||||
use std::time::SystemTime;
|
||||
use std::{path::{Path, PathBuf}, time::SystemTime};
|
||||
|
||||
use raea_core_brief::make::{self, Make};
|
||||
use raea_core_facts::{Level, record::Entry};
|
||||
@@ -143,7 +142,7 @@ fn critic(job: &Job, newest: Option<SystemTime>, notes: &str) -> Vec<Value> {
|
||||
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 => "raea render EDIT.tsx --review review/r1",
|
||||
make::Kind::Scene | make::Kind::Cut | make::Kind::Goal => "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"))];
|
||||
};
|
||||
@@ -183,14 +182,16 @@ pub fn status(job: &Job) -> Value {
|
||||
}
|
||||
}
|
||||
let notes = notes_text(job.dir).unwrap_or_default();
|
||||
if !notes.to_lowercase().contains(&SKILL_HEADING.to_lowercase()) {
|
||||
if job.make.kind != make::Kind::Goal && !notes.to_lowercase().contains(&SKILL_HEADING.to_lowercase()) {
|
||||
missing.push(format!("NOTES.md with a \"{SKILL_HEADING}\" section (one line per thing that cost time; what the guide got wrong for this job)"));
|
||||
}
|
||||
let mut gates = checks(job);
|
||||
gates.extend(lods(job, ¬es));
|
||||
// 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) {
|
||||
// a cut job: its brief's rules over every delivered file (MK25-MK27), and the person's review its critic
|
||||
(Some(c), make::Kind::Cut) => gates.extend(raea_runtime_cut_plan::gates(c, job.dir).into_iter().map(|g| gate(g.name, g.of.as_deref(), g.clear, g.says))),
|
||||
(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, ¬es)),
|
||||
}
|
||||
let (asks, said) = crate::asked::gates(&sheets(job), job.ledger, ¬es);
|
||||
@@ -215,6 +216,7 @@ 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,
|
||||
})
|
||||
@@ -239,6 +241,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"];
|
||||
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 { "" }));
|
||||
if s["kind"] != "goal" { t.push(format!("judge: {} of {} rounds, {} passes in a row{}", j["rounds"], j["cap"], j["passesInARow"], if j["changeApproach"] == true { "; the same defect keeps coming back: change the approach for that part, not the dose" } else { "" })); }
|
||||
t.join("\n")
|
||||
}
|
||||
@@ -7,6 +7,8 @@ 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"
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
//! `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)
|
||||
}
|
||||
}
|
||||
}
|
||||
+62
-19
@@ -9,12 +9,14 @@
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
mod score;
|
||||
|
||||
use raea_runtime_bundle::flag;
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
pub const USAGE: &str = "raea motion \"LINE\" [--keys KEYS.json] [--seconds 5 | --frames N] [--seed 1] [--steps 100] [-o CLIP.json]";
|
||||
pub const ABOUT: &str = "body motion made on this machine by Kimodo (NVIDIA): a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads. On a Mac it runs on MLX (Apple silicon's GPU): the first use fetches the motion model (1.1 GB) into raea's models folder, and the first new line its text encoder (8.8 GB: Llama 3 8B in 8 bits with LLM2Vec's adapters). On Linux and Windows it runs upstream Kimodo on PyTorch, set up once by raea setup motion: on an NVIDIA GPU with CUDA (the text encoder, 16 GB in bf16, on the CPU unless the card has 18 GB or more), else on the CPU alone; reading a new line on the CPU takes about 18 GB of memory. A line's words are read once and kept. Licences: Kimodo's weights NVIDIA's Open Model License, Meta Llama 3 the Meta Llama 3 Community License, LLM2Vec's adapters MIT, Kimodo's code Apache-2.0";
|
||||
pub const USAGE: &str = "raea motion \"LINE\" [--keys KEYS.json] [--seconds 5 | --frames N] [--seed 1] [--seeds 1] [--steps 100] [-o CLIP.json]";
|
||||
pub const ABOUT: &str = "body motion made on this machine by Kimodo (NVIDIA): a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads. On a Mac it runs on MLX (Apple silicon's GPU): the first use fetches the motion model (1.1 GB) into raea's models folder, and the first new line its text encoder (8.8 GB: Llama 3 8B in 8 bits with LLM2Vec's adapters). On Linux and Windows it runs upstream Kimodo on PyTorch, set up once by raea setup motion: on an NVIDIA GPU with CUDA (the text encoder, 16 GB in bf16, on the CPU unless the card has 18 GB or more), else on the CPU alone; reading a new line on the CPU takes about 18 GB of memory. A line's words are read once and kept. --seeds N makes N takes (seeds SEED to SEED+N-1) and keeps the one with the fewest faults: a foot sliding while planted, the shoulders shrugging, the hips sinking, a hand or forearm into the torso or head (a skeletal check; each take's score is printed and the kept one's written into the clip). Licences: Kimodo's weights NVIDIA's Open Model License, Meta Llama 3 the Meta Llama 3 Community License, LLM2Vec's adapters MIT, Kimodo's code Apache-2.0";
|
||||
|
||||
pub const SETUP_USAGE: &str = "raea setup motion [--check]";
|
||||
pub const SETUP_ABOUT: &str = "what raea motion runs on, made where missing (--check only says): on a Mac the MLX models in raea's models folder (the motion model 1.1 GB, the text encoder 8.8 GB); on Linux and Windows, in raea's models folder's kimodo-torch, a Python 3.11 environment made by uv (which it needs on PATH: https://docs.astral.sh/uv) with PyTorch (its CUDA build where there is an NVIDIA driver, about 8 GB, else CPU only, about 2 GB) and upstream Kimodo (nv-tlabs/kimodo at e1c219c, Apache-2.0), then the weights: Kimodo-SOMA-RP-v1 (1.1 GB, NVIDIA Open Model License), LLM2Vec's two adapters (0.3 GB, MIT) and Meta Llama 3 8B Instruct in bf16 (16 GB, Meta Llama 3 Community License, from NousResearch's ungated copy, checked file by file against Meta's SHA-256); about 26 GB in all. It says what this machine has and where each network runs: the denoiser on CUDA when there is an NVIDIA GPU, else the CPU; the text encoder beside it on a GPU of 18 GB or more, else the CPU";
|
||||
@@ -27,7 +29,7 @@ fn number(args: &[String], name: &str, default: f64) -> R<f64> {
|
||||
}
|
||||
|
||||
fn line(args: &[String]) -> String {
|
||||
const WITH_VALUE: [&str; 6] = ["--keys", "--seconds", "--frames", "--seed", "--steps", "-o"];
|
||||
const WITH_VALUE: [&str; 7] = ["--keys", "--seconds", "--frames", "--seed", "--seeds", "--steps", "-o"];
|
||||
let mut out = Vec::new();
|
||||
let mut i = 1;
|
||||
while i < args.len() {
|
||||
@@ -50,6 +52,7 @@ struct Ask {
|
||||
constraints: Option<serde_json::Value>,
|
||||
frames: usize,
|
||||
seed: u64,
|
||||
seeds: usize,
|
||||
steps: usize,
|
||||
out: Option<String>,
|
||||
}
|
||||
@@ -64,15 +67,21 @@ pub fn motion(args: &[String]) -> R<String> {
|
||||
Some(_) => number(args, "--frames", 150.0)? as usize,
|
||||
None => (number(args, "--seconds", 5.0)? * 30.0).round() as usize,
|
||||
};
|
||||
if !(2..=600).contains(&frames) {
|
||||
return Err(format!("a clip is 2 to 600 frames (20 s at 30 a second), asked {frames}"));
|
||||
// Kimodo's own limit (its docs, key_concepts/limitations.md): past 10 s a clip drifts and breaks up (11-27: a
|
||||
// 12.3 s talk clip's feet spread 47 -> 69 cm, shoulders rose 9 cm, the last half second glitched)
|
||||
if !(2..=300).contains(&frames) {
|
||||
return Err(format!(
|
||||
"a clip is 2 to 300 frames (10 s at 30 a second, Kimodo's limit: longer clips drift and break up), asked {frames}; \
|
||||
for longer, make 10 s clips one after another, each from --keys holding the last frames of the one before"
|
||||
));
|
||||
}
|
||||
let constraints = match &keys {
|
||||
Some(p) => Some(serde_json::from_str::<serde_json::Value>(&std::fs::read_to_string(p).map_err(|e| format!("{p}: {e}"))?).map_err(|e| format!("{p}: {e}"))?),
|
||||
None => None,
|
||||
};
|
||||
let (seed, steps) = (number(args, "--seed", 1.0)? as u64, (number(args, "--steps", 100.0)? as usize).max(2));
|
||||
make(Ask { words, keys, constraints, frames, seed, steps, out: flag(args, "-o") })
|
||||
let seeds = (number(args, "--seeds", 1.0)? as usize).clamp(1, 32);
|
||||
make(Ask { words, keys, constraints, frames, seed, seeds, steps, out: flag(args, "-o") })
|
||||
}
|
||||
|
||||
/// -o, else a file named by the line's words in the working folder
|
||||
@@ -83,6 +92,25 @@ fn out_path(out: Option<String>, clean: &str) -> PathBuf {
|
||||
}))
|
||||
}
|
||||
|
||||
/// the take with the lowest score of those made, its seed, and a line per take ("" for a single take)
|
||||
fn keep_best(takes: Vec<(u64, raea_sys_kimodo::decode::Motion)>, sk: &raea_sys_kimodo::skeleton::Skeleton) -> (u64, raea_sys_kimodo::decode::Motion, Option<score::Score>, String) {
|
||||
let one = takes.len() == 1;
|
||||
let mut scored: Vec<(u64, raea_sys_kimodo::decode::Motion, score::Score)> = takes.into_iter().map(|(s, m)| { let sc = score::score(&m, sk); (s, m, sc) }).collect();
|
||||
let report = if one { String::new() } else { scored.iter().map(|(s, _, sc)| format!("\n seed {s}: {}", sc.line())).collect::<String>() };
|
||||
scored.sort_by(|a, b| a.2.total.total_cmp(&b.2.total));
|
||||
let (s, m, sc) = scored.remove(0);
|
||||
(s, m, Some(sc), report)
|
||||
}
|
||||
|
||||
/// the kept take's score, written into the clip
|
||||
fn with_score(mut clip: serde_json::Value, sc: &Option<score::Score>, tried: usize) -> serde_json::Value {
|
||||
if let Some(sc) = sc {
|
||||
clip["score"] = serde_json::json!({"total": sc.total, "foot_drift_cm": sc.foot_drift_cm, "shoulder_rise_cm": sc.shoulder_rise_cm,
|
||||
"hip_drop_cm": sc.hip_drop_cm, "collision_cm": sc.collision_cm, "takes": tried});
|
||||
}
|
||||
clip
|
||||
}
|
||||
|
||||
/// how far the hips end from where they start, on the ground
|
||||
fn travel(m: &raea_sys_kimodo::decode::Motion) -> f32 {
|
||||
let r = &m.root;
|
||||
@@ -109,10 +137,17 @@ 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 motion = decode::decode(&made.features, &stats, &sk);
|
||||
let mut takes = Vec::new();
|
||||
let mut last = None;
|
||||
for s in ask.seed..ask.seed + ask.seeds as u64 {
|
||||
let job = torch::Job { line: &ask.words, frames: ask.frames, seed: s, steps: ask.steps, keys, cfg: (2.0, 2.0) };
|
||||
let made = t.make(&job).map_err(|e| format!("raea motion: {e}"))?;
|
||||
takes.push((s, decode::decode(&made.features, &stats, &sk)));
|
||||
last = Some(made);
|
||||
}
|
||||
let made = last.ok_or("raea motion: no take")?;
|
||||
let (seed, motion, sc, report) = keep_best(takes, &sk);
|
||||
let info = &made.info;
|
||||
let clean = info["line"].as_str().unwrap_or(&ask.words).to_string();
|
||||
let (dev, text_dev) = (info["motion"].as_str().unwrap_or("?"), info["text"].as_str().unwrap_or("?"));
|
||||
@@ -120,26 +155,28 @@ fn make(ask: Ask) -> R<String> {
|
||||
Some(g) => format!("on PyTorch {} with CUDA ({g}; the text encoder on {text_dev}), upstream nv-tlabs/kimodo {}", info["torch"].as_str().unwrap_or("?"), &torch::KIMODO[..7]),
|
||||
None => format!("on PyTorch {} on the CPU, upstream nv-tlabs/kimodo {}", info["torch"].as_str().unwrap_or("?"), &torch::KIMODO[..7]),
|
||||
};
|
||||
let clip = decode::clip_json_on(&motion, &sk, ask.seed, ask.steps, &clean, ask.constraints.is_some(), &on);
|
||||
let clip = with_score(decode::clip_json_on(&motion, &sk, seed, ask.steps, &clean, ask.constraints.is_some(), &on), &sc, ask.seeds);
|
||||
let out = out_path(ask.out, &clean);
|
||||
std::fs::write(&out, serde_json::to_string(&clip).unwrap_or_default()).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
// the hips as PyTorch decoded them against decode.rs's: the features were read as Kimodo wrote them
|
||||
let ours: Vec<[f32; 3]> = motion.joints77.iter().map(|f| f[0]).collect();
|
||||
let gap = torch::root_gap(&info["root"], &ours).map(|g| format!(", decoded here within {:.3} mm of PyTorch's own", g * 1000.0)).unwrap_or_default();
|
||||
let gap = if ask.seeds > 1 { String::new() } else { torch::root_gap(&info["root"], &ours).map(|g| format!(", decoded here within {:.3} mm of PyTorch's own", g * 1000.0)).unwrap_or_default() };
|
||||
let f = |k: &str| info[k].as_f64().unwrap_or(0.0);
|
||||
let read = if f("read_s") > 0.0 { format!(", reading the line {:.1} s after {:.1} s loading its encoder", f("read_s"), f("text_load_s")) } else { String::new() };
|
||||
Ok(format!(
|
||||
"APPLIED motion {:?}{}, {} frames ({:.1} s), seed {}, {} steps -> {} (made {on} in {:.1} s after {:.1} s loading{read}; the hips end {:.2} m from where they start{gap})",
|
||||
"APPLIED motion {:?}{}, {} frames ({:.1} s), seed {}{}, {} steps -> {} (made {on} in {:.1} s after {:.1} s loading{read}; the hips end {:.2} m from where they start{gap}; {}){report}",
|
||||
clean,
|
||||
if ask.keys.is_some() { " with keys" } else { "" },
|
||||
ask.frames,
|
||||
ask.frames as f64 / 30.0,
|
||||
ask.seed,
|
||||
seed,
|
||||
if ask.seeds > 1 { format!(", the best of {} takes", ask.seeds) } else { String::new() },
|
||||
ask.steps,
|
||||
out.display(),
|
||||
f("gen_s"),
|
||||
f("load_s"),
|
||||
travel(&motion),
|
||||
sc.as_ref().map(|s| s.line()).unwrap_or_default(),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -154,23 +191,29 @@ fn make(ask: Ask) -> R<String> {
|
||||
let mut k = raea_sys_kimodo::Kimodo::fetch(&mut progress).map_err(|e| format!("raea motion: {e}"))?;
|
||||
let (clean, emb) = k.encode(&ask.words).map_err(|e| format!("raea motion: {e}"))?;
|
||||
let load_s = t0.elapsed().as_secs_f64();
|
||||
let made_from = raea_sys_kimodo::Ask { line: &ask.words, frames: ask.frames, seed: ask.seed, steps: ask.steps, constraints: ask.constraints.as_ref(), cfg: (2.0, 2.0) };
|
||||
let t1 = std::time::Instant::now();
|
||||
let made = k.make(&made_from, emb.as_deref(), None).map_err(|e| format!("raea motion: {e}"))?;
|
||||
let mut takes = Vec::new();
|
||||
for s in ask.seed..ask.seed + ask.seeds as u64 {
|
||||
let made_from = raea_sys_kimodo::Ask { line: &ask.words, frames: ask.frames, seed: s, steps: ask.steps, constraints: ask.constraints.as_ref(), cfg: (2.0, 2.0) };
|
||||
takes.push((s, k.make(&made_from, emb.as_deref(), None).map_err(|e| format!("raea motion: {e}"))?.motion));
|
||||
}
|
||||
let gen_s = t1.elapsed().as_secs_f64();
|
||||
let clip = raea_sys_kimodo::decode::clip_json(&made.motion, &k.skeleton, ask.seed, ask.steps, &clean, ask.constraints.is_some());
|
||||
let (seed, motion, sc, report) = keep_best(takes, &k.skeleton);
|
||||
let clip = with_score(raea_sys_kimodo::decode::clip_json(&motion, &k.skeleton, seed, ask.steps, &clean, ask.constraints.is_some()), &sc, ask.seeds);
|
||||
let out = out_path(ask.out, &clean);
|
||||
std::fs::write(&out, serde_json::to_string(&clip).unwrap_or_default()).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
Ok(format!(
|
||||
"APPLIED motion {:?}{}, {} frames ({:.1} s), seed {}, {} steps -> {} (made on this Mac in {gen_s:.1} s after {load_s:.1} s loading and reading the line; the hips end {:.2} m from where they start)",
|
||||
"APPLIED motion {:?}{}, {} frames ({:.1} s), seed {}{}, {} steps -> {} (made on this Mac in {gen_s:.1} s after {load_s:.1} s loading and reading the line; the hips end {:.2} m from where they start; {}){report}",
|
||||
clean,
|
||||
if ask.keys.is_some() { " with keys" } else { "" },
|
||||
ask.frames,
|
||||
ask.frames as f64 / 30.0,
|
||||
ask.seed,
|
||||
seed,
|
||||
if ask.seeds > 1 { format!(", the best of {} takes", ask.seeds) } else { String::new() },
|
||||
ask.steps,
|
||||
out.display(),
|
||||
travel(&made.motion)
|
||||
travel(&motion),
|
||||
sc.as_ref().map(|s| s.line()).unwrap_or_default(),
|
||||
))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
//! 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
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "raea-app-playable"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "`raea playable`: a raea game exported as a playable ad, one page or ZIP per ad network (docs/playables.feature)"
|
||||
|
||||
[dependencies]
|
||||
dunce = "1"
|
||||
# the game and sdk/playable's host bundled into one page by raea's own bundler (Rolldown, in process)
|
||||
raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
# where raea's files are: an install's share/raea, else this checkout
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
regex = "1"
|
||||
serde_json = "1"
|
||||
zip = { version = "9", default-features = false, features = ["deflate-flate2"] }
|
||||
@@ -0,0 +1,102 @@
|
||||
//! `raea playable GAME.tsx -o DIR`: a raea game exported as a playable ad (docs/playables.feature PA13). The same TSX
|
||||
//! that renders with `raea render` as the video ad (it plays itself) is linted (lint.rs), bundled once with
|
||||
//! sdk/playable's browser host by raea's own bundler (Rolldown, in process: minified, its pictures and tables carried
|
||||
//! in the script, one three.js), and written as each network's page or ZIP (pages.rs), each checked against its cap.
|
||||
mod lint;
|
||||
mod pages;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
pub const USAGE: &str = "raea playable GAME.tsx -o DIR [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both]";
|
||||
pub const ABOUT: &str = "a game as a playable ad: one page or ZIP per network (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff, preview), each under its 5 MB cap, from the TSX that renders as the video ad";
|
||||
|
||||
/// A path as an import specifier (no Windows verbatim prefix, which Rolldown can't open): raea-bundle's own
|
||||
pub(crate) use raea_runtime_bundle::spec;
|
||||
|
||||
fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
|
||||
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
|
||||
}
|
||||
|
||||
/// The folder whose node_modules holds the three.js a playable draws with: the project's own (`raea add [email protected]`),
|
||||
/// else the copy beside sdk/playable or sdk/r3f in raea's own files
|
||||
fn three_dir(game: &Path, home: &Path) -> R<PathBuf> {
|
||||
let mut d = game.parent();
|
||||
while let Some(dir) = d {
|
||||
if dir.join("node_modules/three/package.json").is_file() {
|
||||
return Ok(dir.to_path_buf());
|
||||
}
|
||||
d = dir.parent();
|
||||
}
|
||||
["sdk/playable", "sdk/r3f"]
|
||||
.iter()
|
||||
.map(|p| home.join(p))
|
||||
.find(|d| d.join("node_modules/three/package.json").is_file())
|
||||
.ok_or_else(|| "a playable draws its 3D with three.js, which this project doesn't have: `raea add [email protected]` in it".into())
|
||||
}
|
||||
|
||||
/// The game and the host in one minified script that carries its files
|
||||
fn bundle(game: &Path, home: &Path) -> R<String> {
|
||||
let host = home.join("sdk/playable/src/host/main.tsx");
|
||||
if !host.is_file() {
|
||||
return Err(format!("{}: raea's playable host isn't there", host.display()));
|
||||
}
|
||||
let three = three_dir(game, home)?;
|
||||
let out = std::env::temp_dir().join(format!("raea-playable-{}.js", std::process::id()));
|
||||
let entry = format!("import {:?};\nimport {:?};\n", spec(game), spec(&host));
|
||||
let alias = format!("three/={}", three.display());
|
||||
let r = raea_runtime_bundle::bundle_entry(&entry, &out, &["--minify", "1", "--inline", "1", "--alias", &alias]);
|
||||
let js = r.and_then(|_| std::fs::read_to_string(&out).map_err(|e| e.to_string()));
|
||||
let _ = std::fs::remove_file(&out);
|
||||
js
|
||||
}
|
||||
|
||||
pub fn cli(args: &[String]) -> R<String> {
|
||||
let game = args.get(1).filter(|a| !a.starts_with('-')).ok_or(USAGE)?;
|
||||
let game = dunce::canonicalize(game).map_err(|e| format!("{game}: {e}"))?;
|
||||
let out = PathBuf::from(flag(args, "-o").ok_or(format!("-o DIR is required: {USAGE}"))?);
|
||||
let networks: Vec<&str> = flag(args, "--networks").map(|n| n.split(',').filter(|s| !s.is_empty()).collect()).unwrap_or_else(|| pages::NETWORKS.to_vec());
|
||||
if let Some(bad) = networks.iter().find(|n| !pages::NETWORKS.contains(n)) {
|
||||
return Err(format!("raea playable: no network {bad} (one of {})", pages::NETWORKS.join(", ")));
|
||||
}
|
||||
let orientation = flag(args, "--orientation").unwrap_or("both");
|
||||
if !["portrait", "landscape", "both"].contains(&orientation) {
|
||||
return Err("--orientation is portrait, landscape or both".into());
|
||||
}
|
||||
let store = serde_json::json!({"ios": flag(args, "--ios").unwrap_or(""), "android": flag(args, "--android").unwrap_or("")}).to_string();
|
||||
let card = serde_json::json!({"title": flag(args, "--title").unwrap_or(""), "cta": flag(args, "--cta").unwrap_or("Play now")}).to_string();
|
||||
let name = game.file_stem().and_then(|s| s.to_str()).unwrap_or("playable").to_string();
|
||||
|
||||
let mut report = Vec::new();
|
||||
let found = lint::lint(&game)?;
|
||||
report.push(format!("3D kinds: {}", if found.kinds.is_empty() { "none".into() } else { found.kinds.join(", ") }));
|
||||
for c in &found.comps {
|
||||
let shape = if c.height > c.width { "portrait" } else { "landscape" };
|
||||
report.push(format!("composition {}: {}x{} {shape}, {} fps, {:.0} s", c.id, c.width, c.height, c.fps, c.frames as f64 / c.fps.max(1.0)));
|
||||
}
|
||||
report.extend(found.notes.iter().map(|n| format!("note: {n}")));
|
||||
if !found.refusals.is_empty() {
|
||||
// the reasons first: the CLI marks an error's first line REFUSED
|
||||
let mut why = found.refusals.clone();
|
||||
why.extend(report);
|
||||
return Err(why.join("\n"));
|
||||
}
|
||||
|
||||
let js = bundle(&game, &raea_io_home::home())?;
|
||||
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
let mut over = false;
|
||||
for net in networks {
|
||||
let script = format!("{}\n{js}", pages::preamble(net, &store, &card));
|
||||
let w = pages::write(net, &name, &script, &out, orientation)?;
|
||||
let ok = w.bytes <= pages::CAP;
|
||||
over |= !ok;
|
||||
report.push(format!("{:<10} {:<40} {:>6} KB / {} KB {}", w.network, w.file.display(), w.bytes / 1024, pages::CAP / 1024, if ok { "ok" } else { "OVER" }));
|
||||
}
|
||||
if over {
|
||||
report.insert(0, format!("a page is over its network's {} KB cap", pages::CAP / 1024));
|
||||
return Err(report.join("\n"));
|
||||
}
|
||||
report.push(format!("APPLIED {name} exported as a playable to {}", out.display()));
|
||||
Ok(report.join("\n"))
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
//! What a playable can't have, refused before it is bundled (docs/playables.feature PA4): the source read for files
|
||||
//! from disk, the network and the native engine's modules; the compositions rendered (sdk/playable/src/export/walk.ts,
|
||||
//! through `raea run` in a process of its own) for their shapes and the 3D kinds the host doesn't draw.
|
||||
use super::R;
|
||||
use serde_json::Value;
|
||||
use std::path::Path;
|
||||
|
||||
/// One composition the game registers
|
||||
pub struct Comp {
|
||||
pub id: String,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub fps: f64,
|
||||
pub frames: u64,
|
||||
}
|
||||
|
||||
/// What the lint found: refusals stop the export, notes don't
|
||||
pub struct Found {
|
||||
pub comps: Vec<Comp>,
|
||||
pub kinds: Vec<String>,
|
||||
pub notes: Vec<String>,
|
||||
pub refusals: Vec<String>,
|
||||
}
|
||||
|
||||
const SOURCE_RULES: &[(&str, &str)] = &[
|
||||
(r"\bstaticFile\s*\(", "staticFile() reads the edit's folder at render time; import the file instead (`import icon from \"./icon.png\"`), which the export carries in the page"),
|
||||
(r"https?://", "a URL in the source: a playable makes no network requests (every network refuses one)"),
|
||||
(r"\bfetch\s*\(|XMLHttpRequest|WebSocket", "fetch/XHR/WebSocket: a playable makes no network requests"),
|
||||
(r#"from\s+["']raea/(native|ml|character|physics|media|matchmove|modelling)["']"#, "a module that needs the native engine (native calls, models, physics, footage)"),
|
||||
(r"<(Video|Audio)\b", "<Video>/<Audio> play through the native media stack; a playable's sound is PA6 (not yet)"),
|
||||
];
|
||||
|
||||
/// The game's source and its compositions, judged
|
||||
pub fn lint(game: &Path) -> R<Found> {
|
||||
let src = std::fs::read_to_string(game).map_err(|e| format!("{}: {e}", game.display()))?;
|
||||
let mut refusals = Vec::new();
|
||||
let mut notes = Vec::new();
|
||||
// a URL the SVG namespace names is a name, not a request
|
||||
let src_no_ns = src.replace("http://www.w3.org", "");
|
||||
for (re, why) in SOURCE_RULES {
|
||||
if regex::Regex::new(re).map_err(|e| e.to_string())?.is_match(&src_no_ns) {
|
||||
refusals.push(why.to_string());
|
||||
}
|
||||
}
|
||||
if !src.contains("raea/playable") {
|
||||
notes.push("no raea/playable import: the game never opens the store itself (add an <EndCard> or <InstallButton>); the host's own end card shows at the last frame".into());
|
||||
}
|
||||
let walked = match walk(game) {
|
||||
Ok(w) => w,
|
||||
// what the source can't have (a fetch, a URL) often stops the render too: the refusal says why, the render's end doesn't
|
||||
Err(_) if !refusals.is_empty() => return Ok(Found { comps: vec![], kinds: vec![], notes, refusals }),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let comps: Vec<Comp> = walked["comps"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|c| Comp {
|
||||
id: c["id"].as_str().unwrap_or("").into(),
|
||||
width: c["width"].as_u64().unwrap_or(0) as u32,
|
||||
height: c["height"].as_u64().unwrap_or(0) as u32,
|
||||
fps: c["fps"].as_f64().unwrap_or(30.0),
|
||||
frames: c["frames"].as_u64().unwrap_or(0),
|
||||
})
|
||||
.collect();
|
||||
let strings = |k: &str| walked[k].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(String::from)).collect::<Vec<_>>();
|
||||
if comps.is_empty() {
|
||||
refusals.push("no composition registered (registerRoot)".into());
|
||||
}
|
||||
if comps.len() == 1 {
|
||||
notes.push("one composition: the other orientation is letterboxed (Unity, AppLovin, Moloco and Mintegral want both; register a second one at the other shape)".into());
|
||||
}
|
||||
for k in strings("refused") {
|
||||
refusals.push(format!("3D kind {k} isn't drawn in a playable"));
|
||||
}
|
||||
Ok(Found { comps, kinds: strings("kinds"), notes, refusals })
|
||||
}
|
||||
|
||||
/// sdk/playable's walk run on the engine (`raea run`) after the game, in a process of its own so the game's React stays
|
||||
/// out of this one; its answer is the JSON it prints
|
||||
fn walk(game: &Path) -> R<Value> {
|
||||
let walk = raea_io_home::home().join("sdk/playable/src/export/walk.ts");
|
||||
if !walk.is_file() {
|
||||
return Err(format!("{}: raea's playable SDK isn't there", walk.display()));
|
||||
}
|
||||
let work = std::env::temp_dir().join(format!("raea-playable-lint-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&work).map_err(|e| e.to_string())?;
|
||||
let entry = work.join("lint.ts");
|
||||
std::fs::write(&entry, format!("import {:?};\nexport {{ default }} from {:?};\n", super::spec(game), super::spec(&walk))).map_err(|e| e.to_string())?;
|
||||
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
let run = std::process::Command::new(exe).arg("run").arg(&entry).output().map_err(|e| format!("raea run: {e}"));
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
let run = run?;
|
||||
let out = String::from_utf8_lossy(&run.stdout);
|
||||
if !run.status.success() {
|
||||
let err = String::from_utf8_lossy(&run.stderr);
|
||||
let said: Vec<&str> = err.lines().chain(out.lines()).filter(|l| !l.trim().is_empty()).collect();
|
||||
// the line that names the error, else the last one ("… ended with exit 1" says nothing)
|
||||
let why = said.iter().find(|l| l.contains("Error") || l.contains("error:")).or(said.last()).unwrap_or(&"").trim().to_string();
|
||||
return Err(format!("the game didn't render for the lint: {why}"));
|
||||
}
|
||||
let at = out.find('{').ok_or("the lint's walk printed no answer")?;
|
||||
serde_json::from_str(&out[at..]).map_err(|e| format!("the lint's walk: {e}"))
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
//! Each network's package around the one script (docs/playables.feature, the Background's table): the page every
|
||||
//! network gets, with that network's own tags, as one HTML file or a ZIP, checked against its cap.
|
||||
use super::R;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub const NETWORKS: &[&str] = &["applovin", "unity", "google", "meta", "moloco", "mintegral", "tiktok", "liftoff", "preview"];
|
||||
|
||||
/// Every network's cap, 5 MB (TikTok's counted zipped, which is what's written)
|
||||
pub const CAP: u64 = 5 * 1024 * 1024;
|
||||
|
||||
/// What one network got: the file and its size
|
||||
pub struct Written {
|
||||
pub network: String,
|
||||
pub file: PathBuf,
|
||||
pub bytes: u64,
|
||||
}
|
||||
|
||||
/// The settings a page starts with, as the globals the host reads (sdk/playable network.ts, host/main.tsx): the network,
|
||||
/// the store links, the end card's words
|
||||
pub fn preamble(network: &str, store: &str, card: &str) -> String {
|
||||
format!("var __RAEA_NETWORK__={},__RAEA_STORE__={store},__RAEA_PLAYABLE__={card};", serde_json::to_string(network).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The page: the network's head and body tags, then the script (a page's inline script ends at the first "</script")
|
||||
pub fn page(title: &str, head: &str, body: &str, script: &str) -> String {
|
||||
let title = title.replace('&', "&").replace('<', "<");
|
||||
format!(
|
||||
"<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover\">\n<title>{title}</title>\n{head}\n</head>\n<body>\n{body}\n<script>\n{}\n</script>\n</body>\n</html>\n",
|
||||
script.replace("</script", "<\\/script")
|
||||
)
|
||||
}
|
||||
|
||||
fn zip(file: &Path, entries: &[(String, String)]) -> R<()> {
|
||||
let f = std::fs::File::create(file).map_err(|e| format!("{}: {e}", file.display()))?;
|
||||
let mut w = zip::ZipWriter::new(f);
|
||||
let o = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||
for (name, text) in entries {
|
||||
w.start_file(name.as_str(), o).map_err(|e| e.to_string())?;
|
||||
w.write_all(text.as_bytes()).map_err(|e| e.to_string())?;
|
||||
}
|
||||
w.finish().map_err(|e| e.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `network`'s package of `script` (its preamble already first) written into `out` as NAME-NETWORK.html or .zip
|
||||
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__={};");
|
||||
}
|
||||
}
|
||||
@@ -21,8 +21,10 @@ struct Hook {
|
||||
fn hooks(agent: &str) -> R<Vec<Hook>> {
|
||||
let h = |event, matcher, secs| Hook { event, matcher, secs };
|
||||
Ok(match agent {
|
||||
"claude" => vec![h("PreToolUse", "Bash", 30), h("PostToolUse", "*", 60), h("Stop", "", 30)],
|
||||
"codex" => vec![h("PreToolUse", "^(Bash|shell|shell_command|exec_command)$", 30), h("PostToolUse", "^(apply_patch|Edit|Write)$", 60)],
|
||||
// SessionStart and UserPromptSubmit: notes sent from raea while the session was closed or idle reach it when it
|
||||
// starts again or is next written to (Shane 11-28: "notes reach closed sessions")
|
||||
"claude" => vec![h("PreToolUse", "Bash", 30), h("PostToolUse", "*", 60), h("Stop", "", 30), h("SessionStart", "", 10), h("UserPromptSubmit", "", 10)],
|
||||
"codex" => vec![h("PreToolUse", "^(Bash|shell|shell_command|exec_command)$", 30), h("PostToolUse", "^(apply_patch|Edit|Write)$", 60), h("Stop", "", 30), h("SessionStart", "", 10), h("UserPromptSubmit", "", 10)],
|
||||
"gemini" => vec![h("BeforeTool", "run_shell_command", 30), h("AfterTool", "write_file|replace", 60)],
|
||||
"kimi" => vec![h("PreToolUse", "Bash|Shell", 30), h("PostToolUse", "Write|Edit|WriteFile|StrReplaceFile", 60)],
|
||||
a => return Err(format!("no agent {a:?}: claude, codex, kimi or gemini")),
|
||||
@@ -124,7 +126,8 @@ mod tests {
|
||||
let c = d.join("claude/settings.json");
|
||||
std::fs::create_dir_all(c.parent().unwrap()).unwrap();
|
||||
std::fs::write(&c, r#"{"model":"x","hooks":{"PostToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"other"}]},{"matcher":"Write","hooks":[{"type":"command","command":"raea hook claude"}]}]}}"#).unwrap();
|
||||
let [pre, post, stop] = <[Hook; 3]>::try_from(hooks("claude").unwrap()).ok().unwrap();
|
||||
let [pre, post, stop, start, prompt] = <[Hook; 5]>::try_from(hooks("claude").unwrap()).ok().unwrap();
|
||||
assert!(add_json(&c, "claude", &start).unwrap() && add_json(&c, "claude", &prompt).unwrap() && !add_json(&c, "claude", &start).unwrap());
|
||||
assert!(add_json(&c, "claude", &pre).unwrap() && !add_json(&c, "claude", &pre).unwrap());
|
||||
assert!(add_json(&c, "claude", &post).unwrap() && !add_json(&c, "claude", &post).unwrap(), "an older raea's after-save hook is widened to every tool, once");
|
||||
assert!(add_json(&c, "claude", &stop).unwrap() && !add_json(&c, "claude", &stop).unwrap());
|
||||
@@ -133,6 +136,9 @@ mod tests {
|
||||
assert_eq!((v["hooks"]["PostToolUse"][0]["matcher"].as_str(), v["hooks"]["PostToolUse"][1]["matcher"].as_str()), (Some("Bash"), Some("*")));
|
||||
assert_eq!(v["hooks"]["PreToolUse"][0]["hooks"][0]["command"], "raea hook claude");
|
||||
assert_eq!(v["hooks"]["Stop"][0]["hooks"][0]["command"], "raea hook claude");
|
||||
assert_eq!(v["hooks"]["SessionStart"][0]["hooks"][0]["command"], "raea hook claude");
|
||||
assert_eq!(v["hooks"]["UserPromptSubmit"][0]["hooks"][0]["command"], "raea hook claude");
|
||||
assert_eq!(hooks("codex").unwrap().iter().map(|h| h.event).collect::<Vec<_>>(), ["PreToolUse", "PostToolUse", "Stop", "SessionStart", "UserPromptSubmit"]);
|
||||
let g = d.join("gemini/settings.json");
|
||||
let [before, _] = <[Hook; 2]>::try_from(hooks("gemini").unwrap()).ok().unwrap();
|
||||
assert!(add_json(&g, "gemini", &before).unwrap());
|
||||
|
||||
@@ -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 "a playable: it needs the playable host's raea_playable (sdk/playable)" ;;
|
||||
examples/playables/brick-rush.tsx) echo "RAEA_LIVE3D_CHECK panics on frame 1: the fast rows carry the sun's rotation and the full rows don't (runtime/scene/src/live.rs; docs/playables.feature PA18)" ;;
|
||||
sdk/raea/bench/bevy-parity/3d/rotate_environment_map.tsx) echo "clearcoat textures need raea-sys-material's multi-layer feature, off by default (as bench/bevy-parity/runs.tsv leaves it out)" ;;
|
||||
esac; }
|
||||
SAME=0 DIFF=0 ERR=0 SKIP=0
|
||||
|
||||
@@ -93,6 +93,10 @@ pub struct Phrase {
|
||||
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>,
|
||||
}
|
||||
@@ -151,6 +155,9 @@ pub fn quotes(c: &Cut) -> Vec<(String, &str)> {
|
||||
}
|
||||
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));
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
//! 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
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
pub mod brief;
|
||||
pub mod cut;
|
||||
pub mod goal;
|
||||
pub mod make;
|
||||
pub mod parts;
|
||||
pub mod script;
|
||||
@@ -41,6 +42,7 @@ pub fn declarations() -> String {
|
||||
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"
|
||||
}
|
||||
|
||||
+34
-1
@@ -21,6 +21,8 @@ pub enum Kind {
|
||||
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,6 +58,13 @@ pub struct Make {
|
||||
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)]
|
||||
@@ -194,7 +203,7 @@ 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"][self as usize]
|
||||
["scene", "kit", "shot", "cut", "goal"][self as usize]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,6 +214,7 @@ pub fn dials(kind: Kind) -> &'static [&'static str] {
|
||||
Kind::Kit => &["count", "variety", "detail", "wear", "wetness", "warmth", "look"],
|
||||
Kind::Shot => &["res", "seconds", "lens", "handheld", "look"],
|
||||
Kind::Cut => &["look"],
|
||||
Kind::Goal => &[],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -232,9 +242,16 @@ 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 == '_')
|
||||
@@ -258,6 +275,12 @@ pub fn doctor(m: &Make) -> Vec<String> {
|
||||
(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());
|
||||
}
|
||||
@@ -295,3 +318,13 @@ 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,
|
||||
}
|
||||
+29
-7
@@ -109,10 +109,26 @@ fn hash_props(m: &Map<String, Value>, h: &mut impl Hasher, take: impl Fn(&str) -
|
||||
}
|
||||
}
|
||||
|
||||
/// A standard material's maps whose picture a render swaps frame by frame (raea-sys-material's SwappedMaps,
|
||||
/// docs/render-memory.feature RM6): a change of picture keys the map's column instead of cutting the part's track.
|
||||
/// The packed roughness and metalness maps are one texture made from two pictures, so they still cut.
|
||||
pub const SWAPPED_MAPS: [(&str, &str); 5] = [("map", "map"), ("normalMap", "normal_map"), ("metallicRoughnessMap", "mr_map"), ("aoMap", "ao_map"), ("emissiveMap", "emissive_map")];
|
||||
|
||||
/// Whether a part's standard material takes its pictures frame by frame in a render (SWAPPED_MAPS): a plain
|
||||
/// standard or physical surface, none of the surfaces built over it (a grid, paint, wear, a procedural pattern, a
|
||||
/// shader), whose maps are made into their own material once.
|
||||
pub fn swaps_maps(it: &Item) -> bool {
|
||||
let Some(m) = &it.material else { return false };
|
||||
matches!(&*m.kind, "MeshStandardMaterial" | "MeshPhysicalMaterial")
|
||||
&& !["grid", "paint", "wear", "procedural", "shader", "toon"].iter().any(|k| m.props.contains_key(*k))
|
||||
&& !["shader", "three", "surface"].iter().any(|k| it.props.contains_key(*k))
|
||||
}
|
||||
|
||||
/// A part's kept inputs as one number: what its row takes from the frame it's spawned in (its shape, its material's
|
||||
/// maps and modes, its words and their glyphs, a model's file). Two frames of a part with the same number make the
|
||||
/// same kept columns.
|
||||
pub fn spawn_sig(it: &Item) -> u64 {
|
||||
/// same kept columns. With `swapped`, a swapped map's picture is left out (whether it has one still counts), as a
|
||||
/// render keys it (SWAPPED_MAPS) rather than cutting the part's track for it; without, every picture counts.
|
||||
pub fn spawn_sig(it: &Item, swapped: bool) -> u64 {
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
it.kind.hash(&mut h);
|
||||
match it.kind {
|
||||
@@ -120,9 +136,14 @@ pub fn spawn_sig(it: &Item) -> u64 {
|
||||
it.shape.hash(&mut h);
|
||||
if let Some(m) = &it.material {
|
||||
m.kind.hash(&mut h);
|
||||
let swap = swapped && swaps_maps(it);
|
||||
let picture = |k: &str| swap && SWAPPED_MAPS.iter().any(|(p, _)| *p == k) && m.props.get(k).and_then(Value::as_str).is_some_and(|s| !s.starts_with("render:"));
|
||||
// a three.js shader's spec is its uniforms and its source, the one keyed and the other its identity
|
||||
if &*m.kind != "ThreeShaderMaterial" {
|
||||
hash_props(&m.props, &mut h, |k| !MAT_LIVE.contains(&k));
|
||||
hash_props(&m.props, &mut h, |k| !MAT_LIVE.contains(&k) && !picture(k));
|
||||
}
|
||||
for (p, _) in SWAPPED_MAPS.iter().filter(|(p, _)| picture(p)) {
|
||||
p.hash(&mut h);
|
||||
}
|
||||
}
|
||||
hash_props(&it.props, &mut h, |k| MESH_KEPT.contains(&k));
|
||||
@@ -147,7 +168,7 @@ pub fn spawn_sig(it: &Item) -> u64 {
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// Tracks cut where a part's kept inputs change: each run of frames with the same spawn_sig is a track of its own
|
||||
/// Tracks cut where a part's kept inputs change: each run of frames with the same spawn_sig (swapped maps left out) is a track of its own
|
||||
/// (`ID~1`, `ID~2` after the first), so a render's row never holds one frame's shape or words over another frame's.
|
||||
pub fn split_kept(tracks: Vec<(String, Vec<Option<Item>>)>) -> Vec<(String, Vec<Option<Item>>)> {
|
||||
let mut out = Vec::with_capacity(tracks.len());
|
||||
@@ -161,7 +182,8 @@ pub fn split_kept(tracks: Vec<(String, Vec<Option<Item>>)>) -> Vec<(String, Vec<
|
||||
let mut runs: Vec<(u64, Vec<Option<Item>>)> = Vec::new();
|
||||
for (i, slot) in track.into_iter().enumerate() {
|
||||
let Some(it) = slot else { continue };
|
||||
let s = spawn_sig(&it);
|
||||
// a render keys a swapped map's picture (SWAPPED_MAPS) rather than cutting for it
|
||||
let s = spawn_sig(&it, true);
|
||||
if runs.last().is_none_or(|(r, _)| *r != s) {
|
||||
runs.push((s, vec![None; n]));
|
||||
}
|
||||
@@ -197,7 +219,7 @@ pub struct KeptInputs {
|
||||
|
||||
impl KeptInputs {
|
||||
pub fn of(it: &Item) -> KeptInputs {
|
||||
KeptInputs { sig: spawn_sig(it), props: it.props.clone(), mat: it.material.as_ref().map(|m| m.props.clone()), shape: it.shape.clone() }
|
||||
KeptInputs { sig: spawn_sig(it, false), props: it.props.clone(), mat: it.material.as_ref().map(|m| m.props.clone()), shape: it.shape.clone() }
|
||||
}
|
||||
|
||||
/// Whether `it` has the kept inputs these were taken from; when it has, its props are held from now on.
|
||||
@@ -210,7 +232,7 @@ impl KeptInputs {
|
||||
if Arc::ptr_eq(&self.props, &it.props) && held(&self.mat, it.material.as_ref().map(|m| &m.props)) && self.shape == it.shape {
|
||||
return true;
|
||||
}
|
||||
if spawn_sig(it) != self.sig {
|
||||
if spawn_sig(it, false) != self.sig {
|
||||
return false;
|
||||
}
|
||||
*self = KeptInputs::of(it);
|
||||
|
||||
@@ -13,6 +13,8 @@ manifold-rust = "0.16.0"
|
||||
skrifa = "0.44"
|
||||
raea-core-fonts = { path = "../fonts" }
|
||||
serde_json = "1"
|
||||
# content names for kept BufferMesh text (buffer.rs kept_buffer)
|
||||
blake3 = "1.8"
|
||||
# blended distance fields and generators (trees, lofts, terrain, rosettes), meshed then closed into solids
|
||||
raea-core-sdf = { path = "../sdf" }
|
||||
raea-core-grow = { path = "../grow" }
|
||||
@@ -128,6 +128,42 @@ pub fn export_tris(t: &Tris, uvs: Option<&[[f32; 2]]>, path: &str, format: &str)
|
||||
Ok(bytes.len())
|
||||
}
|
||||
|
||||
/// A <BufferMesh>'s text from this long on is kept on disk and named by its content (kept_buffer).
|
||||
pub const KEEP_BUFFER_AT: usize = 1 << 16;
|
||||
|
||||
/// A long BufferMesh shape (`buffer:{json}`) as `buffer:@NAME`: its JSON written once to raea's caches
|
||||
/// (buffers/NAME.json, NAME its content's BLAKE3), so what holds the shape holds 40 characters
|
||||
/// (docs/render-memory.feature RM8). halcyon's palms were 263 MB of vertex arrays as text, held by the React scene,
|
||||
/// every frame's program row, the store and the evaluator: two of them 51 MB each. None for a short one, one already
|
||||
/// kept, or when the caches folder can't be written (the text then goes as it is).
|
||||
pub fn kept_buffer(expr: &str) -> Option<String> {
|
||||
let json = expr.strip_prefix("buffer:")?;
|
||||
if json.len() < KEEP_BUFFER_AT || json.starts_with('@') {
|
||||
return None;
|
||||
}
|
||||
let hex = blake3::hash(json.as_bytes()).to_hex();
|
||||
let name = &hex.as_str()[..32];
|
||||
let dir = crate::kept::caches()?.join("buffers");
|
||||
let p = dir.join(format!("{name}.json"));
|
||||
if !p.exists() {
|
||||
let part = dir.join(format!(".{name}.{}.part", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).ok()?;
|
||||
std::fs::write(&part, json).ok()?;
|
||||
std::fs::rename(&part, &p).ok()?;
|
||||
}
|
||||
Some(format!("buffer:@{name}"))
|
||||
}
|
||||
|
||||
/// A buffer shape's JSON (what follows `buffer:`): its own text, or the kept file `@NAME` names (kept_buffer).
|
||||
pub fn buffer_json(b: &str) -> Result<std::borrow::Cow<'_, str>, String> {
|
||||
let Some(name) = b.strip_prefix('@') else { return Ok(std::borrow::Cow::Borrowed(b)) };
|
||||
if name.len() != 32 || !name.bytes().all(|c| c.is_ascii_hexdigit()) {
|
||||
return Err(format!("buffer:@{name}: not a kept buffer's name"));
|
||||
}
|
||||
let p = crate::kept::caches().ok_or("no caches folder for a kept buffer")?.join("buffers").join(format!("{name}.json"));
|
||||
std::fs::read_to_string(&p).map(std::borrow::Cow::Owned).map_err(|e| format!("buffer:@{name}: {}: {e}", p.display()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -160,4 +196,16 @@ mod tests {
|
||||
assert_eq!((v.len(), i.len()), (18, 6));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_buffer_is_kept_by_its_content_and_read_back() {
|
||||
let pos: Vec<String> = (0..36000).map(|i| format!("{}", i % 7)).collect();
|
||||
let expr = format!("buffer:{{\"positions\": [{}]}}", pos.join(", "));
|
||||
assert!(expr.len() > KEEP_BUFFER_AT);
|
||||
let Some(k) = kept_buffer(&expr) else { return }; // no caches folder here: nothing to check
|
||||
assert!(k.starts_with("buffer:@") && k.len() == 8 + 32, "{k}");
|
||||
assert_eq!(kept_buffer(&expr).as_deref(), Some(k.as_str()), "the same text, the same name");
|
||||
assert_eq!(buffer_json(&k[7..]).unwrap(), &expr[7..]);
|
||||
assert!(kept_buffer("buffer:{\"positions\": [0, 0, 0]}").is_none(), "a short one stays as it is");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
//! A cache by key in two generations of at most `cap` bytes each, for what's costly to make and too big to keep all
|
||||
//! of: core/shape's meshes (`cached`) and runtime/calls' built Manifolds (docs/render-memory.feature). One asked for
|
||||
//! again moves to the newest generation and stays; one made and never asked for again goes a generation later, so two
|
||||
//! generations at most are held. An entry's weight is its holder's to say; its key counts too.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub struct Generations<V> {
|
||||
now: HashMap<String, (V, usize)>,
|
||||
old: HashMap<String, (V, usize)>,
|
||||
/// the newest generation's bytes
|
||||
bytes: usize,
|
||||
cap: usize,
|
||||
}
|
||||
|
||||
impl<V: Clone> Generations<V> {
|
||||
pub fn new(cap: usize) -> Self {
|
||||
Generations { now: HashMap::new(), old: HashMap::new(), bytes: 0, cap }
|
||||
}
|
||||
|
||||
/// What's held for `key`, in either generation: one from the older is held again in the newest.
|
||||
pub fn get(&mut self, key: &str) -> Option<V> {
|
||||
if let Some((v, _)) = self.now.get(key) {
|
||||
return Some(v.clone());
|
||||
}
|
||||
let (v, weight) = self.old.remove(key)?;
|
||||
self.hold(key, v.clone(), weight);
|
||||
Some(v)
|
||||
}
|
||||
|
||||
/// `v`, weighing `weight` bytes, held for `key` in the newest generation, which becomes the older one when it
|
||||
/// would pass the cap.
|
||||
pub fn hold(&mut self, key: &str, v: V, weight: usize) {
|
||||
let bytes = weight + key.len();
|
||||
if self.bytes + bytes > self.cap && !self.now.is_empty() {
|
||||
self.old = std::mem::take(&mut self.now);
|
||||
self.bytes = 0;
|
||||
}
|
||||
self.bytes += bytes;
|
||||
self.now.insert(key.to_string(), (v, weight));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn held_entries_go_a_generation_at_a_time_and_what_is_asked_again_stays() {
|
||||
// entries of a quarter of a generation each
|
||||
let mut g = Generations::new(4000);
|
||||
g.hold("kept", 1u8, 996);
|
||||
for i in 0..12 {
|
||||
g.hold(&format!("bar {i:02}"), 1u8, 994);
|
||||
assert!(g.get("kept").is_some(), "asked each time, it stays (after bar {i})");
|
||||
}
|
||||
assert!(g.get("bar 00").is_none(), "made once and never asked again, it went");
|
||||
assert!(g.now.len() + g.old.len() <= 8, "two generations at most: {} + {}", g.now.len(), g.old.len());
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ use std::path::PathBuf;
|
||||
|
||||
/// raea's caches folder, as raea-io-home names it (this crate is below it): ~/Library/Caches/raea on macOS,
|
||||
/// %LOCALAPPDATA%\raea\cache on Windows, $XDG_CACHE_HOME/raea or ~/.cache/raea elsewhere.
|
||||
fn caches() -> Option<PathBuf> {
|
||||
pub(crate) fn caches() -> Option<PathBuf> {
|
||||
let base = PathBuf::from(std::env::var_os(if cfg!(windows) { "LOCALAPPDATA" } else { "HOME" })?);
|
||||
if base.as_os_str().is_empty() {
|
||||
return None;
|
||||
|
||||
+12
-48
@@ -34,9 +34,12 @@ mod kept;
|
||||
mod mesh;
|
||||
mod parse;
|
||||
mod sphere;
|
||||
pub mod generations;
|
||||
|
||||
pub use generations::Generations;
|
||||
pub use sphere::{SphereOf, cuboid_of, cylinder_of, plane_of, sphere_of};
|
||||
|
||||
pub use buffer::{buffer_tris, export_tris};
|
||||
pub use buffer::{buffer_json, buffer_tris, export_tris, kept_buffer, KEEP_BUFFER_AT};
|
||||
pub use mesh::{export, from_mesh, read_glb, read_obj, to_mesh};
|
||||
|
||||
use std::collections::HashMap;
|
||||
@@ -211,47 +214,22 @@ const KEEP_MS: f64 = 2.0;
|
||||
/// and the end checks once more.
|
||||
const GEN_BYTES: usize = 16 << 20;
|
||||
|
||||
/// The shapes held, the newest generation and the one before, and the newest's bytes.
|
||||
#[derive(Default)]
|
||||
struct Held {
|
||||
now: HashMap<String, std::sync::Arc<Tris>>,
|
||||
old: HashMap<String, std::sync::Arc<Tris>>,
|
||||
bytes: usize,
|
||||
}
|
||||
|
||||
impl Held {
|
||||
fn get(&mut self, expr: &str) -> Option<std::sync::Arc<Tris>> {
|
||||
if let Some(t) = self.now.get(expr) {
|
||||
return Some(t.clone());
|
||||
}
|
||||
let t = self.old.remove(expr)?;
|
||||
self.hold(expr, &t);
|
||||
Some(t)
|
||||
}
|
||||
|
||||
/// `t` held for `expr` in the newest generation, which becomes the one before when it would pass GEN_BYTES.
|
||||
fn hold(&mut self, expr: &str, t: &std::sync::Arc<Tris>) {
|
||||
let bytes = (t.positions.len() + t.normals.len()) * 12 + expr.len();
|
||||
if self.bytes + bytes > GEN_BYTES && !self.now.is_empty() {
|
||||
self.old = std::mem::take(&mut self.now);
|
||||
self.bytes = 0;
|
||||
}
|
||||
self.bytes += bytes;
|
||||
self.now.insert(expr.to_string(), t.clone());
|
||||
}
|
||||
/// What a mesh weighs as it's held: its positions and normals.
|
||||
fn tris_bytes(t: &Tris) -> usize {
|
||||
(t.positions.len() + t.normals.len()) * 12
|
||||
}
|
||||
|
||||
/// The mesh for an expression, built once per expression (a re-cut or a key that doesn't change the shape costs nothing).
|
||||
pub fn cached(expr: &str) -> Result<std::sync::Arc<Tris>, String> {
|
||||
static CACHE: OnceLock<Mutex<Held>> = OnceLock::new();
|
||||
let cache = CACHE.get_or_init(Default::default);
|
||||
static CACHE: OnceLock<Mutex<Generations<std::sync::Arc<Tris>>>> = OnceLock::new();
|
||||
let cache = CACHE.get_or_init(|| Mutex::new(Generations::new(GEN_BYTES)));
|
||||
if let Some(t) = cache.lock().unwrap().get(expr) {
|
||||
return Ok(t);
|
||||
}
|
||||
// a buffer mesh's own triangles (buffer.rs): data already, so nothing is kept on disk for it
|
||||
if let Some(b) = expr.strip_prefix("buffer:") {
|
||||
let t = std::sync::Arc::new(buffer_tris(b)?.0);
|
||||
cache.lock().unwrap().hold(expr, &t);
|
||||
let t = std::sync::Arc::new(buffer_tris(&buffer_json(b)?)?.0);
|
||||
cache.lock().unwrap().hold(expr, t.clone(), tris_bytes(&t));
|
||||
return Ok(t);
|
||||
}
|
||||
// made by this build before, on disk (kept.rs): read back as it was written
|
||||
@@ -267,7 +245,7 @@ pub fn cached(expr: &str) -> Result<std::sync::Arc<Tris>, String> {
|
||||
t
|
||||
}
|
||||
};
|
||||
cache.lock().unwrap().hold(expr, &t);
|
||||
cache.lock().unwrap().hold(expr, t.clone(), tris_bytes(&t));
|
||||
Ok(t)
|
||||
}
|
||||
|
||||
@@ -275,20 +253,6 @@ pub fn cached(expr: &str) -> Result<std::sync::Arc<Tris>, String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn held_shapes_go_a_generation_at_a_time_and_what_is_asked_again_stays() {
|
||||
let mut h = Held::default();
|
||||
// a shape of a quarter of a generation
|
||||
let t = std::sync::Arc::new(Tris { positions: vec![[0.0; 3]; GEN_BYTES / 96], normals: vec![[0.0; 3]; GEN_BYTES / 96] });
|
||||
h.hold("kept", &t);
|
||||
for i in 0..12 {
|
||||
h.hold(&format!("bar {i}"), &t);
|
||||
assert!(h.get("kept").is_some(), "asked each time, it stays (after bar {i})");
|
||||
}
|
||||
assert!(h.get("bar 0").is_none(), "made once and never asked again, it went");
|
||||
assert!(h.now.len() + h.old.len() <= 8, "two generations at most: {} + {}", h.now.len(), h.old.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kept_mesh_reads_back_as_it_was_written() {
|
||||
let dir = std::env::temp_dir().join(format!("raea-shape-kept-{}", std::process::id()));
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "raea-core-tables"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "A row's per-frame tables: the column sets that change from frame to frame (a frame's look, the camera's post-processing, a light's), laid onto the row frame by frame"
|
||||
|
||||
[dependencies]
|
||||
raea-core-program = { path = "../program" }
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
|
||||
serde_json = "1"
|
||||
File renamed without changes.
@@ -0,0 +1,101 @@
|
||||
@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
|
||||
+2
-2
@@ -139,8 +139,8 @@ Feature: The Linux engine, as fast as it can be in the cloud
|
||||
Scenario: LX7. The clipping check never makes a render wait
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-contact | systems/contact/src/broad.rs | 160 | a broad phase before the voxels: parts whose boxes don't touch on a frame are never voxelized or tested; a part's voxels kept by its shape and scale, so an unchanged part is voxelized once a render |
|
||||
| raea-sys-contact | systems/contact/src/clip.rs | 178 | the frames checked on the cores the render leaves idle: Clipping takes each frame as it's drawn since SG4a (docs/stage-guards.feature), so off the render's thread |
|
||||
| raea-sys-clip | systems/clip/src/broad.rs | 160 | a broad phase before the voxels: parts whose boxes don't touch on a frame are never voxelized or tested; a part's voxels kept by its shape and scale, so an unchanged part is voxelized once a render |
|
||||
| raea-sys-clip | systems/clip/src/lib.rs | 178 | the frames checked on the cores the render leaves idle: Clipping takes each frame as it's drawn since SG4a (docs/stage-guards.feature), so off the render's thread. The clipping check moves here from raea-sys-contact's clip.rs (11-29: contact plus a broad phase would pass 2000 lines), using contact's deepest, Hit and solid cache as its public interface |
|
||||
Then edit.tsx's clipping check takes at most its frames' own time (from 96.1 s), and RR0's film's at most 300 ms
|
||||
And a render's wall with the check on is within 3% of RAEA_CLIP_CHECK=0
|
||||
And the findings are identical on the RR0 film, edit.tsx and the contact fixtures (systems/contact's tests)
|
||||
|
||||
+33
-1
@@ -260,7 +260,8 @@ Feature: Make: scenes, kits and shots built to a frozen plan and held to a revie
|
||||
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) and `open` (the brief's [TO CONFIRM] items)
|
||||
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
|
||||
@@ -286,6 +287,37 @@ Feature: Make: scenes, kits and shots built to a frozen plan and held to a revie
|
||||
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
|
||||
|
||||
@@ -66,7 +66,9 @@ 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, with no pixel size.
|
||||
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.
|
||||
- `ResizeObserver` calls back once when it starts observing, then after any layout that changed an observed element's
|
||||
size, with `contentRect`, `borderBoxSize` and `contentBoxSize`.
|
||||
|
||||
@@ -75,7 +77,6 @@ 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,7 +1,7 @@
|
||||
---
|
||||
title: "raea app"
|
||||
summary: "Run, check headless and package a desktop app written as one TSX file on @raea/ui."
|
||||
order: 7
|
||||
order: 8
|
||||
sources: ["engine/cli/src/cli.rs", "engine/rune/src/main.rs"]
|
||||
---
|
||||
|
||||
|
||||
@@ -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: 6
|
||||
order: 7
|
||||
sources: ["engine/cli/src/cli.rs", "runtime/bundle/src/lib.rs"]
|
||||
---
|
||||
|
||||
|
||||
@@ -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: 5
|
||||
order: 6
|
||||
sources: ["engine/cli/src/cli.rs"]
|
||||
---
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ 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. |
|
||||
|
||||
@@ -5,7 +5,7 @@ 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({...})` or `shot({...})` from
|
||||
`raea make status` reads the job on a project's brief.ts (`make: scene({...})`, `kit({...})`, `shot({...})`, `cut({...})` or `goal({...})` 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
|
||||
@@ -26,6 +26,24 @@ 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.
|
||||
|
||||
@@ -80,7 +98,8 @@ raea make lenschart counter_push
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
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 status [DIR] [--json] [--plan] (a scene, kit, shot, cut or goal held to its plan, `make` on brief.ts: what's missing, each gate (renders and checks, raea ask's calibrated questions, the critic on the kind's rubric), the judge's rounds, and whether it's done, decided in code; --plan writes the gates as check lines under the job's task in plan.org; the agent's Stop hook holds it there)
|
||||
raea make judge [DIR] [--by claude|kimi] (a goal job: a fresh critic, which only reads, judges each `says` rule; review/goal.judge.json)
|
||||
raea make plan [DIR] [--no-review] (the plan stop: review/plan/floor-plan.png, a grey-box blockout from the entrance and its review sheets, comparison.png beside reference 0)
|
||||
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)
|
||||
@@ -99,6 +118,7 @@ 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`). |
|
||||
|
||||
@@ -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] [--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)
|
||||
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)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
|
||||
@@ -21,10 +21,11 @@ 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 600. Instead of `--seconds`. |
|
||||
| `--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`. |
|
||||
| `--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. |
|
||||
|
||||
@@ -40,6 +41,16 @@ 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.
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
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,7 +1,7 @@
|
||||
---
|
||||
title: "raea run"
|
||||
summary: "Run a TypeScript program on the engine, headless, and print what it prints."
|
||||
order: 8
|
||||
order: 9
|
||||
sources: ["engine/cli/src/cli.rs"]
|
||||
---
|
||||
|
||||
|
||||
@@ -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] [--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)
|
||||
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)
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
@@ -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, kit } from "raea/brief"
|
||||
import { brief, cut, fingerprint, goal } from "raea/brief"
|
||||
```
|
||||
|
||||
`raea/brief` exports 9 functions, 40 types. Source: [sdk/raea/src/brief.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/brief.ts).
|
||||
`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).
|
||||
|
||||
## Functions
|
||||
|
||||
@@ -62,6 +62,16 @@ 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,
|
||||
@@ -243,10 +253,22 @@ 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"
|
||||
type MakeKind = "scene" | "kit" | "shot" | "cut" | "goal"
|
||||
```
|
||||
|
||||
### `MakeObject`
|
||||
|
||||
@@ -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. | 9 functions, 40 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/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
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,244 @@
|
||||
@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
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
@spec
|
||||
Feature: Render memory: a realistic set renders well under 16 GB
|
||||
Shane, 2026-11-26, as memguard's 24 GB cap killed the halcyon reel's shots one after another: "why are those renders
|
||||
so big... how do we keep them down?". Shots of a realistic set ran at 20.5-22.7 GB all morning, with no single
|
||||
regression: any small addition tipped one over the cap.
|
||||
|
||||
Why: raea's brand is local work on consumer hardware, a 16 GB Mac first. A render that needs 24 GB can't run there at
|
||||
all, and on a 64 GB machine it leaves no room for a second job.
|
||||
|
||||
The model this file sets:
|
||||
1. Memory is cut at the cause: a copy nobody reads after it was made is not made, or is let go once read. Nothing
|
||||
here changes what a frame looks like: every step is checked frame for frame against the binary before it.
|
||||
2. Every step is measured on the same probe, the halcyon reel's shot r109 (a walkway, a door, a bicycle; no pool
|
||||
water), as a still (frame 106) and as a sequence, with tools/memprobe (macOS `footprint` by category) and raea's
|
||||
own marks (RAEA_MEM_MARKS), on a binary built from the same tree with and without the step.
|
||||
3. The measures stay: RAEA_MEM_MARKS prints each world's meshes and images with the bytes they hold on the CPU and
|
||||
on the GPU, so a copy that comes back shows up as a number, not as a killed render.
|
||||
|
||||
Background:
|
||||
Given the halcyon motel project (~/Documents/raea/raea/projects/halcyon-motel, compositions/reel.tsx, shot-r109)
|
||||
And tools/memprobe/memprobe.sh (a still) and memseq.sh (a sequence), run under antsy with --mem 20G
|
||||
And the numbers of 11-26 on the 11-25 binary: the still peaks at 14.9 GB (malloc large 6.4, malloc small 4.3,
|
||||
graphics 3.9); the sequence opens its 3D at 10.3 GB of graphics and is killed at 24-25 GB before frame 0
|
||||
|
||||
Rule: the bar
|
||||
The r109 sequence peaks under 16 GB of footprint and the still under 9 GB, with the same frames as before.
|
||||
|
||||
@done
|
||||
Scenario: RM0. Each world's assets after every mark
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-memtally | systems/memtally/src/lib.rs | 140 | after each mark (raea-render's `mem_mark`) one `mem_assets` line per App: its main world's meshes, images and storage buffers with their CPU bytes, its render world's meshes and images with their GPU bytes |
|
||||
When a render runs with RAEA_MEM_MARKS=1
|
||||
Then each mark is followed, at each App's next update, by "mem_assets app N main: meshes M (K on the CPU) X MB,
|
||||
images ... MB, buffers ... MB" and "mem_assets app N render: meshes M X MB, images M Y MB"
|
||||
And the Apps are numbered in the order they opened, so a sequence that holds two 3D worlds shows two
|
||||
|
||||
@needs:RM0 @done
|
||||
Scenario: RM1. Meshes and maps on the GPU only, once nothing on the CPU reads them
|
||||
Then a mesh raea builds (systems/mesh, its indexed buffers, meshseq) and a material's maps (systems/material maps.rs)
|
||||
keep no main-world copy after they are uploaded, where nothing in the main world reads them after: their bounds
|
||||
are taken at spawn, and picking, the end checks' clipping, raea-sys-contact, LOD and Solari's traced copy are
|
||||
each checked to read what they need first
|
||||
And Solari's traced copy of a mesh is made from the CPU copy before that copy is let go, or the mesh is built in
|
||||
Solari's layout from the start so one mesh serves both (engine/render/raytrace/src/solari.rs traceable)
|
||||
And the mem_assets lines show the main world's image bytes near zero once the scene has settled (r109: 19.5 MB,
|
||||
9 of 87 images, all of them pictures raea-sys-sampler and the page read back)
|
||||
And a mesh raea builds keeps its main-world copy, because main-world systems read meshes after their first frame:
|
||||
picking (runtime/input pick.rs), a render's layers (systems/frame layer.rs), toon hulls (systems/material
|
||||
toon.rs), the screen's UVs, sprite3d, and the GI lane's emitters and cells (systems/rt). What it keeps is welded
|
||||
(RM7): r109's 618 meshes on the CPU hold 198 MB, where the 11-25 build's held 1.38 GB. Solari's traced copy
|
||||
(traceable's Copy) is on the GPU only
|
||||
|
||||
@needs:RM0 @done
|
||||
Scenario: RM2. One 3D world at a time in a sequence
|
||||
Then a render never holds two 3D engines at once: where a camera in a page element makes the 3D's rows be stepped
|
||||
again (runtime/export render.rs, fed.rs), the first engine is let go before the second opens
|
||||
And the mem_assets lines of a sequence show one 3D App's render world at a time (r109's sequence: app 0 alone)
|
||||
|
||||
@needs:RM0
|
||||
Scenario: RM3. The growth while a frame settles
|
||||
Then the CPU heap's growth while a held frame settles (about 350 MB/s, still and sequence alike) is found and cut
|
||||
And the still's footprint after its frame is written is within 10% of its footprint after warm-up
|
||||
|
||||
@needs:RM0
|
||||
Scenario: RM4. A texture whose path changes each frame is let go
|
||||
Then a texture a frame names (halcyon's pool: water/n-NN.png, g-NN.jpg, 96 of each) is let go, CPU and GPU, once
|
||||
no part shows it, so a sequence holds the frames in view and not every frame it passed
|
||||
And a pool shot's sequence (its caustics) holds as many textures at its last frame as at its first
|
||||
|
||||
# 11-26, later: Shane widened the goal ("reduce rendering memory footprint as much as possible ... no boiling and
|
||||
# amazing rendering realism ... the fastest, best looking, most efficient rendering engine for gametime performance
|
||||
# and film rendering performance"), the halcyon motel as the benchmark. The scenarios below RM4 carry it on; each is
|
||||
# measured on the same probes, and none may move the look or add boiling (raea light steady under 1.5%).
|
||||
|
||||
Rule: the measured state, 11-26 (r109, 1080x1920)
|
||||
| build | still peak | sequence peak | main-world maps | main-world meshes |
|
||||
| 11-25 frozen | 14.9 GB | killed at 24-25 GB before frame 0 | 2.4 GB | 1.38 GB |
|
||||
| RM1 | 14.6 GB | 16.1 GB, all 107 frames written | 0.02 GB | 0.56 GB |
|
||||
| RM1+RM5+RM6 | | 11.4 GB; 93 images (was 277), GPU 3.7 GB (was 5.5) | 0.02 GB | |
|
||||
| + RM7 weld, shape text out of the store | | 10.2 GB (footprint 7.1 GB), 0 errors | 0.02 GB | 0.20 GB (618 of 1226 meshes) |
|
||||
| + RM8 kept buffers | | 8.8 GB (footprint 6.7 GB), 0 errors; shape text 11.8 MB (was 274) | 0.02 GB | 0.20 GB |
|
||||
| + RM9 BC7 maps | | 8.4 GB (footprint 5.7 GB), 0 errors; GPU images 282 MB (was 733) | 0.02 GB | 0.20 GB |
|
||||
| + RM10 contact solids | | 7.8 GB (footprint 5.5 GB), 0 errors, the same findings | 0.02 GB | 0.20 GB |
|
||||
The pool's caustics shot (196 frames), from before RM6 to the weld build: peak 18.8 GB to 9.9 GB, every 8th frame
|
||||
within run-to-run noise (pixels off by more than 2 levels 0.2-1.5%, by more than 16 at most 0.03%; this tree's
|
||||
noise between two runs of one binary is about 1%).
|
||||
The weld against RAEA_NO_WELD=1 on one binary (r109 f106): a frame held 96 frames (`raea light steady`) settles to
|
||||
the same picture either way (pixels off by more than 16 levels 0.008%), boiling 0.30% welded against 0.38%
|
||||
(worst tile 1.53% against 2.98%), and two runs of the welded build differ in 0.11% of pixels against 1.2%. In the
|
||||
shot's own render, one small emitter's wash (the room sconce's light on the wall, above and below its can) has
|
||||
built up less by f106 when welded: a difference in how fast it settles, not in where it settles.
|
||||
RM9 against RAEA_NO_BC=1 on one binary (r109 f106, caustics f60, the facade's 8776-wide wear maps and the pool's
|
||||
96 water normal maps among them): pixels off by more than 16 levels 0.057% and 0.097%, all of it the bicycle's
|
||||
sub-pixel spokes' glints and a chair's shadow edge on the deck; nothing on the facade or the water (two runs of
|
||||
either build: about 0.03%).
|
||||
Still held after the weld (before RM8): shape text 274 MB in 2,526 rows, 263 MB of it 88 BufferMesh shapes (the palms' vertex
|
||||
arrays as JSON, two of them 51 MB each), half of it the same text in another row (RM8).
|
||||
|
||||
@needs:RM1 @done
|
||||
Scenario: RM5. The CPU heap, named by who holds it
|
||||
Then a still's live heap after warm-up is attributed by call tree (macOS malloc stack logging, malloc_history
|
||||
-callTree; tools/memprobe/heapwho.sh) to the crate that allocated it, and each holder over 250 MB is either cut,
|
||||
let go once read, or written here with why it stays
|
||||
And the shape cache (raea-core-shape `cached`, `solid`), the React world, wgpu's staging and the end checks' solids
|
||||
are each given a number
|
||||
And after RM5 to RM10 (tools/memprobe/heapseq.sh, r109's sequence mid-render; holders.py) what is over 250 MB stays
|
||||
for a reason: MetalFX's denoising scaler 317 MB (Apple's framework, made once a view, the denoiser's own
|
||||
working memory); JavaScriptCore's heap 300 MB in a still, up to 870 MB mid-sequence (the composition's live
|
||||
objects; collecting after every frame, RAEA_JSC_EDEN=1, frees the small heap later but not the peak); the
|
||||
contact check's solids 366 MB (RM10, every part in view the whole shot); wgpu's Metal command encoding
|
||||
250-360 MB in the first frames (inside wgpu-hal). Gone from the list: Manifold's solids (2.4 GB, RM5's cache),
|
||||
the shape text (977 MB of clones, RM8 and the store), the names cache (297 MB, RM8)
|
||||
|
||||
@needs:RM4
|
||||
Scenario: RM6. A picture sequence is one texture, streamed
|
||||
Then a map whose picture changes each frame (a water normal map, a caustic) is one GPU texture written each frame
|
||||
from the frame's file (decoded ahead on a thread), not one texture per picture made at load
|
||||
And a pool shot's sequence holds one texture per such map, its GPU bytes flat from its first frame to its last
|
||||
|
||||
@needs:RM1 @done
|
||||
Scenario: RM7. A mesh as few vertices as its corners need
|
||||
Then a Manifold shape's mesh is indexed (U32) and welded where corners share a place and a normal exactly
|
||||
(systems/mesh welded): halcyon's shapes had 4.65 corners to each vertex, so the raster mesh, its main-world copy
|
||||
and Solari's traced copy are each about a third of what they were (r109's main-world meshes 0.56 GB to 0.20 GB)
|
||||
And a shape with its own UVs or colours a corner (a <BufferMesh>) is left as it is; RAEA_NO_WELD=1 is the control
|
||||
And a frame held 96 frames settles to the same picture welded or not, with no more boiling (numbers above)
|
||||
And it is not built in Solari's layout to spare the traced copy: the main-world copy stays (RM1's readers), so
|
||||
the layout's tangents and colours would make every vertex 64 bytes on the CPU and the GPU, where today it is 32
|
||||
on the CPU and 32 + 64 on the GPU: bytes moved from the GPU to the CPU, not saved
|
||||
|
||||
@needs:RM7 @done
|
||||
Scenario: RM8. A long BufferMesh is held as a name, its text kept on disk by its content
|
||||
Given a <BufferMesh> whose shape text is 64 KB or longer (raea-core-shape KEEP_BUFFER_AT)
|
||||
Then the React read (runtime/react read.rs names3d) writes its JSON once to raea's caches (buffers/NAME.json, NAME
|
||||
its BLAKE3) and passes `buffer:@NAME` on, so the scene, every frame's row, the store and the evaluator hold 40
|
||||
characters, not the vertex arrays
|
||||
And the part is known again each frame by the text's length and xxh3 without naming it again
|
||||
And every reader of a buffer shape (raea-sys-mesh shape_mesh, the three shader's fit, interchange's export) reads
|
||||
the kept file through raea_core_shape::buffer_json, so what is drawn and exported is the same
|
||||
|
||||
@needs:RM1 @done
|
||||
Scenario: RM9. A material's maps are block-compressed on the GPU
|
||||
Given a device that samples BC textures (wgpu TEXTURE_COMPRESSION_BC: Apple silicon and Intel Macs, and desktop
|
||||
GPUs on Windows and Linux)
|
||||
Then every map raea-sys-material makes (map_image: colour as BC7 sRGB, normal, metallic-roughness, occlusion and
|
||||
emissive as BC7 linear) is BC7 with its whole mip chain, 16 bytes for each 4x4 texels, a quarter of RGBA8's
|
||||
And the blocks are encoded once (intel_tex_2's ISPC kernels, on every core) and kept in raea's caches by the
|
||||
picture's content (maps/NAME.bc7), so a later run reads them and makes no mips
|
||||
And a map whose side isn't a multiple of 4, a device without BC, or RAEA_NO_BC=1 is RGBA8 as before
|
||||
And BC7 keeps all four channels, so Bevy's and Solari's shaders read every map as they did
|
||||
|
||||
@done
|
||||
Scenario: RM10. The contact check's solids hold what it reads
|
||||
Given a sequence's parts are checked for clipping as its frames come (raea-sys-contact), every part in view held
|
||||
as a solid until the end checks let them go: in r109, 603 MB of depth grids, 368 MB of inside-cell lists and 301
|
||||
MB of surface points (the heap's biggest holder mid-render, by malloc stack logging)
|
||||
Then a cell's depth is a byte (at most half a grid's side; held at 255 past it), the inside cells are a count
|
||||
(the check reads only how many), and the surface points are three u16s across the part's box with no spare
|
||||
capacity: about 366 MB where there were 1,272, the findings the same (the crate's 18 tests)
|
||||
|
||||
Still open (11-26): a transient 1 GB of heap inside the first frame (after "resources prepared", gone within 10 s)
|
||||
sets the warm sequence's footprint peak (6.5 GB at about 49 s); JavaScriptCore collecting after every frame
|
||||
(RAEA_JSC_EDEN=1, RAEA_JSC_RELEASE_S=1) flattens the small heap later (990 to 330 MB) but not that peak. The GPU's
|
||||
2.6 GB: 282 MB of images, 455 MB of meshes, the rest Solari's and the views' own buffers and MetalFX.
|
||||
|
||||
Rule: speed and quality are measured beside memory
|
||||
Each step reports, on the r109 still and sequence: peak footprint, seconds per frame once warm, and `raea light
|
||||
steady` boiling at a held frame. A step that cuts memory and costs time or adds boiling is not done.
|
||||
@@ -20,6 +20,8 @@ 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"] }
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
//! 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");
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ 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;
|
||||
@@ -41,6 +42,10 @@ 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.
|
||||
@@ -61,6 +66,7 @@ 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 {
|
||||
@@ -84,6 +90,9 @@ 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));
|
||||
}
|
||||
@@ -320,7 +329,7 @@ pub mod ffi {
|
||||
1
|
||||
}
|
||||
|
||||
/// `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
|
||||
/// `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
|
||||
/// be freed with raea_bundle_free
|
||||
///
|
||||
/// # Safety
|
||||
@@ -344,7 +353,8 @@ 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 o = super::Options { z3: opts["z3"].as_bool().unwrap_or(false), script, defines, edit, stamps: opts["stamps"].as_bool().unwrap_or(false) };
|
||||
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 };
|
||||
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}),
|
||||
|
||||
@@ -23,7 +23,8 @@ pub struct Script {
|
||||
pub motion: PathBuf,
|
||||
/// sdk/shell/src/index.ts
|
||||
pub shell: PathBuf,
|
||||
/// `--alias SPEC=PATH`
|
||||
/// `--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
|
||||
pub aliases: HashMap<String, PathBuf>,
|
||||
/// `--node-stub a,b`
|
||||
pub stubs: Vec<String>,
|
||||
@@ -36,8 +37,9 @@ 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.
|
||||
const MEDIA: &[&str] = &["mp4", "mov", "m4v", "mp3", "wav", "m4a", "png", "jpg", "webp", "gif", "glb", "gltf"];
|
||||
/// 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"];
|
||||
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -46,7 +48,12 @@ 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>> {
|
||||
let importer = self.0.js.join("_raea.js");
|
||||
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 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()))),
|
||||
@@ -84,6 +91,9 @@ 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)),
|
||||
|
||||
@@ -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 };
|
||||
let o = raea_bundle::Options { z3: false, script: Some(script.clone()), defines: vec![("FLAG".into(), "\"ON\"".into())], edit: None, stamps: false, ..Default::default() };
|
||||
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 }).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, ..Default::default() }).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);
|
||||
}
|
||||
|
||||
@@ -85,6 +85,8 @@ 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"] }
|
||||
|
||||
@@ -110,3 +110,75 @@ 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"]);
|
||||
});
|
||||
});
|
||||
@@ -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] [--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)");
|
||||
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)");
|
||||
// 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 {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));
|
||||
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));
|
||||
}
|
||||
// `--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.first().map(String::as_str) == Some("export-game") {
|
||||
return raea_app_game::export(args);
|
||||
}
|
||||
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); }
|
||||
// `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)
|
||||
|
||||
@@ -416,6 +416,8 @@ 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":
|
||||
@@ -445,3 +447,15 @@ 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}` };
|
||||
}
|
||||
|
||||
+38
-7
@@ -23,10 +23,18 @@ 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). P: Workspace/id (ids as raea workspace --json
|
||||
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
|
||||
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
|
||||
@@ -50,8 +58,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(["--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"]);
|
||||
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"]);
|
||||
|
||||
/** 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. */
|
||||
@@ -84,6 +92,8 @@ 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);
|
||||
@@ -95,7 +105,19 @@ 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 files = args.filter((a, i) => !a.startsWith("--") && !WITH_VALUE.has(args[i - 1] ?? "") && args[i - 2] !== "--despite").map(abs);
|
||||
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 despite = args.flatMap((a, i) => {
|
||||
if (a !== "--despite") return [];
|
||||
const [check, why] = [args[i + 1], args[i + 2]];
|
||||
@@ -134,7 +156,8 @@ 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}`);
|
||||
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") };
|
||||
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") };
|
||||
}
|
||||
|
||||
/** A --labels file's labels, as feed_post takes them: a list, or { "labels": [...] } (raea media sheet's OUT.labels.json). */
|
||||
@@ -189,7 +212,13 @@ 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;
|
||||
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
|
||||
// --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
|
||||
| { 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`;
|
||||
@@ -213,7 +242,9 @@ 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,
|
||||
`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.`,
|
||||
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.`,
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
@@ -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_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_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] {
|
||||
assert!(help.contains(usage), "{usage}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,8 +17,6 @@ raea-sys-hold = { path = "../../systems/hold" }
|
||||
# the passes, each a crate of its own (systems/)
|
||||
raea-sys-splat = { path = "../../systems/splat" }
|
||||
raea-sys-sprite = { path = "../../systems/sprite" }
|
||||
raea-sys-rt = { path = "../../systems/rt" }
|
||||
raea-sys-gi = { path = "../../systems/gi" }
|
||||
# soft shadows (experimental_pbr_pcss) are under the native feature with raea-runtime-scene3d/pcss: WebGPU refuses their sampling
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "multi_threaded", "3d_bevy_render", "ui_bevy_render", "png", "tonemapping_luts", "ktx2", "zstd_rust"] }
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "hdr"] }
|
||||
@@ -38,27 +36,22 @@ raea-sys-matchmove = { path = "../../systems/matchmove" }
|
||||
raea-sys-grid = { path = "../../systems/grid" }
|
||||
# the view a camera on the Engine's target draws: the frame above its tag row, or a page's box (#130)
|
||||
raea-sys-viewbox = { path = "../../systems/viewbox" }
|
||||
raea-sys-rendermap = { path = "../../systems/rendermap" }
|
||||
raea-sys-meshseq = { path = "../../systems/meshseq" }
|
||||
raea-sys-environment = { path = "../../systems/environment" }
|
||||
raea-sys-look = { path = "../../systems/look" }
|
||||
raea-sys-compose = { path = "../../systems/compose" }
|
||||
raea-sys-material = { path = "../../systems/material" }
|
||||
raea-sys-framepass = { path = "../../systems/framepass" }
|
||||
raea-sys-compute = { path = "../../systems/compute" }
|
||||
raea-sys-phase = { path = "../../systems/phase" }
|
||||
raea-sys-sampler = { path = "../../systems/sampler" }
|
||||
raea-sys-parity = { path = "../../systems/parity" }
|
||||
raea-sys-toon = { path = "../../systems/toon" }
|
||||
# raea's modules as Bevy plugins (RaeaPlugins), a crate of their own
|
||||
raea-render-plugins = { path = "plugins" }
|
||||
raea-sys-memtally = { path = "../../systems/memtally" }
|
||||
raea-sys-shader = { path = "../../systems/shader" }
|
||||
# three.js's shaders: a ShaderMaterial's GLSL and a node material's WGSL (docs/r3f.feature R3F11)
|
||||
raea-sys-three-shader = { path = "../../systems/three-shader" }
|
||||
raea-sys-post = { path = "../../systems/post" }
|
||||
raea-sys-fog = { path = "../../systems/fog" }
|
||||
raea-sys-fog-half = { path = "../../systems/fog-half" }
|
||||
raea-sys-volume = { path = "../../systems/volume" }
|
||||
# a field of grass made in tiles by distance (<Grass>)
|
||||
raea-sys-grass = { path = "../../systems/grass" }
|
||||
raea-sys-lod = { path = "../../systems/lod" }
|
||||
serde_json = { version = "1", features = ["float_roundtrip"] }
|
||||
# the direct render's views, the 2D rows, clips' masks and the paint device (runtime/view)
|
||||
raea-runtime-view = { path = "../../runtime/view", optional = true }
|
||||
@@ -104,8 +97,3 @@ network = ["native"]
|
||||
bevy-all = ["bevy/bevy_gilrs", "bevy/gamepad", "bevy/area_light_luts", "bevy/experimental_pbr_pcss", "bevy/dfg_lut", "bevy/smaa_luts", "bevy/tonemapping_luts", "bevy/bluenoise_texture", "bevy/bevy_gizmos", "bevy/bevy_gizmos_render", "bevy/bevy_dev_tools", "bevy/debug", "bevy/bevy_ui_debug", "bevy/file_watcher", "bevy/embedded_watcher", "bevy/asset_processor", "bevy/png", "bevy/jpeg", "bevy/ktx2", "bevy/zstd_rust", "bevy/basis-universal", "bevy/exr", "bevy/hdr", "bevy/webp", "bevy/dds", "bevy/tga", "bevy/bmp", "bevy/gif", "bevy/ico", "bevy/qoi", "bevy/pnm", "bevy/tiff", "bevy/picking", "bevy/bevy_picking", "bevy/mesh_picking", "bevy/sprite_picking", "bevy/ui_picking", "bevy/meshlet", "bevy/meshlet_processor", "bevy/bevy_solari", "bevy/bevy_animation", "bevy/gltf_animation", "bevy/morph", "bevy/morph_animation", "bevy/bevy_gltf", "bevy/bevy_sprite", "bevy/bevy_sprite_render", "bevy/2d_bevy_render", "bevy/3d_bevy_render", "bevy/ui_bevy_render", "bevy/bevy_ui_widgets", "bevy/bevy_feathers", "bevy/custom_cursor", "bevy/bevy_input_focus", "bevy/bevy_camera_controller", "bevy/free_camera", "bevy/pan_camera", "bevy/bevy_text", "bevy/system_font_discovery", "bevy/scene", "bevy/bevy_state", "bevy/serialize", "bevy/reflect_functions", "bevy/reflect_documentation", "bevy/sysinfo_plugin", "bevy/bevy_clipboard", "bevy/system_clipboard", "bevy/clipboard_image", "bevy/ghost_nodes", "bevy/bevy_settings", "bevy/shader_format_spirv", "bevy/bevy_debug_stepping", "bevy/bevy_world_serialization", "bevy/bevy_audio", "bevy/mp3", "bevy/flac", "bevy/vorbis", "bevy/wav", "bevy/aac", "bevy/mp4", "bevy/http", "bevy/https", "bevy/web_asset_cache", "bevy/bevy_curve", "bevy/complex_script_segmentation", "bevy/compressed_image_saver_universal", "bevy/pan_orbit_camera", "bevy/pan_orbit_gizmo", "bevy/render_dev_tools"]
|
||||
# per-system spans as a chrome trace (RUST_LOG=info, trace-*.json in the working directory)
|
||||
trace = ["bevy/trace", "bevy/trace_chrome"]
|
||||
|
||||
[package.metadata.cargo-shear]
|
||||
# raea-core-shape is unused since a mesh row's shape went to raea_sys_material::mesh::shape_mesh. Its line sits beside
|
||||
# an unlanded branch's (scene-loop: raea-sys-procmat), so it goes, with this table, once that branch lands
|
||||
ignored = ["raea-core-shape"]
|
||||
@@ -0,0 +1,42 @@
|
||||
[package]
|
||||
name = "raea-render-plugins"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "raea's Engine as Bevy plugins (docs/sdk.feature S6a): RaeaPlugins, each module's install as a Plugin in Engine::new's order, so any Bevy App can draw raea's looks"
|
||||
|
||||
[dependencies]
|
||||
raea-core-program = { path = "../../../core/program" }
|
||||
raea-runtime-plugins = { path = "../../../runtime/plugins" }
|
||||
raea-runtime-scene3d = { path = "../../../runtime/scene3d" }
|
||||
raea-sys-compose = { path = "../../../systems/compose" }
|
||||
raea-sys-environment = { path = "../../../systems/environment" }
|
||||
raea-sys-fog = { path = "../../../systems/fog" }
|
||||
raea-sys-fog-half = { path = "../../../systems/fog-half" }
|
||||
raea-sys-frame = { path = "../../../systems/frame" }
|
||||
raea-sys-grid = { path = "../../../systems/grid" }
|
||||
raea-sys-look = { path = "../../../systems/look" }
|
||||
raea-sys-material = { path = "../../../systems/material" }
|
||||
raea-sys-meshseq = { path = "../../../systems/meshseq" }
|
||||
raea-sys-post = { path = "../../../systems/post" }
|
||||
raea-sys-screen = { path = "../../../systems/screen" }
|
||||
raea-sys-shader = { path = "../../../systems/shader" }
|
||||
raea-sys-splat = { path = "../../../systems/splat" }
|
||||
raea-sys-sprite = { path = "../../../systems/sprite" }
|
||||
raea-sys-text3d = { path = "../../../systems/text3d" }
|
||||
raea-sys-toon = { path = "../../../systems/toon" }
|
||||
raea-sys-volume = { path = "../../../systems/volume" }
|
||||
raea-sys-procmat = { path = "../../../systems/procmat" }
|
||||
raea-sys-rt = { path = "../../../systems/rt" }
|
||||
raea-sys-gi = { path = "../../../systems/gi" }
|
||||
raea-sys-grass = { path = "../../../systems/grass" }
|
||||
raea-sys-lod = { path = "../../../systems/lod" }
|
||||
raea-sys-three-shader = { path = "../../../systems/three-shader" }
|
||||
raea-sys-framepass = { path = "../../../systems/framepass" }
|
||||
raea-sys-compute = { path = "../../../systems/compute" }
|
||||
raea-sys-phase = { path = "../../../systems/phase" }
|
||||
raea-sys-parity = { path = "../../../systems/parity" }
|
||||
raea-sys-rendermap = { path = "../../../systems/rendermap" }
|
||||
raea-sys-sampler = { path = "../../../systems/sampler" }
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render"] }
|
||||
@@ -14,6 +14,27 @@ use bevy::prelude::*;
|
||||
// the frame's system sets, raea-sys-frame's: a plugin orders its systems by them
|
||||
pub use raea_sys_frame::{FrameSystems, Scene3dSystems};
|
||||
|
||||
// raea's modules, by the names Engine::new installs them under (raea-render's engine.rs)
|
||||
use raea_runtime_plugins as plugins;
|
||||
use raea_runtime_scene3d as scene3d;
|
||||
use raea_sys_compose::{compose, passes};
|
||||
use raea_sys_environment as environment;
|
||||
use raea_sys_fog::{fire, froxel, froxel_glass};
|
||||
use raea_sys_fog_half as fog_half;
|
||||
use raea_sys_frame::bevy_api;
|
||||
use raea_sys_grid as grid;
|
||||
use raea_sys_look::{look, paint};
|
||||
use raea_sys_material::{decal, shadow_catch, shadow_only};
|
||||
use raea_sys_meshseq as meshseq;
|
||||
use raea_sys_post::{cut, dof, effect_stack, lens, motion_blur, outline};
|
||||
use raea_sys_screen as screen;
|
||||
use raea_sys_shader as shader_ext;
|
||||
use raea_sys_splat as splat;
|
||||
use raea_sys_sprite as sprite2d;
|
||||
use raea_sys_text3d as text3d;
|
||||
use raea_sys_toon as toon;
|
||||
use raea_sys_volume as volume;
|
||||
|
||||
macro_rules! raea_plugin {
|
||||
($($name:ident: $install:path, $doc:literal;)*) => {
|
||||
$(
|
||||
@@ -37,46 +58,46 @@ macro_rules! raea_plugin {
|
||||
}
|
||||
|
||||
raea_plugin! {
|
||||
VolumetricFogPlugin: super::scene3d::install_fog_shader, "Volumetric fog's shader, its dither seeded from the film frame (scene3d.rs).";
|
||||
DepthOfFieldPlugin: super::dof::install, "Bevy's depth of field, keeping the frame's alpha (dof.rs).";
|
||||
EffectStackPlugin: super::effect_stack::install, "The effect stack (a <Grade>'s aberration and vignette), keeping alpha (effect_stack.rs).";
|
||||
Bevy019DefaultsPlugin: super::bevy_api::install_0_19_defaults, "Bevy 0.19's tone curve \"none\" and screen-space transmission, which 0.20 changed (bevy_api.rs).";
|
||||
HalfFogPlugin: super::fog_half::install, "Volumetric fog at a fraction of the frame's resolution, upsampled by depth (fog_half.rs).";
|
||||
EnvironmentPlugin: super::environment::install, "Each panorama's light filtered once (environment.rs).";
|
||||
FroxelFogPlugin: super::froxel::install, "Fog as one medium in a grid along the view (froxel.rs).";
|
||||
FroxelGlassPlugin: super::froxel_glass::install, "Glass seen through froxel fog (froxel_glass.rs).";
|
||||
LookPlugin: super::look::install, "Models drawn as pixel art or the site's grain (look.rs).";
|
||||
OutlinePlugin: super::outline::install, "Ink outlines (outline.rs).";
|
||||
VolumetricFogPlugin: crate::scene3d::install_fog_shader, "Volumetric fog's shader, its dither seeded from the film frame (scene3d.rs).";
|
||||
DepthOfFieldPlugin: crate::dof::install, "Bevy's depth of field, keeping the frame's alpha (dof.rs).";
|
||||
EffectStackPlugin: crate::effect_stack::install, "The effect stack (a <Grade>'s aberration and vignette), keeping alpha (effect_stack.rs).";
|
||||
Bevy019DefaultsPlugin: crate::bevy_api::install_0_19_defaults, "Bevy 0.19's tone curve \"none\" and screen-space transmission, which 0.20 changed (bevy_api.rs).";
|
||||
HalfFogPlugin: crate::fog_half::install, "Volumetric fog at a fraction of the frame's resolution, upsampled by depth (fog_half.rs).";
|
||||
EnvironmentPlugin: crate::environment::install, "Each panorama's light filtered once (environment.rs).";
|
||||
FroxelFogPlugin: crate::froxel::install, "Fog as one medium in a grid along the view (froxel.rs).";
|
||||
FroxelGlassPlugin: crate::froxel_glass::install, "Glass seen through froxel fog (froxel_glass.rs).";
|
||||
LookPlugin: crate::look::install, "Models drawn as pixel art or the site's grain (look.rs).";
|
||||
OutlinePlugin: crate::outline::install, "Ink outlines (outline.rs).";
|
||||
SteadyPlugin: raea_sys_post::steady::install, "raea's temporal filter: each frame jittered and blended with those before it (raea-sys-post steady.rs, docs/realism.feature LT12).";
|
||||
ComposePlugin: super::compose::install, "Composition passes: each object's pass mask, read by Look, Outline, Bloom and Grade (compose.rs).";
|
||||
Text3dPlugin: super::text3d::install, "Text in the 3D world: bevy_rich_text3d and its faces (raea-sys-text3d).";
|
||||
FirePlugin: super::fire::install, "Flames drawn as volumes (fire.rs).";
|
||||
SplatPlugin: super::splat::install, "Gaussian splats, sorted per frame for the scene camera (raea-sys-splat).";
|
||||
MeshSequencePlugin: super::meshseq::install, "Mesh sequences by the frame, glitches on parts (meshseq.rs).";
|
||||
ComposePlugin: crate::compose::install, "Composition passes: each object's pass mask, read by Look, Outline, Bloom and Grade (compose.rs).";
|
||||
Text3dPlugin: crate::text3d::install, "Text in the 3D world: bevy_rich_text3d and its faces (raea-sys-text3d).";
|
||||
FirePlugin: crate::fire::install, "Flames drawn as volumes (fire.rs).";
|
||||
SplatPlugin: crate::splat::install, "Gaussian splats, sorted per frame for the scene camera (raea-sys-splat).";
|
||||
MeshSequencePlugin: crate::meshseq::install, "Mesh sequences by the frame, glitches on parts (meshseq.rs).";
|
||||
Draws2dPlugin: raea_sys_sprite::install, "Plugins' 2D drawing brings up the scene's 2D camera (raea-sys-sprite's Draws2d).";
|
||||
ScreenPlugin: super::screen::install, "Live pictures on surfaces, drawn as CRTs (screen.rs).";
|
||||
GridPlugin: super::grid::install, "Greybox surfaces: graph paper and outlines (grid.rs).";
|
||||
ScreenPlugin: crate::screen::install, "Live pictures on surfaces, drawn as CRTs (screen.rs).";
|
||||
GridPlugin: crate::grid::install, "Greybox surfaces: graph paper and outlines (grid.rs).";
|
||||
ProcMatPlugin: raea_sys_procmat::install, "Procedural surfaces: wood, stone, brick, tiles and the rest, with dust and dirt (systems/procmat).";
|
||||
PaintPlugin: super::paint::install, "The paint and cartoon looks' surfaces (paint.rs).";
|
||||
PassesPlugin: super::passes::install, "Render passes per view (passes.rs).";
|
||||
PaintPlugin: crate::paint::install, "The paint and cartoon looks' surfaces (paint.rs).";
|
||||
PassesPlugin: crate::passes::install, "Render passes per view (passes.rs).";
|
||||
TracedAoPlugin: raea_sys_rt::passes, "Traced passes: ambient occlusion, raealism's world probes and the sun's far shadow map (raea-sys-rt).";
|
||||
GiScreenPlugin: raea_sys_gi::install, "raealism's light on screen: each pixel's indirect diffuse from the world cache, read by the main pass (raea-sys-gi, RAEA_GI=1).";
|
||||
VolumePlugin: super::volume::install, "Simulated smoke, clouds and contrails, raymarched (volume.rs).";
|
||||
VolumePlugin: crate::volume::install, "Simulated smoke, clouds and contrails, raymarched (volume.rs).";
|
||||
GrassPlugin: raea_sys_grass::install, "Fields of grass, made in tiles as detailed as the camera's distance asks (systems/grass).";
|
||||
DetailPlugin: raea_sys_lod::install, "Where each part is drawn: levels by distance or size on screen, cross-faded, draw distance and shadows left to a coarser level (raea-sys-lod, docs/realism.feature LT21).";
|
||||
ShadowOnlyPlugin: super::shadow_only::install, "Meshes in the shadow maps only (shadow_only.rs).";
|
||||
ShadowCatchPlugin: super::shadow_catch::install, "Surfaces that show only the shadows falling on them (shadow_catch.rs).";
|
||||
ShadowOnlyPlugin: crate::shadow_only::install, "Meshes in the shadow maps only (shadow_only.rs).";
|
||||
ShadowCatchPlugin: crate::shadow_catch::install, "Surfaces that show only the shadows falling on them (shadow_catch.rs).";
|
||||
TintPlugin: raea_sys_material::tint::install, "A colour a copy over an <Instances>' surface, three's instanceColor (tint.rs).";
|
||||
ToonPlugin: super::toon::install, "The toon surface and its ink outline's materials (toon.rs).";
|
||||
ShaderExtPlugin: super::shader_ext::install, "Shaders written in TypeScript over the lit standard surface (raea-sys-shader).";
|
||||
ToonPlugin: crate::toon::install, "The toon surface and its ink outline's materials (toon.rs).";
|
||||
ShaderExtPlugin: crate::shader_ext::install, "Shaders written in TypeScript over the lit standard surface (raea-sys-shader).";
|
||||
ThreeShaderPlugin: raea_sys_three_shader::install, "three.js's shaders: a ShaderMaterial's GLSL (naga) and a node material's WGSL, with three's built-ins (raea-sys-three-shader).";
|
||||
FramePassPlugin: raea_sys_framepass::install, "Full-screen passes written in TypeScript (raea-sys-framepass).";
|
||||
ComputePlugin: raea_sys_compute::install, "Compute shaders written in TypeScript, run before the cameras draw (raea-sys-compute).";
|
||||
PhaseItemPlugin: raea_sys_phase::install, "Your own draws in a camera's opaque phase, as Bevy's custom_phase_item queues one (raea-sys-phase).";
|
||||
LensPlugin: super::lens::install, "The camera's lens (Fisheye, LensDistortion), after tone mapping (lens.rs).";
|
||||
LensPlugin: crate::lens::install, "The camera's lens (Fisheye, LensDistortion), after tone mapping (lens.rs).";
|
||||
ParityPlugin: raea_sys_parity::install, "The parity probe: a frame's cost and World, written when RAEA_PARITY is set (raea-sys-parity, docs/control.feature FC0a).";
|
||||
CameraCutPlugin: super::cut::install, "A camera that jumps is a cut: its history starts again and its motion blur waits (cut.rs, RT31).";
|
||||
MotionBlurPlugin: super::motion_blur::install, "Motion blur's frame counter pinned to the frame (motion_blur.rs).";
|
||||
CameraCutPlugin: crate::cut::install, "A camera that jumps is a cut: its history starts again and its motion blur waits (cut.rs, RT31).";
|
||||
MotionBlurPlugin: crate::motion_blur::install, "Motion blur's frame counter pinned to the frame (motion_blur.rs).";
|
||||
}
|
||||
|
||||
/// The frame's state that raea's plugins' systems read (the clock, the frame's rows, the loaded edit, the error), empty
|
||||
@@ -86,11 +107,11 @@ pub struct FramePlugin;
|
||||
|
||||
impl Plugin for FramePlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<super::Clock>().init_resource::<super::Error>().init_resource::<super::FrameRows>();
|
||||
if !app.world().contains_resource::<super::Edit>() {
|
||||
app.init_resource::<raea_sys_frame::Clock>().init_resource::<raea_sys_frame::Error>().init_resource::<raea_sys_frame::FrameRows>();
|
||||
if !app.world().contains_resource::<raea_sys_frame::Edit>() {
|
||||
let prog = raea_core_program::ir::Program::default();
|
||||
let timeline = raea_core_program::timeline::Timeline::new(&prog, &[]).expect("an empty timeline");
|
||||
app.insert_resource(super::Edit { prog, timeline: std::sync::Arc::new(timeline), media: Vec::new() });
|
||||
app.insert_resource(raea_sys_frame::Edit { prog, timeline: std::sync::Arc::new(timeline), media: Vec::new() });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -102,7 +123,7 @@ pub struct RegisteredPlugins {
|
||||
|
||||
impl Plugin for RegisteredPlugins {
|
||||
fn build(&self, app: &mut App) {
|
||||
super::plugins::install(app, self.fps);
|
||||
crate::plugins::install(app, self.fps);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,14 +132,14 @@ impl Plugin for RegisteredPlugins {
|
||||
pub fn scene3d_systems() -> ScheduleConfigs<ScheduleSystem> {
|
||||
(
|
||||
// 2D over the 3D: its camera once there's a part, then each part's place, cell and colour (raea-sys-sprite)
|
||||
(super::sprite2d::camera_2d, super::sprite2d::sync_2d).chain(),
|
||||
super::scene3d::model_setup,
|
||||
super::scene3d::instance_models,
|
||||
super::scene3d::model_shadow_markers,
|
||||
super::scene3d::toon_models,
|
||||
((super::scene3d::sync_meshes, super::scene3d::sync_instances, super::scene3d::sync_pictures, raea_sys_rendermap::sync_render_maps, super::shader_ext::sync_shaded, raea_sys_sampler::arrays::sync_arrays, raea_sys_sampler::sync_samplers).chain(), super::toon::sync_toon, (super::scene3d::sync_camera, super::scene3d::sync_post).chain(), super::motion_blur::sync_motion_blur, (super::environment::sync_environment, super::environment::sync_prefiltered, super::environment::sync_suns).chain(), (super::scene3d::sync_light_sets, super::scene3d::sync_lights).chain(), super::scene3d::sync_fog_volumes, super::scene3d::sync_fog_dither, super::scene3d::sync_models, super::scene3d::sync_morphs, super::scene3d::sync_attach, super::grid::grid_models, super::scene3d::sync_bones, super::look::sync_frame_look, super::look::sync_looks, super::compose::sync_passes, super::look::sync_flat, super::paint::sync_paint, super::decal::sync_decals, super::text3d::sync_texts).chain(),
|
||||
(crate::sprite2d::camera_2d, crate::sprite2d::sync_2d).chain(),
|
||||
crate::scene3d::model_setup,
|
||||
crate::scene3d::instance_models,
|
||||
crate::scene3d::model_shadow_markers,
|
||||
crate::scene3d::toon_models,
|
||||
((crate::scene3d::sync_meshes, crate::scene3d::sync_instances, crate::scene3d::sync_pictures, raea_sys_rendermap::sync_render_maps, raea_sys_material::swapped::sync_swapped_maps, crate::shader_ext::sync_shaded, raea_sys_sampler::arrays::sync_arrays, raea_sys_sampler::sync_samplers).chain(), crate::toon::sync_toon, (crate::scene3d::sync_camera, crate::scene3d::sync_post).chain(), crate::motion_blur::sync_motion_blur, (crate::environment::sync_environment, crate::environment::sync_prefiltered, crate::environment::sync_suns).chain(), (crate::scene3d::sync_light_sets, crate::scene3d::sync_lights).chain(), crate::scene3d::sync_fog_volumes, crate::scene3d::sync_fog_dither, crate::scene3d::sync_models, crate::scene3d::sync_morphs, crate::scene3d::sync_attach, crate::grid::grid_models, crate::scene3d::sync_bones, crate::look::sync_frame_look, crate::look::sync_looks, crate::compose::sync_passes, crate::look::sync_flat, crate::paint::sync_paint, crate::decal::sync_decals, crate::text3d::sync_texts).chain(),
|
||||
// --clay and --review's clay half: every standard surface grey, after the rows set their colours
|
||||
super::scene3d::clay::clay_materials,
|
||||
crate::scene3d::clay::clay_materials,
|
||||
)
|
||||
.chain()
|
||||
}
|
||||
@@ -149,8 +170,8 @@ mod tests {
|
||||
let mut app = App::new();
|
||||
app.add_plugins(FramePlugin);
|
||||
let w = app.world();
|
||||
assert!(w.contains_resource::<super::super::Clock>() && w.contains_resource::<super::super::Error>());
|
||||
assert!(w.contains_resource::<super::super::FrameRows>() && w.contains_resource::<super::super::Edit>());
|
||||
assert!(w.contains_resource::<raea_sys_frame::Clock>() && w.contains_resource::<raea_sys_frame::Error>());
|
||||
assert!(w.contains_resource::<raea_sys_frame::FrameRows>() && w.contains_resource::<raea_sys_frame::Edit>());
|
||||
assert!(RaeaPlugins.build().enabled::<FramePlugin>());
|
||||
}
|
||||
|
||||
@@ -347,7 +347,12 @@ fn traceable(src: &Mesh, mapped: bool) -> Option<Traceable> {
|
||||
let n = pos.len();
|
||||
let normal = src.attribute(Mesh::ATTRIBUTE_NORMAL)?.clone();
|
||||
let uv = src.attribute(Mesh::ATTRIBUTE_UV_0).cloned().unwrap_or(VertexAttributeValues::Float32x2(vec![[0.0, 0.0]; n]));
|
||||
let mut out = Mesh::new(PrimitiveTopology::TriangleList, bevy::asset::RenderAssetUsages::default());
|
||||
// RM1 (docs/render-memory.feature): the GPU's copy alone. Solari builds its BLAS from the render world's mesh
|
||||
// (blas.rs: RenderMesh, MeshAllocator) and nothing on the CPU reads this copy once it's made (its tangents are
|
||||
// made below, before it's added); kept in the main world too, every traced part was held twice there
|
||||
// (RAEA_KEEP_CPU_ASSETS=1 keeps it in the main world too: the A/B control)
|
||||
let usage = if std::env::var_os("RAEA_KEEP_CPU_ASSETS").is_some() { bevy::asset::RenderAssetUsages::default() } else { bevy::asset::RenderAssetUsages::RENDER_WORLD };
|
||||
let mut out = Mesh::new(PrimitiveTopology::TriangleList, usage);
|
||||
out.insert_attribute(Mesh::ATTRIBUTE_POSITION, pos);
|
||||
out.insert_attribute(Mesh::ATTRIBUTE_NORMAL, normal);
|
||||
out.insert_attribute(Mesh::ATTRIBUTE_UV_0, uv);
|
||||
|
||||
+13
-20
@@ -47,16 +47,9 @@ pub use aov::Aov;
|
||||
|
||||
// a frame's rows, the edit, the clock and the row helpers every pass reads (raea-sys-frame)
|
||||
use raea_sys_frame::*;
|
||||
use raea_sys_frame::bevy_api;
|
||||
use raea_sys_environment as environment;
|
||||
use raea_runtime_scene3d as scene3d;
|
||||
use raea_sys_look::look;
|
||||
use raea_sys_post::outline;
|
||||
// composition passes: which pass drew each pixel, and the frame-wide effects held back from some
|
||||
use raea_sys_compose::compose;
|
||||
use raea_sys_fog_half as fog_half;
|
||||
use raea_sys_fog::froxel;
|
||||
use raea_sys_fog::froxel_glass;
|
||||
use raea_sys_fog::fire;
|
||||
// text in the 3D world, a glyph an entity (raea-sys-text3d)
|
||||
use raea_sys_text3d as text3d;
|
||||
@@ -67,34 +60,25 @@ use raea_sys_sprite as sprite2d;
|
||||
use raea_sys_grid as grid;
|
||||
// footage behind the 3D and a camera's window on a larger view (<Matchmove>)
|
||||
use raea_sys_matchmove as matchmove;
|
||||
use raea_sys_look::paint;
|
||||
use raea_sys_material::decal;
|
||||
use raea_sys_compose::passes;
|
||||
use raea_sys_screen as screen;
|
||||
// the Engine's screens
|
||||
#[cfg(feature = "native")]
|
||||
mod screens;
|
||||
use raea_sys_volume as volume;
|
||||
// meshes that cast shadows without being drawn (<Mesh shadow="only">)
|
||||
use raea_sys_material::shadow_only;
|
||||
use raea_sys_material::shadow_catch;
|
||||
// baked simulations played back by the frame (<MeshSequence>, <Goo>) and glitches on any part (physics.tsx)
|
||||
use raea_sys_meshseq as meshseq;
|
||||
// toon (cel) surfaces and their ink outlines (<MeshToonMaterial>)
|
||||
use raea_sys_material::toon;
|
||||
use raea_sys_toon as toon;
|
||||
use raea_sys_shader as shader_ext;
|
||||
// the camera's lens: Fisheye and LensDistortion, a pass after tone mapping
|
||||
use raea_sys_post::lens;
|
||||
// the camera's motion blur (<MotionBlur>), a function of the frame
|
||||
use raea_sys_post::motion_blur;
|
||||
use raea_sys_post::cut;
|
||||
// Bevy's depth of field, patched to keep the frame's alpha (the paint look's sky)
|
||||
use raea_sys_post::dof;
|
||||
use raea_sys_post::effect_stack;
|
||||
// Bevy plugins compiled in by a crate that registers them, driven by generic rows and stepped by the frame index
|
||||
use raea_runtime_plugins as plugins;
|
||||
/// raea's modules as Bevy plugins, gathered in RaeaPlugins (docs/sdk.feature S6a)
|
||||
pub mod raea_plugins;
|
||||
/// raea's modules as Bevy plugins, gathered in RaeaPlugins (raea-render-plugins, docs/sdk.feature S6a)
|
||||
pub use raea_render_plugins as raea_plugins;
|
||||
|
||||
pub struct Engine {
|
||||
app: App,
|
||||
@@ -142,7 +126,8 @@ impl Drop for Engine {
|
||||
|
||||
#[cfg(feature = "native")] pub(crate) use raea_io_trace::stat; #[cfg(not(feature = "native"))] pub(crate) fn stat(_: &str) -> bool { false } // a stat channel (io/trace stats.rs, nobuild NB2a); the web's build has none
|
||||
/// RAEA_MEM_MARKS: one line on stderr per start-up phase, "mem_mark <ms since the first mark> <phys_footprint MB>
|
||||
/// <phase>", to line up with a memory timeline (the footprint is the process's, as the OS counts it).
|
||||
/// <phase>", to line up with a memory timeline (the footprint is the process's, as the OS counts it). Each App's
|
||||
/// assets follow it, as raea-sys-memtally tallies them (RM0).
|
||||
pub fn mem_mark(what: &str) {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
static T0: std::sync::OnceLock<bevy::platform::time::Instant> = std::sync::OnceLock::new();
|
||||
@@ -152,6 +137,7 @@ pub fn mem_mark(what: &str) {
|
||||
let t = T0.get_or_init(bevy::platform::time::Instant::now).elapsed().as_secs_f64() * 1e3;
|
||||
let mb = phys_footprint().map(|b| format!("{:.1}", b as f64 / 1048576.0)).unwrap_or_else(|| "?".into());
|
||||
eprintln!("mem_mark {t:.1} {mb} {what}");
|
||||
raea_sys_memtally::marked();
|
||||
}
|
||||
|
||||
/// The edit has 3D rows (a light or a mesh): its camera draws through the 3D pipeline, and the Apple encoder runs
|
||||
@@ -227,6 +213,13 @@ impl Engine {
|
||||
Engine::build(prog, inserted, dir, None, true)
|
||||
}
|
||||
|
||||
/// The live engine in `slot` (re)opened for `prog`, with its own inserted rows: the one there is let go first, so
|
||||
/// two 3D worlds are never held at once (docs/render-memory.feature RM2).
|
||||
pub fn open_in<'a>(slot: &'a mut Option<Engine>, prog: &Program, dir: &Path) -> Result<&'a mut Engine, String> {
|
||||
*slot = None;
|
||||
Ok(slot.insert(Engine::new_live(prog, &crate::inserted_of(prog), dir)?))
|
||||
}
|
||||
|
||||
/// The frame `draw` drew last, if any.
|
||||
pub fn drawn(&self) -> Option<i64> { self.drawn }
|
||||
|
||||
|
||||
@@ -40,7 +40,58 @@ impl Engine {
|
||||
store::clear(world);
|
||||
world.insert_resource(raea_sys_frame::RenderImages::default()); // its render images: this load's are made as its rows spawn
|
||||
world.despawn_all::<With<Mirror>>();
|
||||
let ents = store::load(world, inserted);
|
||||
// RM9: maps made BC7 where this device samples BC (raea-sys-material maps.rs bc7_chain)
|
||||
if let Some(d) = world.get_resource::<bevy::render::renderer::RenderDevice>() {
|
||||
raea_sys_material::maps::set_block_compression(d.features().contains(bevy::render::render_resource::WgpuFeatures::TEXTURE_COMPRESSION_BC));
|
||||
}
|
||||
let ents = store::load_for_engine(world, inserted);
|
||||
// RAEA_MEM_MARKS (docs/render-memory.feature RM5): the rows' text by kind and column, the biggest first. Each
|
||||
// string is held by the program, the store and the evaluator's gathered columns, so its bytes count three times
|
||||
if std::env::var_os("RAEA_MEM_MARKS").is_some() {
|
||||
let mut by: std::collections::HashMap<(&str, &str), (usize, usize)> = std::collections::HashMap::new();
|
||||
for t in inserted {
|
||||
for (c, v) in &t.vals {
|
||||
if let raea_core_program::ir::V::S(s) = v {
|
||||
let e = by.entry((t.kind.as_str(), c.as_str())).or_default();
|
||||
e.0 += s.len();
|
||||
e.1 += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut by: Vec<_> = by.into_iter().collect();
|
||||
by.sort_by(|a, b| b.1 .0.cmp(&a.1 .0));
|
||||
let all: usize = by.iter().map(|(_, (n, _))| n).sum();
|
||||
eprintln!("mem_text all {:.1} MB in {} rows", all as f64 / 1e6, inserted.len());
|
||||
for ((k, c), (n, rows)) in by.iter().take(10) {
|
||||
eprintln!("mem_text {k}.{c} {:.1} MB over {rows} rows", *n as f64 / 1e6);
|
||||
}
|
||||
// the shapes by their outermost call, and how many are the same text as another's
|
||||
let mut heads: std::collections::HashMap<&str, (usize, usize)> = std::collections::HashMap::new();
|
||||
let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
|
||||
let (mut dup, mut moved_inner) = (0usize, std::collections::HashSet::<&str>::new());
|
||||
for t in inserted.iter().filter(|t| t.kind == "mesh") {
|
||||
let Some(raea_core_program::ir::V::S(sh)) = t.vals.get("shape") else { continue };
|
||||
let head = sh.split(|c: char| c == '(' || c == ':').next().unwrap_or("");
|
||||
let e = heads.entry(head).or_default();
|
||||
e.0 += sh.len();
|
||||
e.1 += 1;
|
||||
if !seen.insert(sh.as_str()) {
|
||||
dup += sh.len();
|
||||
}
|
||||
// a moved, turned or scaled shape: its inside, which copies placed apart share
|
||||
if matches!(head, "move" | "rotate" | "scale" | "transform") {
|
||||
if let (Some(a), Some(b)) = (sh.find('('), sh.rfind(',')) {
|
||||
moved_inner.insert(&sh[a + 1..b.max(a + 1)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut heads: Vec<_> = heads.into_iter().collect();
|
||||
heads.sort_by(|a, b| b.1 .0.cmp(&a.1 .0));
|
||||
eprintln!("mem_text shapes: {:.1} MB the same text as another row's; by outermost call: {}", dup as f64 / 1e6, heads.iter().take(8).map(|(h, (n, c))| format!("{h} {:.1} MB/{c}", *n as f64 / 1e6)).collect::<Vec<_>>().join(", "));
|
||||
let mut longest: Vec<usize> = inserted.iter().filter_map(|t| match t.vals.get("shape") { Some(raea_core_program::ir::V::S(s)) => Some(s.len()), _ => None }).collect();
|
||||
longest.sort_unstable_by(|a, b| b.cmp(a));
|
||||
eprintln!("mem_text shapes: longest {:?} chars", &longest[..longest.len().min(6)]);
|
||||
}
|
||||
#[cfg(feature = "native")]
|
||||
let mut rows2d: Vec<(String, serde_json::Value, Entity)> = Vec::new();
|
||||
let mut camera = None;
|
||||
@@ -133,7 +184,10 @@ impl Engine {
|
||||
Some(t) => t,
|
||||
None => std::sync::Arc::new(raea_core_program::timeline::Timeline::from_cols(prog, base)?),
|
||||
};
|
||||
world.insert_resource(Edit { prog: prog.clone(), timeline, media });
|
||||
// the edit's header only (its size, rate and length: all anything reads of it); a whole copy held every row's
|
||||
// text a fourth time, halcyon's shapes 274 MB (docs/render-memory.feature RM5)
|
||||
let head = Program { fps: prog.fps, width: prog.width, height: prog.height, frames: prog.frames, ..Default::default() };
|
||||
world.insert_resource(Edit { prog: head, timeline, media });
|
||||
world.insert_resource(raea_sys_frame::tables::Cuts::of(prog));
|
||||
world.insert_resource(raea_sys_frame::shots::Shots::of(prog));
|
||||
world.insert_resource(FrameRows::new(ix));
|
||||
|
||||
@@ -191,6 +191,9 @@ impl Engine {
|
||||
app.insert_non_send(Media { backend, decoders: HashMap::new(), dir: dir.to_path_buf() });
|
||||
}
|
||||
raea_sys_hold::install(&mut app, live); // a part held by a hand, and wireframe (docs/scene-feed.feature SF4c, SF3e)
|
||||
if super::stat("RAEA_MEM_MARKS") {
|
||||
raea_sys_memtally::install(&mut app); // RM0: each world's assets after a mark
|
||||
}
|
||||
mem_mark("engine: plugins built (DefaultPlugins, the render device)");
|
||||
Ok(Opening { app, prog: prog.clone(), inserted: inserted.to_vec(), dir: dir.to_path_buf(), timeline, live })
|
||||
}
|
||||
@@ -225,6 +228,8 @@ impl Engine {
|
||||
image.texture_descriptor.view_formats = &[TextureFormat::Rgba8Unorm];
|
||||
let target = app.world_mut().resource_mut::<Assets<Image>>().add(image);
|
||||
app.insert_resource(TagRowTarget(target.clone())).init_resource::<ViewBox>().add_systems(PostUpdate, tag_row_view.before(bevy::camera::CameraUpdateSystems));
|
||||
// a camera drawing a box's view culls by it (#261), once Bevy has made its own frusta
|
||||
app.add_systems(PostUpdate, sub_view_frusta.after(bevy::camera::visibility::VisibilitySystems::UpdateFrusta).before(bevy::camera::visibility::VisibilitySystems::CheckVisibility));
|
||||
// a free camera over the scene (docs/preview.feature PV1c): off until a preview asks for one
|
||||
app.init_resource::<raea_sys_frame::view::FreeView>().add_systems(PostUpdate, raea_sys_frame::view::apply.before(bevy::transform::TransformSystems::Propagate));
|
||||
// without native nothing ever comes back (frames are read back only to be encoded or analysed)
|
||||
|
||||
@@ -280,7 +280,8 @@ pub(crate) fn spawn_3d(world: &mut World, e: Entity, t: &Tup, inserted: &[Tup],
|
||||
};
|
||||
let mesh = match &three {
|
||||
Some((_, own)) => {
|
||||
let m = raea_sys_three_shader::fitted(world.resource::<Assets<Mesh>>().get(&mesh), &t.id, expr.strip_prefix("buffer:"), own)?;
|
||||
let buffer = expr.strip_prefix("buffer:").map(raea_core_shape::buffer_json).transpose().map_err(|e| format!("mesh {}: {e}", t.id))?;
|
||||
let m = raea_sys_three_shader::fitted(world.resource::<Assets<Mesh>>().get(&mesh), &t.id, buffer.as_deref(), own)?;
|
||||
scene3d::shared_mesh(world, &format!("{expr}\0{uvs}\0{tangents}\0three:{}", own.join(",")), || Ok(m))?
|
||||
}
|
||||
None => mesh,
|
||||
@@ -314,6 +315,10 @@ pub(crate) fn spawn_3d(world: &mut World, e: Entity, t: &Tup, inserted: &[Tup],
|
||||
if shared {
|
||||
world.entity_mut(e).insert(scene3d::SharedMaterial);
|
||||
}
|
||||
// a map whose picture a render keys frame by frame (RM6): swapped on this part's material
|
||||
if let Some(sw) = raea_sys_material::swapped::of(t, dir)? {
|
||||
world.entity_mut(e).insert(sw);
|
||||
}
|
||||
} else {
|
||||
grid::put(world, e, mesh, mat, vals);
|
||||
// a shader over the lit surface (shader_ext.rs): put on once the rows are applied (scene3d's shade_rows)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! raea-runtime-gpuframe), the render world's diagnostics forwarded.
|
||||
|
||||
use super::*;
|
||||
pub(crate) use raea_sys_viewbox::{TagRowTarget, ViewBox, tag_row_view};
|
||||
pub(crate) use raea_sys_viewbox::{TagRowTarget, ViewBox, sub_view_frusta, tag_row_view};
|
||||
|
||||
/// Bevy's render diagnostics (each pass's elapsed time, `render/...`): each new measurement into the run's totals (stats.read, the stats table: nobuild NB2a), the smoothed ones into its trace once a second.
|
||||
#[cfg(feature = "native")]
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
// 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} />
|
||||
</>
|
||||
));
|
||||
@@ -34,6 +34,8 @@ 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),
|
||||
@@ -41,10 +43,12 @@ const AMD: u32 = 0x1002;
|
||||
/// 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 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 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
|
||||
/// (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) && kind != wgpu::DeviceType::Cpu)
|
||||
windows && env.is_none() && dx12.iter().any(|&(vendor, kind)| (matches!(vendor, INTEL | AMD) || QUALCOMM.contains(&vendor)) && 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
|
||||
@@ -147,6 +151,8 @@ 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");
|
||||
|
||||
+7
-1
@@ -11,5 +11,11 @@ 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" }
|
||||
rav1d = { git = "https://github.com/memorysafety/rav1d", tag = "v1.1.0", default-features = false, features = ["bitdepth_8", "bitdepth_16"] }
|
||||
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"] }
|
||||
@@ -112,6 +112,18 @@ pub fn logs() -> Option<std::path::PathBuf> {
|
||||
|
||||
/// A new temp file named `raea-NAME-PID-N`, open to read and write, gone when raea is: unlinked once open on unix,
|
||||
/// delete-on-close on Windows, so a render that dies leaves nothing behind (an encoder's samples, a render's parts).
|
||||
/// `bytes` written to `path` whole or not at all: into a part file beside it (named for this process, so two
|
||||
/// writers never share one), then renamed over it, so a reader never sees half a file. Its folder is made first.
|
||||
pub fn write_whole(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
|
||||
if let Some(d) = path.parent() {
|
||||
std::fs::create_dir_all(d)?;
|
||||
}
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let part = path.with_file_name(format!(".{name}.{}.part", std::process::id()));
|
||||
std::fs::write(&part, bytes)?;
|
||||
std::fs::rename(&part, path)
|
||||
}
|
||||
|
||||
pub fn scratch_file(name: &str) -> Result<std::fs::File, String> {
|
||||
static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let p = std::env::temp_dir().join(format!("raea-{name}-{}-{}", std::process::id(), N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
|
||||
|
||||
@@ -24,12 +24,13 @@ 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.
|
||||
fn spec(p: &Path) -> String {
|
||||
pub 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).
|
||||
/// 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).
|
||||
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()));
|
||||
@@ -41,6 +42,7 @@ 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 };
|
||||
@@ -56,6 +58,8 @@ 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",
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -64,6 +68,8 @@ 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);
|
||||
|
||||
@@ -35,7 +35,9 @@ pub fn drop_tsconfigs(dir: &Path, depth: usize) {
|
||||
}
|
||||
}
|
||||
|
||||
pub const MEDIA_EXTS: [&str; 12] = ["mp4", "mov", "m4v", "mp3", "wav", "m4a", "png", "jpg", "webp", "gif", "glb", "gltf"];
|
||||
/// 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"];
|
||||
|
||||
/// 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
|
||||
|
||||
@@ -17,6 +17,8 @@ raea-runtime-wear = { path = "../wear" }
|
||||
raea-native = { path = "../../engine/native", default-features = false }
|
||||
raea-io-trace = { path = "../../io/trace" }
|
||||
raea-core-shape = { path = "../../core/shape" }
|
||||
# ECS worlds on Bevy's own ECS (ecs.*), a crate of their own
|
||||
raea-runtime-ecs = { path = "../ecs" }
|
||||
raea-core-place = { path = "../../core/place" }
|
||||
raea-core-scene = { path = "../../core/scene" }
|
||||
raea-io-media = { path = "../../io/media", default-features = false, features = ["soft-audio", "apple"] }
|
||||
@@ -26,7 +28,6 @@ raea-sys-grab = { path = "../../systems/grab" }
|
||||
raea-sys-fonts = { path = "../../systems/fonts" }
|
||||
raea-sys-ml = { path = "../../systems/ml", optional = true }
|
||||
raea-sys-speech = { path = "../../systems/speech", optional = true }
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
|
||||
manifold-rust = "0.16.0"
|
||||
base64 = "0.22"
|
||||
image = { version = "0.25", default-features = false, features = ["png", "hdr"] }
|
||||
|
||||
+2
-470
@@ -1,470 +1,2 @@
|
||||
//! raea/ecs on Bevy's own ECS: each world is a `bevy::ecs::world::World`. A component is a real Bevy component
|
||||
//! registered by name at run time (its value a JSON object, in Bevy's archetype tables); an entity holds any number of
|
||||
//! them; queries are Bevy's (QueryBuilder with/without by component id) with column conditions on top; parent and child
|
||||
//! are Bevy's `ChildOf` relationship (despawning a parent takes its children); resources and per-frame events sit beside
|
||||
//! the world. Entities carry stable ids of ours, so a world copies (for `at(frame)`) and comes back the same.
|
||||
//!
|
||||
//! The first version's calls (one kind per entity: spawn {kind, cols}, query {kind, where}, column, count, rows) are
|
||||
//! kept: a kind is a component named after it.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
use bevy::ecs::component::{ComponentCloneBehavior, ComponentDescriptor, ComponentId, StorageType};
|
||||
use bevy::ecs::entity::Entity;
|
||||
use bevy::ecs::hierarchy::{ChildOf, Children};
|
||||
use bevy::ecs::query::QueryBuilder;
|
||||
use bevy::ecs::world::World;
|
||||
use bevy::ptr::OwningPtr;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
/// One world: Bevy's, plus our ids, the component names, resources and this frame's events.
|
||||
struct BWorld {
|
||||
w: World,
|
||||
comps: BTreeMap<String, ComponentId>,
|
||||
ids: BTreeMap<u64, Entity>,
|
||||
back: HashMap<Entity, u64>,
|
||||
/// the kind an entity was spawned with (the first version's single component)
|
||||
kind: HashMap<u64, String>,
|
||||
next: u64,
|
||||
resources: BTreeMap<String, Value>,
|
||||
events: BTreeMap<String, Vec<Value>>,
|
||||
}
|
||||
|
||||
unsafe fn drop_value(p: OwningPtr<'_>) {
|
||||
// SAFETY: every dynamic component's value is a serde_json::Value (its descriptor's layout)
|
||||
unsafe { p.drop_as::<Value>() }
|
||||
}
|
||||
|
||||
impl BWorld {
|
||||
fn new() -> BWorld {
|
||||
BWorld { w: World::new(), comps: BTreeMap::new(), ids: BTreeMap::new(), back: HashMap::new(), kind: HashMap::new(), next: 0, resources: BTreeMap::new(), events: BTreeMap::new() }
|
||||
}
|
||||
|
||||
/// The component registered for `name` (made on first use).
|
||||
fn comp(&mut self, name: &str) -> ComponentId {
|
||||
if let Some(c) = self.comps.get(name) {
|
||||
return *c;
|
||||
}
|
||||
// SAFETY: the layout and drop are serde_json::Value's, which is Send + Sync; no relationship
|
||||
let d = unsafe { ComponentDescriptor::new_with_layout(name.to_string(), StorageType::Table, std::alloc::Layout::new::<Value>(), Some(drop_value), true, false, ComponentCloneBehavior::Ignore, None) };
|
||||
let id = self.w.register_component_with_descriptor(d);
|
||||
self.comps.insert(name.to_string(), id);
|
||||
id
|
||||
}
|
||||
|
||||
fn entity(&self, id: u64) -> R<Entity> {
|
||||
self.ids.get(&id).copied().ok_or_else(|| format!("no entity {id}"))
|
||||
}
|
||||
|
||||
fn insert(&mut self, e: Entity, name: &str, value: Value) {
|
||||
let c = self.comp(name);
|
||||
OwningPtr::make(value, |ptr| {
|
||||
// SAFETY: `c` was registered with Value's layout and `ptr` holds a Value
|
||||
unsafe {
|
||||
self.w.entity_mut(e).insert_by_id(c, ptr);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn get(&self, e: Entity, name: &str) -> Option<&Value> {
|
||||
let c = *self.comps.get(name)?;
|
||||
// SAFETY: as insert
|
||||
self.w.get_by_id(e, c).map(|p| unsafe { p.deref::<Value>() })
|
||||
}
|
||||
|
||||
fn spawn(&mut self, comps: &Map<String, Value>) -> u64 {
|
||||
let e = self.w.spawn_empty().id();
|
||||
self.next += 1;
|
||||
let id = self.next;
|
||||
self.ids.insert(id, e);
|
||||
self.back.insert(e, id);
|
||||
for (k, v) in comps {
|
||||
self.insert(e, k, v.clone());
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// The names of the components an entity has, sorted.
|
||||
fn names(&self, e: Entity) -> Vec<String> {
|
||||
self.comps.iter().filter(|(_, c)| self.w.get_by_id(e, **c).is_some()).map(|(n, _)| n.clone()).collect()
|
||||
}
|
||||
|
||||
fn despawn(&mut self, id: u64) -> R<()> {
|
||||
let e = self.entity(id)?;
|
||||
// Bevy despawns the children with it (ChildOf links them): their ids go too
|
||||
let mut gone = vec![e];
|
||||
let mut i = 0;
|
||||
while i < gone.len() {
|
||||
if let Some(ch) = self.w.get::<Children>(gone[i]) {
|
||||
gone.extend(ch.iter());
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
self.w.despawn(e);
|
||||
for g in gone {
|
||||
if let Some(gid) = self.back.remove(&g) {
|
||||
self.ids.remove(&gid);
|
||||
self.kind.remove(&gid);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Entities with every `with` component and none of `without`, by Bevy's query; ours in id order.
|
||||
fn find(&mut self, with: &[String], without: &[String]) -> Vec<u64> {
|
||||
let with_ids: Vec<ComponentId> = with.iter().map(|n| self.comp(n)).collect();
|
||||
let without_ids: Vec<ComponentId> = without.iter().map(|n| self.comp(n)).collect();
|
||||
let mut qb = QueryBuilder::<Entity>::new(&mut self.w);
|
||||
for c in &with_ids {
|
||||
qb.with_id(*c);
|
||||
}
|
||||
for c in &without_ids {
|
||||
qb.without_id(*c);
|
||||
}
|
||||
let mut q = qb.build();
|
||||
let mut out: Vec<u64> = q.iter(&self.w).filter_map(|e| self.back.get(&e).copied()).collect();
|
||||
out.sort_unstable();
|
||||
out
|
||||
}
|
||||
|
||||
/// A column condition: "Comp.field" (or "field" of the first `with` component) compared with a value.
|
||||
fn passes(&self, e: Entity, default: Option<&str>, cond: &Value) -> bool {
|
||||
let Some(a) = cond.as_array() else { return false };
|
||||
let (col, op, val) = (a.first().and_then(Value::as_str).unwrap_or(""), a.get(1).and_then(Value::as_str).unwrap_or("=="), a.get(2).cloned().unwrap_or(Value::Null));
|
||||
let (comp, field) = match col.split_once('.') {
|
||||
Some((c, f)) => (c, f),
|
||||
None => (default.unwrap_or(""), col),
|
||||
};
|
||||
let x = self.get(e, comp).and_then(|v| v.get(field)).cloned().unwrap_or(Value::Null);
|
||||
let num = |v: &Value| match v {
|
||||
Value::Bool(b) => Some(if *b { 1.0 } else { 0.0 }),
|
||||
Value::Number(n) => n.as_f64(),
|
||||
_ => None,
|
||||
};
|
||||
match op {
|
||||
"==" => x == val || (num(&x).is_some() && num(&x) == num(&val)),
|
||||
"!=" => !(x == val || (num(&x).is_some() && num(&x) == num(&val))),
|
||||
_ => match (num(&x), num(&val)) {
|
||||
(Some(y), Some(w)) => match op {
|
||||
"<" => y < w,
|
||||
"<=" => y <= w,
|
||||
">" => y > w,
|
||||
">=" => y >= w,
|
||||
_ => false,
|
||||
},
|
||||
_ => false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything, to copy the world: each entity's id, kind, components and parent, plus resources and events.
|
||||
fn dump(&self) -> Value {
|
||||
let ents: Vec<Value> = self
|
||||
.ids
|
||||
.iter()
|
||||
.map(|(id, e)| {
|
||||
let comps: Map<String, Value> = self.names(*e).into_iter().filter_map(|n| self.get(*e, &n).cloned().map(|v| (n, v))).collect();
|
||||
let parent = self.w.get::<ChildOf>(*e).and_then(|c| self.back.get(&c.parent()).copied());
|
||||
json!({"id": id, "kind": self.kind.get(id), "components": comps, "parent": parent})
|
||||
})
|
||||
.collect();
|
||||
json!({"entities": ents, "next": self.next, "resources": self.resources, "events": self.events})
|
||||
}
|
||||
|
||||
fn load(d: &Value) -> BWorld {
|
||||
let mut w = BWorld::new();
|
||||
let ents = d["entities"].as_array().cloned().unwrap_or_default();
|
||||
for en in &ents {
|
||||
let id = en["id"].as_u64().unwrap_or(0);
|
||||
let e = w.w.spawn_empty().id();
|
||||
w.ids.insert(id, e);
|
||||
w.back.insert(e, id);
|
||||
if let Some(k) = en["kind"].as_str() {
|
||||
w.kind.insert(id, k.to_string());
|
||||
}
|
||||
for (k, v) in en["components"].as_object().into_iter().flatten() {
|
||||
w.insert(e, k, v.clone());
|
||||
}
|
||||
}
|
||||
for en in &ents {
|
||||
if let (Some(id), Some(p)) = (en["id"].as_u64(), en["parent"].as_u64()) {
|
||||
let (c, p) = (w.ids[&id], w.ids[&p]);
|
||||
w.w.entity_mut(c).insert(ChildOf(p));
|
||||
}
|
||||
}
|
||||
w.next = d["next"].as_u64().unwrap_or(0);
|
||||
w.resources = d["resources"].as_object().map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())).collect()).unwrap_or_default();
|
||||
w.events = d["events"].as_object().map(|m| m.iter().map(|(k, v)| (k.clone(), v.as_array().cloned().unwrap_or_default())).collect()).unwrap_or_default();
|
||||
w
|
||||
}
|
||||
|
||||
/// The first version's row: {id, kind, ...the kind component's columns}.
|
||||
fn row(&self, id: u64) -> R<Value> {
|
||||
let e = self.entity(id)?;
|
||||
let kind = self.kind.get(&id).cloned().unwrap_or_default();
|
||||
let mut m = self.get(e, &kind).and_then(Value::as_object).cloned().unwrap_or_default();
|
||||
m.insert("id".into(), json!(id));
|
||||
m.insert("kind".into(), json!(kind));
|
||||
Ok(Value::Object(m))
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static WORLDS: RefCell<(u64, HashMap<u64, BWorld>)> = RefCell::new((0, HashMap::new()));
|
||||
}
|
||||
|
||||
fn u(v: &Value, k: &str) -> R<u64> {
|
||||
v.get(k).and_then(Value::as_u64).ok_or_else(|| format!("{k}: a number"))
|
||||
}
|
||||
fn s<'a>(v: &'a Value, k: &str) -> R<&'a str> {
|
||||
v.get(k).and_then(Value::as_str).ok_or_else(|| format!("{k}: a string"))
|
||||
}
|
||||
fn strings(v: &Value, k: &str) -> Vec<String> {
|
||||
v.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn with_world<T>(v: &Value, f: impl FnOnce(&mut BWorld) -> R<T>) -> R<T> {
|
||||
let id = u(v, "world")?;
|
||||
WORLDS.with(|ws| {
|
||||
let mut ws = ws.borrow_mut();
|
||||
let w = ws.1.get_mut(&id).ok_or_else(|| format!("no world {id}"))?;
|
||||
f(w)
|
||||
})
|
||||
}
|
||||
|
||||
fn put(w: BWorld) -> Value {
|
||||
WORLDS.with(|ws| {
|
||||
let mut ws = ws.borrow_mut();
|
||||
ws.0 += 1;
|
||||
let id = ws.0;
|
||||
ws.1.insert(id, w);
|
||||
json!({"world": id})
|
||||
})
|
||||
}
|
||||
|
||||
/// The ecs.* calls.
|
||||
pub fn call(name: &str, v: &Value) -> R<Value> {
|
||||
match name {
|
||||
"ecs.new" => Ok(put(BWorld::new())),
|
||||
"ecs.clone" => {
|
||||
let d = with_world(v, |w| Ok(w.dump()))?;
|
||||
Ok(put(BWorld::load(&d)))
|
||||
}
|
||||
"ecs.free" => {
|
||||
let id = u(v, "world")?;
|
||||
WORLDS.with(|ws| ws.borrow_mut().1.remove(&id));
|
||||
Ok(Value::Null)
|
||||
}
|
||||
"ecs.spawn" => with_world(v, |w| {
|
||||
let mut comps = v.get("components").and_then(Value::as_object).cloned().unwrap_or_default();
|
||||
let kind = v.get("kind").and_then(Value::as_str).map(str::to_string);
|
||||
if let Some(k) = &kind {
|
||||
comps.insert(k.clone(), Value::Object(v.get("cols").and_then(Value::as_object).cloned().unwrap_or_default()));
|
||||
}
|
||||
let id = w.spawn(&comps);
|
||||
if let Some(k) = kind {
|
||||
w.kind.insert(id, k);
|
||||
}
|
||||
if let Some(p) = v.get("parent").and_then(Value::as_u64) {
|
||||
let (c, p) = (w.entity(id)?, w.entity(p)?);
|
||||
w.w.entity_mut(c).insert(ChildOf(p));
|
||||
}
|
||||
Ok(json!({"id": id}))
|
||||
}),
|
||||
"ecs.set" => with_world(v, |w| {
|
||||
let id = u(v, "id")?;
|
||||
let e = w.entity(id)?;
|
||||
let kind = w.kind.get(&id).cloned().ok_or_else(|| format!("entity {id} has no kind (use ecs.insert)"))?;
|
||||
let mut cur = w.get(e, &kind).and_then(Value::as_object).cloned().unwrap_or_default();
|
||||
for (k, x) in v.get("cols").and_then(Value::as_object).into_iter().flatten() {
|
||||
cur.insert(k.clone(), x.clone());
|
||||
}
|
||||
w.insert(e, &kind, Value::Object(cur));
|
||||
Ok(Value::Null)
|
||||
}),
|
||||
"ecs.get" => with_world(v, |w| w.row(u(v, "id")?)),
|
||||
"ecs.despawn" => with_world(v, |w| w.despawn(u(v, "id")?).map(|_| Value::Null)),
|
||||
"ecs.insert" => with_world(v, |w| {
|
||||
let e = w.entity(u(v, "id")?)?;
|
||||
for (k, x) in v.get("components").and_then(Value::as_object).into_iter().flatten() {
|
||||
w.insert(e, k, x.clone());
|
||||
}
|
||||
Ok(Value::Null)
|
||||
}),
|
||||
"ecs.remove" => with_world(v, |w| {
|
||||
let e = w.entity(u(v, "id")?)?;
|
||||
for n in strings(v, "names") {
|
||||
if let Some(c) = w.comps.get(&n).copied() {
|
||||
w.w.entity_mut(e).remove_by_id(c);
|
||||
}
|
||||
}
|
||||
Ok(Value::Null)
|
||||
}),
|
||||
"ecs.components" => with_world(v, |w| {
|
||||
let e = w.entity(u(v, "id")?)?;
|
||||
let m: Map<String, Value> = w.names(e).into_iter().filter_map(|n| w.get(e, &n).cloned().map(|x| (n, x))).collect();
|
||||
Ok(Value::Object(m))
|
||||
}),
|
||||
"ecs.find" => with_world(v, |w| {
|
||||
let with = strings(v, "with");
|
||||
let without = strings(v, "without");
|
||||
let conds: Vec<Value> = v.get("where").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
let ids = w.find(&with, &without);
|
||||
let default = with.first().cloned();
|
||||
let ids: Vec<u64> = ids.into_iter().filter(|id| conds.iter().all(|c| w.passes(w.ids[id], default.as_deref(), c))).collect();
|
||||
if v.get("rows").and_then(Value::as_bool).unwrap_or(false) {
|
||||
let rows: Vec<Value> = ids
|
||||
.iter()
|
||||
.map(|id| {
|
||||
let e = w.ids[id];
|
||||
let comps: Map<String, Value> = w.names(e).into_iter().filter_map(|n| w.get(e, &n).cloned().map(|x| (n, x))).collect();
|
||||
json!({"id": id, "components": comps})
|
||||
})
|
||||
.collect();
|
||||
return Ok(json!({"ids": ids, "rows": rows}));
|
||||
}
|
||||
Ok(json!({"ids": ids}))
|
||||
}),
|
||||
// the first version's query: a kind's entities by its columns
|
||||
"ecs.query" => with_world(v, |w| {
|
||||
let kind = s(v, "kind")?.to_string();
|
||||
let conds: Vec<Value> = v.get("where").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
let ids: Vec<u64> = w.find(std::slice::from_ref(&kind), &[]).into_iter().filter(|id| w.kind.get(id) == Some(&kind)).filter(|id| conds.iter().all(|c| w.passes(w.ids[id], Some(&kind), c))).collect();
|
||||
Ok(json!({"ids": ids}))
|
||||
}),
|
||||
"ecs.column" => with_world(v, |w| {
|
||||
let kind = s(v, "kind")?.to_string();
|
||||
let col = s(v, "col")?;
|
||||
let ids: Vec<u64> = w.find(std::slice::from_ref(&kind), &[]).into_iter().filter(|id| w.kind.get(id) == Some(&kind)).collect();
|
||||
Ok(json!(ids.iter().map(|id| w.get(w.ids[id], &kind).and_then(|c| c.get(col)).and_then(Value::as_f64).map(|x| json!(x)).unwrap_or(Value::Null)).collect::<Vec<_>>()))
|
||||
}),
|
||||
"ecs.count" => with_world(v, |w| {
|
||||
let kind = s(v, "kind")?.to_string();
|
||||
Ok(json!(w.find(std::slice::from_ref(&kind), &[]).into_iter().filter(|id| w.kind.get(id) == Some(&kind)).count()))
|
||||
}),
|
||||
"ecs.rows" => with_world(v, |w| {
|
||||
let mut ids: Vec<(String, u64)> = w.kind.iter().map(|(id, k)| (k.clone(), *id)).collect();
|
||||
ids.sort();
|
||||
Ok(Value::Array(ids.into_iter().filter_map(|(_, id)| w.row(id).ok()).collect()))
|
||||
}),
|
||||
"ecs.parent" => with_world(v, |w| {
|
||||
let c = w.entity(u(v, "id")?)?;
|
||||
match v.get("parent").and_then(Value::as_u64) {
|
||||
Some(p) => {
|
||||
let p = w.entity(p)?;
|
||||
w.w.entity_mut(c).insert(ChildOf(p));
|
||||
}
|
||||
None if v.get("parent").is_some_and(Value::is_null) => {
|
||||
w.w.entity_mut(c).remove::<ChildOf>();
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
Ok(json!(w.w.get::<ChildOf>(c).and_then(|p| w.back.get(&p.parent()).copied())))
|
||||
}),
|
||||
"ecs.children" => with_world(v, |w| {
|
||||
let e = w.entity(u(v, "id")?)?;
|
||||
let mut out: Vec<u64> = w.w.get::<Children>(e).map(|c| c.iter().filter_map(|x| w.back.get(&x).copied()).collect()).unwrap_or_default();
|
||||
out.sort_unstable();
|
||||
Ok(json!(out))
|
||||
}),
|
||||
"ecs.resource" => with_world(v, |w| {
|
||||
let name = s(v, "name")?.to_string();
|
||||
if let Some(x) = v.get("value") {
|
||||
w.resources.insert(name.clone(), x.clone());
|
||||
}
|
||||
Ok(w.resources.get(&name).cloned().unwrap_or(Value::Null))
|
||||
}),
|
||||
"ecs.send" => with_world(v, |w| {
|
||||
w.events.entry(s(v, "name")?.to_string()).or_default().push(v.get("value").cloned().unwrap_or(Value::Null));
|
||||
Ok(Value::Null)
|
||||
}),
|
||||
"ecs.events" => with_world(v, |w| Ok(json!(w.events.get(s(v, "name")?).cloned().unwrap_or_default()))),
|
||||
"ecs.clear_events" => with_world(v, |w| {
|
||||
w.events.clear();
|
||||
Ok(Value::Null)
|
||||
}),
|
||||
// what renders, straight from the world: entities with a Mesh and a Transform as 3D nodes (world space,
|
||||
// parents' transforms composed), and lights; the bridge draws these without a React element per entity
|
||||
"ecs.scene" => with_world(v, |w| {
|
||||
let mut out = Vec::new();
|
||||
for id in w.find(&["Mesh".into()], &[]) {
|
||||
let e = w.ids[&id];
|
||||
let mesh = w.get(e, "Mesh").cloned().unwrap_or(Value::Null);
|
||||
let mut t = transform_of(w.get(e, "Transform"));
|
||||
let mut p = w.w.get::<ChildOf>(e).map(|c| c.parent());
|
||||
while let Some(pe) = p {
|
||||
let pt = transform_of(w.get(pe, "Transform"));
|
||||
t = compose(&pt, &t);
|
||||
p = w.w.get::<ChildOf>(pe).map(|c| c.parent());
|
||||
}
|
||||
out.push(json!({"id": id, "kind": "Mesh", "mesh": mesh, "position": [t[0], t[1], t[2]], "rotation": [t[3], t[4], t[5]], "scale": t[6]}));
|
||||
}
|
||||
for id in w.find(&["Light".into()], &[]) {
|
||||
out.push(json!({"id": id, "kind": "Light", "light": w.get(w.ids[&id], "Light").cloned().unwrap_or(Value::Null)}));
|
||||
}
|
||||
Ok(Value::Array(out))
|
||||
}),
|
||||
o => Err(format!("no native call {o}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// [x, y, z, rx, ry, rz, scale] from a Transform component ({x, y, z, rx, ry, rz, scale}, all optional).
|
||||
fn transform_of(t: Option<&Value>) -> [f64; 7] {
|
||||
let g = |k: &str, d: f64| t.and_then(|t| t.get(k)).and_then(Value::as_f64).unwrap_or(d);
|
||||
[g("x", 0.0), g("y", 0.0), g("z", 0.0), g("rx", 0.0), g("ry", 0.0), g("rz", 0.0), g("scale", 1.0)]
|
||||
}
|
||||
|
||||
/// A child's transform in its parent's space, made world space (rotation by z, then y, then x; uniform scale).
|
||||
fn compose(parent: &[f64; 7], child: &[f64; 7]) -> [f64; 7] {
|
||||
let (sx, cx) = parent[3].sin_cos();
|
||||
let (sy, cy) = parent[4].sin_cos();
|
||||
let (sz, cz) = parent[5].sin_cos();
|
||||
let (mut x, mut y, mut z) = (child[0] * parent[6], child[1] * parent[6], child[2] * parent[6]);
|
||||
// z
|
||||
let (x1, y1) = (x * cz - y * sz, x * sz + y * cz);
|
||||
x = x1;
|
||||
y = y1;
|
||||
// y
|
||||
let (x2, z2) = (x * cy + z * sy, -x * sy + z * cy);
|
||||
x = x2;
|
||||
z = z2;
|
||||
// x
|
||||
let (y3, z3) = (y * cx - z * sx, y * sx + z * cx);
|
||||
y = y3;
|
||||
z = z3;
|
||||
[parent[0] + x, parent[1] + y, parent[2] + z, parent[3] + child[3], parent[4] + child[4], parent[5] + child[5], parent[6] * child[6]]
|
||||
}
|
||||
|
||||
/// The ecs.* names with their TypeScript types, for the registry.
|
||||
pub const CALLS: &[(&str, &str, &str, &str)] = &[
|
||||
("ecs.new", "{}", "{ world: number }", "a new world (Bevy's)"),
|
||||
("ecs.clone", "{ world: number }", "{ world: number }", "a copy of a world"),
|
||||
("ecs.free", "{ world: number }", "null", "drop a world"),
|
||||
("ecs.spawn", "{ world: number; kind?: string; cols?: Record<string, number | string | boolean>; components?: Record<string, unknown>; parent?: number }", "{ id: number }", "a new entity: a kind with columns, and/or any components"),
|
||||
("ecs.set", "{ world: number; id: number; cols: Record<string, number | string | boolean> }", "null", "columns merged into an entity's kind"),
|
||||
("ecs.get", "{ world: number; id: number }", "{ id: number; kind: string } & Record<string, number | string | boolean>", "an entity's row (its kind's columns)"),
|
||||
("ecs.despawn", "{ world: number; id: number }", "null", "remove an entity and its children"),
|
||||
("ecs.insert", "{ world: number; id: number; components: Record<string, unknown> }", "null", "components added to (or replaced on) an entity"),
|
||||
("ecs.remove", "{ world: number; id: number; names: string[] }", "null", "components taken off an entity"),
|
||||
("ecs.components", "{ world: number; id: number }", "Record<string, unknown>", "an entity's components by name"),
|
||||
("ecs.find", "{ world: number; with?: string[]; without?: string[]; where?: [string, \"==\" | \"!=\" | \"<\" | \"<=\" | \">\" | \">=\", number | string | boolean][]; rows?: boolean }", "{ ids: number[]; rows?: { id: number; components: Record<string, unknown> }[] }", "entities with every `with` component and no `without` one (Bevy's query), passing every condition (\"Comp.field\")"),
|
||||
("ecs.query", "{ world: number; kind: string; where: [string, \"==\" | \"!=\" | \"<\" | \"<=\" | \">\" | \">=\", number | string | boolean][] }", "{ ids: number[] }", "ids of kind's entities passing every condition"),
|
||||
("ecs.column", "{ world: number; kind: string; col: string }", "(number | null)[]", "one numeric column of a kind, in id order"),
|
||||
("ecs.count", "{ world: number; kind: string }", "number", "how many entities of a kind"),
|
||||
("ecs.rows", "{ world: number }", "({ id: number; kind: string } & Record<string, number | string | boolean>)[]", "every kind's rows, by kind then id"),
|
||||
("ecs.parent", "{ world: number; id: number; parent?: number | null }", "number | null", "an entity's parent (set it with parent; null clears it)"),
|
||||
("ecs.children", "{ world: number; id: number }", "number[]", "an entity's children"),
|
||||
("ecs.resource", "{ world: number; name: string; value?: unknown }", "unknown", "a resource (set it with value)"),
|
||||
("ecs.send", "{ world: number; name: string; value?: unknown }", "null", "an event for this frame"),
|
||||
("ecs.events", "{ world: number; name: string }", "unknown[]", "this frame's events of a name"),
|
||||
("ecs.clear_events", "{ world: number }", "null", "the frame's events cleared (each step starts with none)"),
|
||||
("ecs.scene", "{ world: number }", "{ id: number; kind: \"Mesh\" | \"Light\"; mesh?: unknown; light?: unknown; position?: [number, number, number]; rotation?: [number, number, number]; scale?: number }[]", "the world's Mesh+Transform entities (world space) and lights, to draw"),
|
||||
];
|
||||
|
||||
/// How many worlds are alive (media.live's leak check).
|
||||
pub fn live() -> usize {
|
||||
WORLDS.with(|ws| ws.borrow().1.len())
|
||||
}
|
||||
//! raea/ecs on Bevy's own ECS: raea-runtime-ecs, its own crate since 11-29 (the crate limit).
|
||||
pub use raea_runtime_ecs::*;
|
||||
@@ -104,6 +104,8 @@ struct Picture {
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
solids: HashMap<u64, solid::Solid>,
|
||||
/// each expression's one solid (solid.rs put_later)
|
||||
solid_ids: HashMap<String, u64>,
|
||||
pictures: HashMap<u64, Picture>,
|
||||
#[cfg(target_vendor = "apple")]
|
||||
vdecs: HashMap<u64, raea_io_media::apple::packets::PacketDecoder>,
|
||||
|
||||
+64
-21
@@ -5,21 +5,48 @@ use serde_json::{Value, json};
|
||||
|
||||
use super::{R, State, args, f, s, u};
|
||||
|
||||
/// A solid by its expression, and its Manifold once something needs it. A boolean or a move only writes the
|
||||
/// expression: the renderer builds the mesh from that (raea-core-shape, which keeps it on disk), so a set made of cuts
|
||||
/// isn't cut a second time here on every open (a third of a launch-film set's script pass, 11-10). A query, a mesh,
|
||||
/// an export or an operation that works on the solid itself builds it then.
|
||||
/// A solid by its expression. A boolean or a move only writes the expression: the renderer builds the mesh from that
|
||||
/// (raea-core-shape, which keeps it on disk), so a set made of cuts isn't cut a second time here on every open (a third
|
||||
/// of a launch-film set's script pass, 11-10). A query, a mesh, an export or an operation that works on the solid
|
||||
/// itself builds its Manifold then, into BUILT.
|
||||
///
|
||||
/// docs/render-memory.feature RM5: a solid was once its expression and its Manifold for as long as the script ran. No
|
||||
/// component frees its solids (TypeScript has no finalizer to), and each render of a component makes them again, so
|
||||
/// halcyon's script held 2.4 GB of Manifolds (their colliders 1 GB) by the end of warm-up, a third of the render's
|
||||
/// heap. Now the same expression is one solid, counted (solid.free lets one holder go), and a built Manifold lives in
|
||||
/// BUILT, a bounded cache by expression: one let go is built again from its expression if it's asked for again.
|
||||
pub(crate) struct Solid {
|
||||
m: std::cell::OnceCell<Manifold>,
|
||||
expr: String,
|
||||
refs: u32,
|
||||
}
|
||||
|
||||
/// Built Manifolds by expression, two generations of at most GEN_BYTES each (raea-core-shape's Generations).
|
||||
const GEN_BYTES: usize = 192 << 20;
|
||||
|
||||
/// A Manifold's heap, roughly: its halfedges, vertices, normals and properties, and the collider a boolean builds on
|
||||
/// it (measured 11-26 on halcyon's solids: about 250 bytes a triangle in all).
|
||||
fn manifold_bytes(m: &Manifold) -> usize {
|
||||
m.num_tri() * 250 + 4096
|
||||
}
|
||||
|
||||
/// `m` kept in BUILT for `expr`, weighed by its heap.
|
||||
fn keep_built(expr: &str, m: std::rc::Rc<Manifold>) {
|
||||
let weight = manifold_bytes(&m);
|
||||
BUILT.with(|b| b.borrow_mut().hold(expr, m, weight));
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static BUILT: std::cell::RefCell<raea_core_shape::Generations<std::rc::Rc<Manifold>>> = std::cell::RefCell::new(raea_core_shape::Generations::new(GEN_BYTES));
|
||||
}
|
||||
|
||||
impl Solid {
|
||||
fn m(&self) -> R<&Manifold> {
|
||||
if self.m.get().is_none() {
|
||||
let _ = self.m.set(raea_core_shape::solid_or_empty(&self.expr)?);
|
||||
fn m(&self) -> R<std::rc::Rc<Manifold>> {
|
||||
if let Some(m) = BUILT.with(|b| b.borrow_mut().get(&self.expr)) {
|
||||
return Ok(m);
|
||||
}
|
||||
Ok(self.m.get().expect("just set"))
|
||||
let m = std::rc::Rc::new(raea_core_shape::solid_or_empty(&self.expr)?);
|
||||
keep_built(&self.expr, m.clone());
|
||||
Ok(m)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,18 +59,24 @@ fn arg_text(a: &Value) -> String {
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// A solid already built: its Manifold kept in BUILT for what asks for it next.
|
||||
fn put(&mut self, m: Manifold, expr: String) -> Value {
|
||||
self.next += 1;
|
||||
let id = self.next;
|
||||
self.solids.insert(id, Solid { m: std::cell::OnceCell::from(m), expr: expr.clone() });
|
||||
json!({"id": id, "expr": expr})
|
||||
keep_built(&expr, std::rc::Rc::new(m));
|
||||
self.put_later(expr)
|
||||
}
|
||||
|
||||
/// A solid that is only its expression so far.
|
||||
/// A solid that is only its expression so far: the one solid of that expression, counted once more.
|
||||
fn put_later(&mut self, expr: String) -> Value {
|
||||
if let Some(&id) = self.solid_ids.get(&expr) {
|
||||
if let Some(sd) = self.solids.get_mut(&id) {
|
||||
sd.refs += 1;
|
||||
return json!({"id": id, "expr": expr});
|
||||
}
|
||||
}
|
||||
self.next += 1;
|
||||
let id = self.next;
|
||||
self.solids.insert(id, Solid { m: std::cell::OnceCell::new(), expr: expr.clone() });
|
||||
self.solid_ids.insert(expr.clone(), id);
|
||||
self.solids.insert(id, Solid { expr: expr.clone(), refs: 1 });
|
||||
json!({"id": id, "expr": expr})
|
||||
}
|
||||
|
||||
@@ -51,6 +84,16 @@ impl State {
|
||||
self.solids.get(&id).ok_or_else(|| format!("solid {id} is gone (freed?)"))
|
||||
}
|
||||
|
||||
/// One holder of solid `id` lets it go; the last one's going frees it.
|
||||
fn free_solid(&mut self, id: u64) {
|
||||
let Some(sd) = self.solids.get_mut(&id) else { return };
|
||||
sd.refs = sd.refs.saturating_sub(1);
|
||||
if sd.refs == 0 {
|
||||
if let Some(sd) = self.solids.remove(&id) {
|
||||
self.solid_ids.remove(&sd.expr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A solid no expression describes (made from a mesh, a level set, a warp), written as OBJ under its content's hash; its
|
||||
@@ -176,7 +219,7 @@ pub(super) fn call(st: &mut State, name: &str, v: &Value) -> R<Value> {
|
||||
"genus" => Ok(json!(sd.m()?.genus())),
|
||||
"min_gap" => {
|
||||
let o = st.solid(u(v, "other")?)?;
|
||||
Ok(json!(sd.m()?.min_gap(o.m()?, f(v, "z")?)))
|
||||
Ok(json!(sd.m()?.min_gap(&*o.m()?, f(v, "z")?)))
|
||||
}
|
||||
"ray" => {
|
||||
let a: Vec<f64> = args(v).iter().filter_map(Value::as_f64).collect();
|
||||
@@ -225,7 +268,7 @@ pub(super) fn call(st: &mut State, name: &str, v: &Value) -> R<Value> {
|
||||
}
|
||||
"minkowski" | "minkowski_diff" => {
|
||||
let o = other.ok_or_else(|| format!("{fun} takes another solid"))?;
|
||||
let m = if fun == "minkowski" { base.m()?.minkowski_sum(o.m()?) } else { base.m()?.minkowski_difference(o.m()?) };
|
||||
let m = if fun == "minkowski" { base.m()?.minkowski_sum(&*o.m()?) } else { base.m()?.minkowski_difference(&*o.m()?) };
|
||||
(m, format!("{fun}({}, {})", base.expr, o.expr))
|
||||
}
|
||||
"simplify" | "refine_length" | "refine_tolerance" => {
|
||||
@@ -252,7 +295,7 @@ pub(super) fn call(st: &mut State, name: &str, v: &Value) -> R<Value> {
|
||||
}
|
||||
"solid.mesh" => {
|
||||
let sd = st.solid(u(v, "id")?)?;
|
||||
let (verts, tris) = raea_core_shape::to_mesh(sd.m()?);
|
||||
let (verts, tris) = raea_core_shape::to_mesh(&*sd.m()?);
|
||||
Ok(json!({"verts": verts, "tris": tris}))
|
||||
}
|
||||
"solid.from_mesh" => {
|
||||
@@ -297,7 +340,7 @@ pub(super) fn call(st: &mut State, name: &str, v: &Value) -> R<Value> {
|
||||
let sd = st.solid(u(v, "id")?)?;
|
||||
let path = s(v, "path")?;
|
||||
let format = v.get("format").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| if path.ends_with(".glb") { "glb".into() } else { "obj".into() });
|
||||
Ok(json!({"bytes": raea_core_shape::export(sd.m()?, path, &format)?}))
|
||||
Ok(json!({"bytes": raea_core_shape::export(&*sd.m()?, path, &format)?}))
|
||||
}
|
||||
"solid.import" => {
|
||||
let path = s(v, "path")?;
|
||||
@@ -330,7 +373,7 @@ pub(super) fn call(st: &mut State, name: &str, v: &Value) -> R<Value> {
|
||||
}
|
||||
let parts: Vec<&Solid> = ids.iter().map(|i| st.solid(*i)).collect::<R<_>>()?;
|
||||
let expr = if parts.len() == 1 { parts[0].expr.clone() } else { format!("union({})", parts.iter().map(|p| p.expr.as_str()).collect::<Vec<_>>().join(", ")) };
|
||||
let m = Manifold::compose(&parts.iter().map(|p| p.m().cloned()).collect::<R<Vec<_>>>()?);
|
||||
let m = Manifold::compose(&parts.iter().map(|p| p.m().map(|m| (*m).clone())).collect::<R<Vec<_>>>()?);
|
||||
Ok(st.put(m, expr))
|
||||
}
|
||||
// the convex hull of points
|
||||
@@ -428,7 +471,7 @@ pub(super) fn call(st: &mut State, name: &str, v: &Value) -> R<Value> {
|
||||
Ok(section_json(&cs))
|
||||
}
|
||||
"solid.free" => {
|
||||
st.solids.remove(&u(v, "id")?);
|
||||
st.free_solid(u(v, "id")?);
|
||||
Ok(Value::Null)
|
||||
}
|
||||
o => Err(format!("no native call {o}")),
|
||||
|
||||
+19
-15
@@ -10,14 +10,8 @@ use std::path::Path;
|
||||
use raea_core_brief::cut::{self, Cut, norm};
|
||||
use serde_json::Value;
|
||||
|
||||
/// One gate as `raea make status` lists it: its name, the file or item it's about, whether it's clear, what it says.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Gate {
|
||||
pub name: &'static str,
|
||||
pub of: Option<String>,
|
||||
pub clear: bool,
|
||||
pub says: String,
|
||||
}
|
||||
/// One gate as `raea make status` lists it (a goal's are the same kind)
|
||||
pub use raea_core_brief::make::Gate;
|
||||
|
||||
fn gate(name: &'static str, of: Option<&str>, clear: bool, says: String) -> Gate {
|
||||
Gate { name, of: of.map(str::to_string), clear, says }
|
||||
@@ -183,17 +177,27 @@ fn file_gates(c: &Cut, plan: &cut::CutPlan, format: &str, f: &Path, rel: &str, s
|
||||
if let Some(cta) = &c.cta {
|
||||
let within = cta.within.unwrap_or(cut::CTA_WITHIN);
|
||||
let end = shape.map(|s| s.2).or_else(|| words.last().map(|w| w.2)).unwrap_or(0.0);
|
||||
let want_s = norm(&cta.text);
|
||||
let want: Vec<&str> = want_s.split(' ').collect();
|
||||
let share = |got: &[&str]| {
|
||||
let last: Vec<&str> = words.iter().filter(|w| w.2 >= end - within).map(|w| w.0.as_str()).collect();
|
||||
// the share of a line's words, in order, in `got`; the best of the brief's lines
|
||||
let share = |line: &str, got: &[&str]| {
|
||||
let want_s = norm(line);
|
||||
let want: Vec<&str> = want_s.split(' ').collect();
|
||||
let j = joined(got, &want);
|
||||
in_order(&want, &j.iter().map(|(w, _)| w.as_str()).collect::<Vec<_>>())
|
||||
};
|
||||
let last: Vec<&str> = words.iter().filter(|w| w.2 >= end - within).map(|w| w.0.as_str()).collect();
|
||||
let heard_share = share(&last);
|
||||
let on_screen = screen.iter().any(|(s, at)| *at >= end - within && share(&s.split(' ').collect::<Vec<_>>()) >= CTA_SHARE);
|
||||
let lines: Vec<&str> = std::iter::once(cta.text.as_str()).chain(cta.also.iter().map(String::as_str)).collect();
|
||||
// the line heard most, the first of equals (none when no line's words were heard)
|
||||
let heard: Vec<_> = lines.iter().map(|l| share(l, &last)).collect();
|
||||
let heard_share = heard.iter().copied().fold(0.0, f64::max);
|
||||
let best = lines.iter().zip(&heard).find(|(_, h)| heard_share > 0.0 && **h == heard_share).map_or("", |(l, _)| *l);
|
||||
let on_screen = screen.iter().any(|(s, at)| *at >= end - within && lines.iter().any(|l| share(l, &s.split(' ').collect::<Vec<_>>()) >= CTA_SHARE));
|
||||
let ok = heard_share >= CTA_SHARE || on_screen;
|
||||
out.push(gate("cta", Some(rel), ok, if ok { format!("ends on the CTA ({})", if on_screen { "on screen" } else { "heard" }) } else { format!("the CTA isn't in its last {within:.0} s ({:.0}% of its words heard there): \"{}\"", heard_share * 100.0, cta.text) }));
|
||||
let says = match (ok, on_screen) {
|
||||
(true, true) => "ends on the CTA (on screen)".to_string(),
|
||||
(true, false) => format!("ends on the CTA (heard: \"{best}\")"),
|
||||
_ => format!("no CTA in its last {within:.0} s ({:.0}% of the nearest one's words heard there): \"{}\"", heard_share * 100.0, if best.is_empty() { &cta.text } else { best }),
|
||||
};
|
||||
out.push(gate("cta", Some(rel), ok, says));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,3 +180,20 @@ fn heard_the_way_people_say_it() {
|
||||
deliver(&d, S1, &line.replace("It's free it's fun", "It's fun it's free"), &[]);
|
||||
assert!(!of(&run(&m, &d), "say", S1).clear);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rotated_cta_lands_on_any_of_its_lines() {
|
||||
// Dutch's hosts rotate "See a vet today at Dutch.com." and "Download the Dutch app and book a call for your dog or cat."
|
||||
let brief = format!("{BRIEF}\"See a vet today at Dutch.com.\"\n");
|
||||
let d = dir("rotated");
|
||||
put(&d, "media/brief.txt", brief.as_bytes());
|
||||
let mut m = contract("");
|
||||
m.cut.as_mut().unwrap().cta.as_mut().unwrap().also = vec!["See a vet today at Dutch.com.".into()];
|
||||
deliver(&d, S1, "it draws the names it's free fun and easy so See a vet today at Dutch com", &[]);
|
||||
let g = run(&m, &d);
|
||||
assert!(of(&g, "cta", S1).clear, "{:?}", of(&g, "cta", S1));
|
||||
assert!(named(&g, "quotes")[0].clear, "{:?}", named(&g, "quotes"));
|
||||
// a rotated line the brief doesn't have is held like any other rule
|
||||
m.cut.as_mut().unwrap().cta.as_mut().unwrap().also.push("Book now at Dutch.com".into());
|
||||
assert!(!named(&run(&m, &d), "quotes")[0].clear);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "raea-runtime-ecs"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "raea/ecs on Bevy's own ECS: worlds of real Bevy components registered by name at run time, a composition's native ecs.* calls"
|
||||
|
||||
[dependencies]
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,470 @@
|
||||
//! raea/ecs on Bevy's own ECS: each world is a `bevy::ecs::world::World`. A component is a real Bevy component
|
||||
//! registered by name at run time (its value a JSON object, in Bevy's archetype tables); an entity holds any number of
|
||||
//! them; queries are Bevy's (QueryBuilder with/without by component id) with column conditions on top; parent and child
|
||||
//! are Bevy's `ChildOf` relationship (despawning a parent takes its children); resources and per-frame events sit beside
|
||||
//! the world. Entities carry stable ids of ours, so a world copies (for `at(frame)`) and comes back the same.
|
||||
//!
|
||||
//! The first version's calls (one kind per entity: spawn {kind, cols}, query {kind, where}, column, count, rows) are
|
||||
//! kept: a kind is a component named after it.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
use bevy::ecs::component::{ComponentCloneBehavior, ComponentDescriptor, ComponentId, StorageType};
|
||||
use bevy::ecs::entity::Entity;
|
||||
use bevy::ecs::hierarchy::{ChildOf, Children};
|
||||
use bevy::ecs::query::QueryBuilder;
|
||||
use bevy::ecs::world::World;
|
||||
use bevy::ptr::OwningPtr;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
/// One world: Bevy's, plus our ids, the component names, resources and this frame's events.
|
||||
struct BWorld {
|
||||
w: World,
|
||||
comps: BTreeMap<String, ComponentId>,
|
||||
ids: BTreeMap<u64, Entity>,
|
||||
back: HashMap<Entity, u64>,
|
||||
/// the kind an entity was spawned with (the first version's single component)
|
||||
kind: HashMap<u64, String>,
|
||||
next: u64,
|
||||
resources: BTreeMap<String, Value>,
|
||||
events: BTreeMap<String, Vec<Value>>,
|
||||
}
|
||||
|
||||
unsafe fn drop_value(p: OwningPtr<'_>) {
|
||||
// SAFETY: every dynamic component's value is a serde_json::Value (its descriptor's layout)
|
||||
unsafe { p.drop_as::<Value>() }
|
||||
}
|
||||
|
||||
impl BWorld {
|
||||
fn new() -> BWorld {
|
||||
BWorld { w: World::new(), comps: BTreeMap::new(), ids: BTreeMap::new(), back: HashMap::new(), kind: HashMap::new(), next: 0, resources: BTreeMap::new(), events: BTreeMap::new() }
|
||||
}
|
||||
|
||||
/// The component registered for `name` (made on first use).
|
||||
fn comp(&mut self, name: &str) -> ComponentId {
|
||||
if let Some(c) = self.comps.get(name) {
|
||||
return *c;
|
||||
}
|
||||
// SAFETY: the layout and drop are serde_json::Value's, which is Send + Sync; no relationship
|
||||
let d = unsafe { ComponentDescriptor::new_with_layout(name.to_string(), StorageType::Table, std::alloc::Layout::new::<Value>(), Some(drop_value), true, false, ComponentCloneBehavior::Ignore, None) };
|
||||
let id = self.w.register_component_with_descriptor(d);
|
||||
self.comps.insert(name.to_string(), id);
|
||||
id
|
||||
}
|
||||
|
||||
fn entity(&self, id: u64) -> R<Entity> {
|
||||
self.ids.get(&id).copied().ok_or_else(|| format!("no entity {id}"))
|
||||
}
|
||||
|
||||
fn insert(&mut self, e: Entity, name: &str, value: Value) {
|
||||
let c = self.comp(name);
|
||||
OwningPtr::make(value, |ptr| {
|
||||
// SAFETY: `c` was registered with Value's layout and `ptr` holds a Value
|
||||
unsafe {
|
||||
self.w.entity_mut(e).insert_by_id(c, ptr);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn get(&self, e: Entity, name: &str) -> Option<&Value> {
|
||||
let c = *self.comps.get(name)?;
|
||||
// SAFETY: as insert
|
||||
self.w.get_by_id(e, c).map(|p| unsafe { p.deref::<Value>() })
|
||||
}
|
||||
|
||||
fn spawn(&mut self, comps: &Map<String, Value>) -> u64 {
|
||||
let e = self.w.spawn_empty().id();
|
||||
self.next += 1;
|
||||
let id = self.next;
|
||||
self.ids.insert(id, e);
|
||||
self.back.insert(e, id);
|
||||
for (k, v) in comps {
|
||||
self.insert(e, k, v.clone());
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// The names of the components an entity has, sorted.
|
||||
fn names(&self, e: Entity) -> Vec<String> {
|
||||
self.comps.iter().filter(|(_, c)| self.w.get_by_id(e, **c).is_some()).map(|(n, _)| n.clone()).collect()
|
||||
}
|
||||
|
||||
fn despawn(&mut self, id: u64) -> R<()> {
|
||||
let e = self.entity(id)?;
|
||||
// Bevy despawns the children with it (ChildOf links them): their ids go too
|
||||
let mut gone = vec![e];
|
||||
let mut i = 0;
|
||||
while i < gone.len() {
|
||||
if let Some(ch) = self.w.get::<Children>(gone[i]) {
|
||||
gone.extend(ch.iter());
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
self.w.despawn(e);
|
||||
for g in gone {
|
||||
if let Some(gid) = self.back.remove(&g) {
|
||||
self.ids.remove(&gid);
|
||||
self.kind.remove(&gid);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Entities with every `with` component and none of `without`, by Bevy's query; ours in id order.
|
||||
fn find(&mut self, with: &[String], without: &[String]) -> Vec<u64> {
|
||||
let with_ids: Vec<ComponentId> = with.iter().map(|n| self.comp(n)).collect();
|
||||
let without_ids: Vec<ComponentId> = without.iter().map(|n| self.comp(n)).collect();
|
||||
let mut qb = QueryBuilder::<Entity>::new(&mut self.w);
|
||||
for c in &with_ids {
|
||||
qb.with_id(*c);
|
||||
}
|
||||
for c in &without_ids {
|
||||
qb.without_id(*c);
|
||||
}
|
||||
let mut q = qb.build();
|
||||
let mut out: Vec<u64> = q.iter(&self.w).filter_map(|e| self.back.get(&e).copied()).collect();
|
||||
out.sort_unstable();
|
||||
out
|
||||
}
|
||||
|
||||
/// A column condition: "Comp.field" (or "field" of the first `with` component) compared with a value.
|
||||
fn passes(&self, e: Entity, default: Option<&str>, cond: &Value) -> bool {
|
||||
let Some(a) = cond.as_array() else { return false };
|
||||
let (col, op, val) = (a.first().and_then(Value::as_str).unwrap_or(""), a.get(1).and_then(Value::as_str).unwrap_or("=="), a.get(2).cloned().unwrap_or(Value::Null));
|
||||
let (comp, field) = match col.split_once('.') {
|
||||
Some((c, f)) => (c, f),
|
||||
None => (default.unwrap_or(""), col),
|
||||
};
|
||||
let x = self.get(e, comp).and_then(|v| v.get(field)).cloned().unwrap_or(Value::Null);
|
||||
let num = |v: &Value| match v {
|
||||
Value::Bool(b) => Some(if *b { 1.0 } else { 0.0 }),
|
||||
Value::Number(n) => n.as_f64(),
|
||||
_ => None,
|
||||
};
|
||||
match op {
|
||||
"==" => x == val || (num(&x).is_some() && num(&x) == num(&val)),
|
||||
"!=" => !(x == val || (num(&x).is_some() && num(&x) == num(&val))),
|
||||
_ => match (num(&x), num(&val)) {
|
||||
(Some(y), Some(w)) => match op {
|
||||
"<" => y < w,
|
||||
"<=" => y <= w,
|
||||
">" => y > w,
|
||||
">=" => y >= w,
|
||||
_ => false,
|
||||
},
|
||||
_ => false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything, to copy the world: each entity's id, kind, components and parent, plus resources and events.
|
||||
fn dump(&self) -> Value {
|
||||
let ents: Vec<Value> = self
|
||||
.ids
|
||||
.iter()
|
||||
.map(|(id, e)| {
|
||||
let comps: Map<String, Value> = self.names(*e).into_iter().filter_map(|n| self.get(*e, &n).cloned().map(|v| (n, v))).collect();
|
||||
let parent = self.w.get::<ChildOf>(*e).and_then(|c| self.back.get(&c.parent()).copied());
|
||||
json!({"id": id, "kind": self.kind.get(id), "components": comps, "parent": parent})
|
||||
})
|
||||
.collect();
|
||||
json!({"entities": ents, "next": self.next, "resources": self.resources, "events": self.events})
|
||||
}
|
||||
|
||||
fn load(d: &Value) -> BWorld {
|
||||
let mut w = BWorld::new();
|
||||
let ents = d["entities"].as_array().cloned().unwrap_or_default();
|
||||
for en in &ents {
|
||||
let id = en["id"].as_u64().unwrap_or(0);
|
||||
let e = w.w.spawn_empty().id();
|
||||
w.ids.insert(id, e);
|
||||
w.back.insert(e, id);
|
||||
if let Some(k) = en["kind"].as_str() {
|
||||
w.kind.insert(id, k.to_string());
|
||||
}
|
||||
for (k, v) in en["components"].as_object().into_iter().flatten() {
|
||||
w.insert(e, k, v.clone());
|
||||
}
|
||||
}
|
||||
for en in &ents {
|
||||
if let (Some(id), Some(p)) = (en["id"].as_u64(), en["parent"].as_u64()) {
|
||||
let (c, p) = (w.ids[&id], w.ids[&p]);
|
||||
w.w.entity_mut(c).insert(ChildOf(p));
|
||||
}
|
||||
}
|
||||
w.next = d["next"].as_u64().unwrap_or(0);
|
||||
w.resources = d["resources"].as_object().map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())).collect()).unwrap_or_default();
|
||||
w.events = d["events"].as_object().map(|m| m.iter().map(|(k, v)| (k.clone(), v.as_array().cloned().unwrap_or_default())).collect()).unwrap_or_default();
|
||||
w
|
||||
}
|
||||
|
||||
/// The first version's row: {id, kind, ...the kind component's columns}.
|
||||
fn row(&self, id: u64) -> R<Value> {
|
||||
let e = self.entity(id)?;
|
||||
let kind = self.kind.get(&id).cloned().unwrap_or_default();
|
||||
let mut m = self.get(e, &kind).and_then(Value::as_object).cloned().unwrap_or_default();
|
||||
m.insert("id".into(), json!(id));
|
||||
m.insert("kind".into(), json!(kind));
|
||||
Ok(Value::Object(m))
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static WORLDS: RefCell<(u64, HashMap<u64, BWorld>)> = RefCell::new((0, HashMap::new()));
|
||||
}
|
||||
|
||||
fn u(v: &Value, k: &str) -> R<u64> {
|
||||
v.get(k).and_then(Value::as_u64).ok_or_else(|| format!("{k}: a number"))
|
||||
}
|
||||
fn s<'a>(v: &'a Value, k: &str) -> R<&'a str> {
|
||||
v.get(k).and_then(Value::as_str).ok_or_else(|| format!("{k}: a string"))
|
||||
}
|
||||
fn strings(v: &Value, k: &str) -> Vec<String> {
|
||||
v.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn with_world<T>(v: &Value, f: impl FnOnce(&mut BWorld) -> R<T>) -> R<T> {
|
||||
let id = u(v, "world")?;
|
||||
WORLDS.with(|ws| {
|
||||
let mut ws = ws.borrow_mut();
|
||||
let w = ws.1.get_mut(&id).ok_or_else(|| format!("no world {id}"))?;
|
||||
f(w)
|
||||
})
|
||||
}
|
||||
|
||||
fn put(w: BWorld) -> Value {
|
||||
WORLDS.with(|ws| {
|
||||
let mut ws = ws.borrow_mut();
|
||||
ws.0 += 1;
|
||||
let id = ws.0;
|
||||
ws.1.insert(id, w);
|
||||
json!({"world": id})
|
||||
})
|
||||
}
|
||||
|
||||
/// The ecs.* calls.
|
||||
pub fn call(name: &str, v: &Value) -> R<Value> {
|
||||
match name {
|
||||
"ecs.new" => Ok(put(BWorld::new())),
|
||||
"ecs.clone" => {
|
||||
let d = with_world(v, |w| Ok(w.dump()))?;
|
||||
Ok(put(BWorld::load(&d)))
|
||||
}
|
||||
"ecs.free" => {
|
||||
let id = u(v, "world")?;
|
||||
WORLDS.with(|ws| ws.borrow_mut().1.remove(&id));
|
||||
Ok(Value::Null)
|
||||
}
|
||||
"ecs.spawn" => with_world(v, |w| {
|
||||
let mut comps = v.get("components").and_then(Value::as_object).cloned().unwrap_or_default();
|
||||
let kind = v.get("kind").and_then(Value::as_str).map(str::to_string);
|
||||
if let Some(k) = &kind {
|
||||
comps.insert(k.clone(), Value::Object(v.get("cols").and_then(Value::as_object).cloned().unwrap_or_default()));
|
||||
}
|
||||
let id = w.spawn(&comps);
|
||||
if let Some(k) = kind {
|
||||
w.kind.insert(id, k);
|
||||
}
|
||||
if let Some(p) = v.get("parent").and_then(Value::as_u64) {
|
||||
let (c, p) = (w.entity(id)?, w.entity(p)?);
|
||||
w.w.entity_mut(c).insert(ChildOf(p));
|
||||
}
|
||||
Ok(json!({"id": id}))
|
||||
}),
|
||||
"ecs.set" => with_world(v, |w| {
|
||||
let id = u(v, "id")?;
|
||||
let e = w.entity(id)?;
|
||||
let kind = w.kind.get(&id).cloned().ok_or_else(|| format!("entity {id} has no kind (use ecs.insert)"))?;
|
||||
let mut cur = w.get(e, &kind).and_then(Value::as_object).cloned().unwrap_or_default();
|
||||
for (k, x) in v.get("cols").and_then(Value::as_object).into_iter().flatten() {
|
||||
cur.insert(k.clone(), x.clone());
|
||||
}
|
||||
w.insert(e, &kind, Value::Object(cur));
|
||||
Ok(Value::Null)
|
||||
}),
|
||||
"ecs.get" => with_world(v, |w| w.row(u(v, "id")?)),
|
||||
"ecs.despawn" => with_world(v, |w| w.despawn(u(v, "id")?).map(|_| Value::Null)),
|
||||
"ecs.insert" => with_world(v, |w| {
|
||||
let e = w.entity(u(v, "id")?)?;
|
||||
for (k, x) in v.get("components").and_then(Value::as_object).into_iter().flatten() {
|
||||
w.insert(e, k, x.clone());
|
||||
}
|
||||
Ok(Value::Null)
|
||||
}),
|
||||
"ecs.remove" => with_world(v, |w| {
|
||||
let e = w.entity(u(v, "id")?)?;
|
||||
for n in strings(v, "names") {
|
||||
if let Some(c) = w.comps.get(&n).copied() {
|
||||
w.w.entity_mut(e).remove_by_id(c);
|
||||
}
|
||||
}
|
||||
Ok(Value::Null)
|
||||
}),
|
||||
"ecs.components" => with_world(v, |w| {
|
||||
let e = w.entity(u(v, "id")?)?;
|
||||
let m: Map<String, Value> = w.names(e).into_iter().filter_map(|n| w.get(e, &n).cloned().map(|x| (n, x))).collect();
|
||||
Ok(Value::Object(m))
|
||||
}),
|
||||
"ecs.find" => with_world(v, |w| {
|
||||
let with = strings(v, "with");
|
||||
let without = strings(v, "without");
|
||||
let conds: Vec<Value> = v.get("where").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
let ids = w.find(&with, &without);
|
||||
let default = with.first().cloned();
|
||||
let ids: Vec<u64> = ids.into_iter().filter(|id| conds.iter().all(|c| w.passes(w.ids[id], default.as_deref(), c))).collect();
|
||||
if v.get("rows").and_then(Value::as_bool).unwrap_or(false) {
|
||||
let rows: Vec<Value> = ids
|
||||
.iter()
|
||||
.map(|id| {
|
||||
let e = w.ids[id];
|
||||
let comps: Map<String, Value> = w.names(e).into_iter().filter_map(|n| w.get(e, &n).cloned().map(|x| (n, x))).collect();
|
||||
json!({"id": id, "components": comps})
|
||||
})
|
||||
.collect();
|
||||
return Ok(json!({"ids": ids, "rows": rows}));
|
||||
}
|
||||
Ok(json!({"ids": ids}))
|
||||
}),
|
||||
// the first version's query: a kind's entities by its columns
|
||||
"ecs.query" => with_world(v, |w| {
|
||||
let kind = s(v, "kind")?.to_string();
|
||||
let conds: Vec<Value> = v.get("where").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
let ids: Vec<u64> = w.find(std::slice::from_ref(&kind), &[]).into_iter().filter(|id| w.kind.get(id) == Some(&kind)).filter(|id| conds.iter().all(|c| w.passes(w.ids[id], Some(&kind), c))).collect();
|
||||
Ok(json!({"ids": ids}))
|
||||
}),
|
||||
"ecs.column" => with_world(v, |w| {
|
||||
let kind = s(v, "kind")?.to_string();
|
||||
let col = s(v, "col")?;
|
||||
let ids: Vec<u64> = w.find(std::slice::from_ref(&kind), &[]).into_iter().filter(|id| w.kind.get(id) == Some(&kind)).collect();
|
||||
Ok(json!(ids.iter().map(|id| w.get(w.ids[id], &kind).and_then(|c| c.get(col)).and_then(Value::as_f64).map(|x| json!(x)).unwrap_or(Value::Null)).collect::<Vec<_>>()))
|
||||
}),
|
||||
"ecs.count" => with_world(v, |w| {
|
||||
let kind = s(v, "kind")?.to_string();
|
||||
Ok(json!(w.find(std::slice::from_ref(&kind), &[]).into_iter().filter(|id| w.kind.get(id) == Some(&kind)).count()))
|
||||
}),
|
||||
"ecs.rows" => with_world(v, |w| {
|
||||
let mut ids: Vec<(String, u64)> = w.kind.iter().map(|(id, k)| (k.clone(), *id)).collect();
|
||||
ids.sort();
|
||||
Ok(Value::Array(ids.into_iter().filter_map(|(_, id)| w.row(id).ok()).collect()))
|
||||
}),
|
||||
"ecs.parent" => with_world(v, |w| {
|
||||
let c = w.entity(u(v, "id")?)?;
|
||||
match v.get("parent").and_then(Value::as_u64) {
|
||||
Some(p) => {
|
||||
let p = w.entity(p)?;
|
||||
w.w.entity_mut(c).insert(ChildOf(p));
|
||||
}
|
||||
None if v.get("parent").is_some_and(Value::is_null) => {
|
||||
w.w.entity_mut(c).remove::<ChildOf>();
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
Ok(json!(w.w.get::<ChildOf>(c).and_then(|p| w.back.get(&p.parent()).copied())))
|
||||
}),
|
||||
"ecs.children" => with_world(v, |w| {
|
||||
let e = w.entity(u(v, "id")?)?;
|
||||
let mut out: Vec<u64> = w.w.get::<Children>(e).map(|c| c.iter().filter_map(|x| w.back.get(&x).copied()).collect()).unwrap_or_default();
|
||||
out.sort_unstable();
|
||||
Ok(json!(out))
|
||||
}),
|
||||
"ecs.resource" => with_world(v, |w| {
|
||||
let name = s(v, "name")?.to_string();
|
||||
if let Some(x) = v.get("value") {
|
||||
w.resources.insert(name.clone(), x.clone());
|
||||
}
|
||||
Ok(w.resources.get(&name).cloned().unwrap_or(Value::Null))
|
||||
}),
|
||||
"ecs.send" => with_world(v, |w| {
|
||||
w.events.entry(s(v, "name")?.to_string()).or_default().push(v.get("value").cloned().unwrap_or(Value::Null));
|
||||
Ok(Value::Null)
|
||||
}),
|
||||
"ecs.events" => with_world(v, |w| Ok(json!(w.events.get(s(v, "name")?).cloned().unwrap_or_default()))),
|
||||
"ecs.clear_events" => with_world(v, |w| {
|
||||
w.events.clear();
|
||||
Ok(Value::Null)
|
||||
}),
|
||||
// what renders, straight from the world: entities with a Mesh and a Transform as 3D nodes (world space,
|
||||
// parents' transforms composed), and lights; the bridge draws these without a React element per entity
|
||||
"ecs.scene" => with_world(v, |w| {
|
||||
let mut out = Vec::new();
|
||||
for id in w.find(&["Mesh".into()], &[]) {
|
||||
let e = w.ids[&id];
|
||||
let mesh = w.get(e, "Mesh").cloned().unwrap_or(Value::Null);
|
||||
let mut t = transform_of(w.get(e, "Transform"));
|
||||
let mut p = w.w.get::<ChildOf>(e).map(|c| c.parent());
|
||||
while let Some(pe) = p {
|
||||
let pt = transform_of(w.get(pe, "Transform"));
|
||||
t = compose(&pt, &t);
|
||||
p = w.w.get::<ChildOf>(pe).map(|c| c.parent());
|
||||
}
|
||||
out.push(json!({"id": id, "kind": "Mesh", "mesh": mesh, "position": [t[0], t[1], t[2]], "rotation": [t[3], t[4], t[5]], "scale": t[6]}));
|
||||
}
|
||||
for id in w.find(&["Light".into()], &[]) {
|
||||
out.push(json!({"id": id, "kind": "Light", "light": w.get(w.ids[&id], "Light").cloned().unwrap_or(Value::Null)}));
|
||||
}
|
||||
Ok(Value::Array(out))
|
||||
}),
|
||||
o => Err(format!("no native call {o}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// [x, y, z, rx, ry, rz, scale] from a Transform component ({x, y, z, rx, ry, rz, scale}, all optional).
|
||||
fn transform_of(t: Option<&Value>) -> [f64; 7] {
|
||||
let g = |k: &str, d: f64| t.and_then(|t| t.get(k)).and_then(Value::as_f64).unwrap_or(d);
|
||||
[g("x", 0.0), g("y", 0.0), g("z", 0.0), g("rx", 0.0), g("ry", 0.0), g("rz", 0.0), g("scale", 1.0)]
|
||||
}
|
||||
|
||||
/// A child's transform in its parent's space, made world space (rotation by z, then y, then x; uniform scale).
|
||||
fn compose(parent: &[f64; 7], child: &[f64; 7]) -> [f64; 7] {
|
||||
let (sx, cx) = parent[3].sin_cos();
|
||||
let (sy, cy) = parent[4].sin_cos();
|
||||
let (sz, cz) = parent[5].sin_cos();
|
||||
let (mut x, mut y, mut z) = (child[0] * parent[6], child[1] * parent[6], child[2] * parent[6]);
|
||||
// z
|
||||
let (x1, y1) = (x * cz - y * sz, x * sz + y * cz);
|
||||
x = x1;
|
||||
y = y1;
|
||||
// y
|
||||
let (x2, z2) = (x * cy + z * sy, -x * sy + z * cy);
|
||||
x = x2;
|
||||
z = z2;
|
||||
// x
|
||||
let (y3, z3) = (y * cx - z * sx, y * sx + z * cx);
|
||||
y = y3;
|
||||
z = z3;
|
||||
[parent[0] + x, parent[1] + y, parent[2] + z, parent[3] + child[3], parent[4] + child[4], parent[5] + child[5], parent[6] * child[6]]
|
||||
}
|
||||
|
||||
/// The ecs.* names with their TypeScript types, for the registry.
|
||||
pub const CALLS: &[(&str, &str, &str, &str)] = &[
|
||||
("ecs.new", "{}", "{ world: number }", "a new world (Bevy's)"),
|
||||
("ecs.clone", "{ world: number }", "{ world: number }", "a copy of a world"),
|
||||
("ecs.free", "{ world: number }", "null", "drop a world"),
|
||||
("ecs.spawn", "{ world: number; kind?: string; cols?: Record<string, number | string | boolean>; components?: Record<string, unknown>; parent?: number }", "{ id: number }", "a new entity: a kind with columns, and/or any components"),
|
||||
("ecs.set", "{ world: number; id: number; cols: Record<string, number | string | boolean> }", "null", "columns merged into an entity's kind"),
|
||||
("ecs.get", "{ world: number; id: number }", "{ id: number; kind: string } & Record<string, number | string | boolean>", "an entity's row (its kind's columns)"),
|
||||
("ecs.despawn", "{ world: number; id: number }", "null", "remove an entity and its children"),
|
||||
("ecs.insert", "{ world: number; id: number; components: Record<string, unknown> }", "null", "components added to (or replaced on) an entity"),
|
||||
("ecs.remove", "{ world: number; id: number; names: string[] }", "null", "components taken off an entity"),
|
||||
("ecs.components", "{ world: number; id: number }", "Record<string, unknown>", "an entity's components by name"),
|
||||
("ecs.find", "{ world: number; with?: string[]; without?: string[]; where?: [string, \"==\" | \"!=\" | \"<\" | \"<=\" | \">\" | \">=\", number | string | boolean][]; rows?: boolean }", "{ ids: number[]; rows?: { id: number; components: Record<string, unknown> }[] }", "entities with every `with` component and no `without` one (Bevy's query), passing every condition (\"Comp.field\")"),
|
||||
("ecs.query", "{ world: number; kind: string; where: [string, \"==\" | \"!=\" | \"<\" | \"<=\" | \">\" | \">=\", number | string | boolean][] }", "{ ids: number[] }", "ids of kind's entities passing every condition"),
|
||||
("ecs.column", "{ world: number; kind: string; col: string }", "(number | null)[]", "one numeric column of a kind, in id order"),
|
||||
("ecs.count", "{ world: number; kind: string }", "number", "how many entities of a kind"),
|
||||
("ecs.rows", "{ world: number }", "({ id: number; kind: string } & Record<string, number | string | boolean>)[]", "every kind's rows, by kind then id"),
|
||||
("ecs.parent", "{ world: number; id: number; parent?: number | null }", "number | null", "an entity's parent (set it with parent; null clears it)"),
|
||||
("ecs.children", "{ world: number; id: number }", "number[]", "an entity's children"),
|
||||
("ecs.resource", "{ world: number; name: string; value?: unknown }", "unknown", "a resource (set it with value)"),
|
||||
("ecs.send", "{ world: number; name: string; value?: unknown }", "null", "an event for this frame"),
|
||||
("ecs.events", "{ world: number; name: string }", "unknown[]", "this frame's events of a name"),
|
||||
("ecs.clear_events", "{ world: number }", "null", "the frame's events cleared (each step starts with none)"),
|
||||
("ecs.scene", "{ world: number }", "{ id: number; kind: \"Mesh\" | \"Light\"; mesh?: unknown; light?: unknown; position?: [number, number, number]; rotation?: [number, number, number]; scale?: number }[]", "the world's Mesh+Transform entities (world space) and lights, to draw"),
|
||||
];
|
||||
|
||||
/// How many worlds are alive (media.live's leak check).
|
||||
pub fn live() -> usize {
|
||||
WORLDS.with(|ws| ws.borrow().1.len())
|
||||
}
|
||||
@@ -167,9 +167,9 @@ pub fn live_scene(world: &mut World, ls: &mut LiveScene, engine: &mut Option<rae
|
||||
None => {
|
||||
let clear = scene_clear(world);
|
||||
let p = ls.open(Shot { scene: &scene, clear: clear.as_deref() }, size.0, size.1, fps);
|
||||
let mut e = aov_on(raea_render::engine::Engine::new_live(&p, &raea_render::inserted_of(&p), dir).map_err(|e| format!("the 3D didn't open: {e}"))?);
|
||||
let e = raea_render::engine::Engine::open_in(engine, &p, dir).map_err(|e| format!("the 3D didn't open: {e}"))?;
|
||||
aov_on(e);
|
||||
e.set_rows(&[])?;
|
||||
*engine = Some(e);
|
||||
}
|
||||
Some(e) => {
|
||||
// the frame's own clear, keyed as a render keys a background that changes (RR1)
|
||||
@@ -268,7 +268,7 @@ pub(crate) fn render_fed(app: &mut App, js: &Path, w: u32, h: u32, fps: f64, tot
|
||||
if programmed && !restepped && raea_runtime_page::VIEW_BOX.lock().unwrap().is_some() {
|
||||
restepped = true;
|
||||
if let Some(p) = scene_program_checked(js, &dir, total, Some(wanted))? {
|
||||
cx.scene3d = Some(raea_render::engine::Engine::new_live(&p, &raea_render::inserted_of(&p), &dir)?);
|
||||
aov_on(raea_render::engine::Engine::open_in(&mut cx.scene3d, &p, &dir)?);
|
||||
if let Some(m) = cx.manifest.as_mut() {
|
||||
m.pop();
|
||||
}
|
||||
|
||||
@@ -198,9 +198,9 @@ const LIVE_PAST: i64 = 3600;
|
||||
/// raea-render program drawn by raea-render into `out` (.mp4, .png for one frame, a folder of PNGs). `dir` is where relative media resolves. `wanted`: the frames (all when None).
|
||||
pub fn render_bundle(js: &Path, dir: &Path, out: &Path, wanted: Option<Vec<i64>>) -> R<String> {
|
||||
// stills of a 3D scene: its engine opened live beside the page (as the fed path opens it), the page laid over each
|
||||
// frame's 3D and each <Screen> painted from the page's own picture of it
|
||||
// frame's 3D and each <Screen> painted from the page's own picture of it. A .png with no --frame is frame 0, drawn as --frame 0 draws it: the frames path gave a camera in a page element (an <R3F> in a box) the whole frame's view (#261)
|
||||
let ext = out_ext(out);
|
||||
let stills = (ext == "png" && wanted.as_ref().is_some_and(|w| w.len() == 1)) || ext.is_empty();
|
||||
let stills = (ext == "png" && wanted.as_ref().is_none_or(|w| w.len() == 1)) || ext.is_empty();
|
||||
let how = std::env::var_os("RAEA_3D").and_then(|v| v.into_string().ok()).unwrap_or_default();
|
||||
// a game: its 3D made frame by frame as it's stepped (rows made beforehand hold every frame's scene: a 10-minute
|
||||
// game took 24 GB before its first frame); RAEA_3D=live or =program chooses
|
||||
@@ -210,16 +210,16 @@ pub fn render_bundle(js: &Path, dir: &Path, out: &Path, wanted: Option<Vec<i64>>
|
||||
return render_bundle_with(js, dir, out, wanted, video, None, true);
|
||||
}
|
||||
if stills && how != "files" {
|
||||
let upto = wanted.as_ref().and_then(|w| w.iter().max()).map_or(0, |f| f + 1);
|
||||
// a still far into a 3D piece: its 3D made live at the still, as a game's is. The rows made beforehand hold a
|
||||
// scene for every frame up to it: raea check --quick's three stills of a 13,175-frame film took 10.4 GB that
|
||||
// way and 0.8 GB live, the same pixels as the film's (SG4a)
|
||||
if how != "program" && upto > LIVE_PAST && raea_runtime_view::gpuview::paint_device().is_some() && wanted.as_deref().is_some_and(|w| crate::fed::stills_live(js, dir, w).unwrap_or(false)) {
|
||||
let still = if ext == "png" && wanted.is_none() { Some(vec![0]) } else { wanted.clone() };
|
||||
let upto = still.as_ref().and_then(|w| w.iter().max()).map_or(0, |f| f + 1);
|
||||
// a still far into a 3D piece: its 3D made live at the still, as a game's is. The rows made beforehand hold a scene for every frame up to it:
|
||||
// raea check --quick's three stills of a 13,175-frame film took 10.4 GB that way and 0.8 GB live, the same pixels as the film's (SG4a)
|
||||
if how != "program" && upto > LIVE_PAST && raea_runtime_view::gpuview::paint_device().is_some() && still.as_deref().is_some_and(|w| crate::fed::stills_live(js, dir, w).unwrap_or(false)) {
|
||||
raea_runtime_react::startup_mark("stills past the rows' reach: the 3D made live at each");
|
||||
return render_bundle_with(js, dir, out, wanted, false, None, true);
|
||||
return render_bundle_with(js, dir, out, still, false, None, true);
|
||||
}
|
||||
if let Some(scene) = scene_program_checked(js, dir, upto, wanted.as_deref())? {
|
||||
return render_bundle_with(js, dir, out, wanted, false, Some(scene), false);
|
||||
if let Some(scene) = scene_program_checked(js, dir, upto, still.as_deref())? {
|
||||
return render_bundle_with(js, dir, out, still, false, Some(scene), false);
|
||||
}
|
||||
}
|
||||
// a video: fed, its pages handed to the encoder on the GPU (B1d), until a frame holds 3D, which starts it again
|
||||
@@ -299,7 +299,7 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Opti
|
||||
let mut cx = Ctx { dir, work: &work, sounds: Vec::new(), scene: Vec::new(), clear: None, marker: None, mix: None, audible: HashMap::new(), brand: page_css(dir, w, js), manifest: MANIFEST.lock().unwrap().as_ref().map(|_| Vec::new()), now: 0, said: Default::default(), made: HashMap::new(), scene3d: None, live3d: None };
|
||||
if fed {
|
||||
if let Some(p) = scene {
|
||||
cx.scene3d = Some(aov_on(raea_render::engine::Engine::new_live(&p, &raea_render::inserted_of(&p), dir)?));
|
||||
aov_on(raea_render::engine::Engine::open_in(&mut cx.scene3d, &p, dir)?);
|
||||
raea_runtime_react::startup_mark("the 3D's engine open");
|
||||
}
|
||||
if live3d {
|
||||
@@ -312,7 +312,7 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Opti
|
||||
let programmed = scene.is_some();
|
||||
match scene {
|
||||
Some(p) => {
|
||||
cx.scene3d = Some(aov_on(raea_render::engine::Engine::new_live(&p, &raea_render::inserted_of(&p), dir)?));
|
||||
aov_on(raea_render::engine::Engine::open_in(&mut cx.scene3d, &p, dir)?);
|
||||
raea_runtime_react::startup_mark("the 3D's engine open");
|
||||
}
|
||||
None => cx.live3d = Some(LiveScene::default()),
|
||||
@@ -337,7 +337,7 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Opti
|
||||
if i == 0 && programmed && raea_runtime_page::VIEW_BOX.lock().unwrap().is_some() {
|
||||
let upto = wanted.iter().max().map_or(0, |m| m + 1);
|
||||
if let Some(p) = scene_program_checked(js, dir, upto, Some(&wanted))? {
|
||||
cx.scene3d = Some(aov_on(raea_render::engine::Engine::new_live(&p, &raea_render::inserted_of(&p), dir)?));
|
||||
aov_on(raea_render::engine::Engine::open_in(&mut cx.scene3d, &p, dir)?);
|
||||
px = bevy_over_3d(app.world_mut(), pg, &mut cx, fps)?;
|
||||
}
|
||||
}
|
||||
@@ -442,11 +442,10 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Opti
|
||||
}
|
||||
|
||||
/// An engine for the scene path, drawing the guide data when `--aov` asked for it.
|
||||
pub(crate) fn aov_on(mut e: raea_render::engine::Engine) -> raea_render::engine::Engine {
|
||||
pub(crate) fn aov_on(e: &mut raea_render::engine::Engine) {
|
||||
if AOV.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
e.want_aov();
|
||||
}
|
||||
e
|
||||
}
|
||||
|
||||
/// Frame i's guide data (RT1) as mlxdlss run-sequence reads it: DIR/motion/frame-NNNNN.f32 (H x W x 2 float32) and
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "raea-runtime-goal-plan"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "A goal job held to its rules: commands that must pass, and words a fresh critic must find true after the work's last change (make: goal({...}), /goal)"
|
||||
|
||||
[dependencies]
|
||||
# the contract: `make: goal({...})` on brief.ts
|
||||
raea-core-brief = { path = "../../core/brief" }
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,205 @@
|
||||
//! A goal job's gates (`make: goal({...})` on brief.ts, core/brief goal.rs): the person's goal held as rules, from what's
|
||||
//! on disk and what a fresh critic said, never from the agent that did the work. `/goal` in raea.app and an agent's own
|
||||
//! goal are this one loop (11-26, Shane: "it can't stop unless all the goals pass").
|
||||
//! run the command exits 0 in the brief's folder, within its timeout (run again at every status)
|
||||
//! file the file exists: a deliverable, so `raea make status` lists it under missing, not here
|
||||
//! says a fresh critic (`raea make judge`) found it true of the work, after the work's last change
|
||||
//! The critic's verdict is review/goal.judge.json: {at, by, rules: {ID: {pass, why}}}.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant, SystemTime};
|
||||
|
||||
use raea_core_brief::goal::Goal;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// One gate as `raea make status` lists it (a cut's are the same kind): `of` is the rule it's about
|
||||
pub use raea_core_brief::make::Gate;
|
||||
|
||||
fn gate(name: &'static str, of: &str, clear: bool, says: String) -> Gate {
|
||||
Gate { name, of: Some(of.to_string()), clear, says }
|
||||
}
|
||||
|
||||
/// Where the critic's verdict is kept, beside the brief.
|
||||
pub const VERDICT: &str = "review/goal.judge.json";
|
||||
/// The seconds a `run` rule gets when it names none.
|
||||
pub const TIMEOUT: u32 = 300;
|
||||
|
||||
/// Folders that aren't the work: what the job writes about itself, and what tools keep.
|
||||
const NOT_WORK: [&str; 7] = ["review", ".git", "node_modules", ".raea", "target", ".cache", ".raea-cloud"];
|
||||
|
||||
/// When the work last changed: the newest file under DIR, its own bookkeeping left out (a bounded walk).
|
||||
pub fn newest(dir: &Path) -> Option<SystemTime> {
|
||||
let mut best: Option<SystemTime> = None;
|
||||
let mut stack = vec![dir.to_path_buf()];
|
||||
let mut seen = 0usize;
|
||||
while let Some(d) = stack.pop() {
|
||||
for e in std::fs::read_dir(&d).into_iter().flatten().flatten() {
|
||||
seen += 1;
|
||||
if seen > 20_000 {
|
||||
return best;
|
||||
}
|
||||
let p = e.path();
|
||||
let name = e.file_name().to_string_lossy().to_string();
|
||||
let Ok(t) = e.file_type() else { continue };
|
||||
if t.is_dir() {
|
||||
if !(d == dir && NOT_WORK.contains(&name.as_str())) && name != "node_modules" && name != ".git" {
|
||||
stack.push(p);
|
||||
}
|
||||
} else if t.is_file() && name != "NOTES.md" {
|
||||
if let Ok(m) = e.metadata().and_then(|m| m.modified()) {
|
||||
best = Some(best.map_or(m, |b| b.max(m)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// A command run in DIR through the system shell, stopped at its timeout: (passed, its last words).
|
||||
pub fn run(cmd: &str, dir: &Path, secs: u32) -> (bool, String) {
|
||||
let mut c = if cfg!(windows) {
|
||||
let mut c = std::process::Command::new("cmd");
|
||||
c.args(["/C", cmd]);
|
||||
c
|
||||
} else {
|
||||
let mut c = std::process::Command::new("sh");
|
||||
c.args(["-c", cmd]);
|
||||
c
|
||||
};
|
||||
let out = std::env::temp_dir().join(format!("raea-goal-{}-{}.log", std::process::id(), Instant::now().elapsed().as_nanos()));
|
||||
let Ok(log) = std::fs::File::create(&out) else { return (false, "couldn't make a log file for it".into()) };
|
||||
let Ok(err) = log.try_clone() else { return (false, "couldn't make a log file for it".into()) };
|
||||
let child = c.current_dir(dir).stdin(std::process::Stdio::null()).stdout(log).stderr(err).spawn();
|
||||
let mut child = match child {
|
||||
Ok(ch) => ch,
|
||||
Err(e) => return (false, format!("couldn't start it: {e}")),
|
||||
};
|
||||
let until = Instant::now() + Duration::from_secs(secs as u64);
|
||||
let status = loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(s)) => break Some(s),
|
||||
Ok(None) if Instant::now() >= until => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
break None;
|
||||
}
|
||||
Ok(None) => std::thread::sleep(Duration::from_millis(100)),
|
||||
Err(_) => break None,
|
||||
}
|
||||
};
|
||||
let text = std::fs::read_to_string(&out).unwrap_or_default();
|
||||
let _ = std::fs::remove_file(&out);
|
||||
let last = text.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("").trim();
|
||||
let last: String = last.chars().take(200).collect();
|
||||
match status {
|
||||
Some(s) if s.success() => (true, "passes".into()),
|
||||
Some(s) => (false, format!("exits {}{}", s.code().map_or("by a signal".into(), |c| c.to_string()), if last.is_empty() { String::new() } else { format!(": {last}") })),
|
||||
None => (false, format!("still running after {secs} s: stopped (give the rule a longer `timeout`, or make it quicker)")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The critic's verdict, when there is one.
|
||||
pub fn verdict(dir: &Path) -> Option<Value> {
|
||||
serde_json::from_str(&std::fs::read_to_string(dir.join(VERDICT)).ok()?).ok()
|
||||
}
|
||||
|
||||
/// Every rule's gate but `file` rules (deliverables: status lists them as missing).
|
||||
pub fn gates(g: &Goal, dir: &Path) -> Vec<Gate> {
|
||||
let says: Vec<_> = g.rules.iter().filter(|r| r.says.is_some()).collect();
|
||||
let v = if says.is_empty() { None } else { verdict(dir) };
|
||||
let judged = v.as_ref().and_then(|v| v["at"].as_u64()).map(|s| SystemTime::UNIX_EPOCH + Duration::from_secs(s));
|
||||
let changed = if says.is_empty() { None } else { newest(dir) };
|
||||
// at whole seconds, as the verdict keeps its time: work saved in the second the critic was asked counts as judged
|
||||
let secs = |t: SystemTime| t.duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
|
||||
let fresh = match (judged, changed) {
|
||||
(Some(j), Some(c)) => secs(j) >= secs(c),
|
||||
(Some(_), None) => true,
|
||||
_ => false,
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for r in &g.rules {
|
||||
if let Some(cmd) = &r.run {
|
||||
let (ok, said) = run(cmd, dir, r.timeout.unwrap_or(TIMEOUT));
|
||||
out.push(gate("run", &r.id, ok, if ok { format!("`{cmd}` passes") } else { format!("`{cmd}` {said}") }));
|
||||
} else if r.says.is_some() {
|
||||
let one = v.as_ref().map(|v| &v["rules"][&r.id]);
|
||||
let (clear, said) = match one {
|
||||
None => (false, "not judged yet: raea make judge".to_string()),
|
||||
Some(Value::Null) => (false, "the last judging didn't cover it: raea make judge".to_string()),
|
||||
Some(_) if !fresh => (false, "the work changed after the critic judged it: raea make judge again".to_string()),
|
||||
Some(x) if x["pass"] == true => (true, format!("a fresh critic found it true: {}", x["why"].as_str().unwrap_or(""))),
|
||||
Some(x) => (false, format!("a fresh critic found it not true yet: {}", x["why"].as_str().unwrap_or(""))),
|
||||
};
|
||||
out.push(gate("says", &r.id, clear, said));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// What the critic is asked: the goal, each `says` rule by id, and the answer's shape. It reads; it changes nothing.
|
||||
pub fn prompt(g: &Goal, dir: &Path) -> String {
|
||||
let rules: Vec<String> = g.rules.iter().filter_map(|r| r.says.as_ref().map(|s| format!("- {}: {s}", r.id))).collect();
|
||||
format!(
|
||||
"You are a fresh critic. You did none of this work and owe it nothing. The work is in {d}: read whatever you need \
|
||||
there (its files, its renders, NOTES.md), and change nothing.\n\nThe goal, as the person said it: {goal}\n\nFor each rule \
|
||||
below, decide whether it is true of the work as it is on disk now. Count it true only when you have seen it hold; if you \
|
||||
can't tell, it isn't true yet. Say why in one sentence, naming what you looked at.\n\n{rules}\n\nAnswer last with one JSON \
|
||||
object and nothing after it: {{\"rules\": {{\"ID\": {{\"pass\": true, \"why\": \"...\"}}}}}}",
|
||||
d = dir.display(),
|
||||
goal = g.goal,
|
||||
rules = rules.join("\n")
|
||||
)
|
||||
}
|
||||
|
||||
/// The verdict: the object around the text's last `"rules"` key (a critic may think aloud, or quote the shape, first).
|
||||
pub fn last_verdict(text: &str) -> Option<Value> {
|
||||
let key = text.rfind("\"rules\"")?;
|
||||
// the nearest brace before the key opens the verdict
|
||||
let open = text[..key].rfind('{')?;
|
||||
let v: Value = serde_json::Deserializer::from_str(&text[open..]).into_iter::<Value>().next()?.ok()?;
|
||||
v["rules"].is_object().then_some(v)
|
||||
}
|
||||
|
||||
/// The critics `raea make judge` can ask, each a fresh session that may only read.
|
||||
pub const BY: [&str; 2] = ["claude", "kimi"];
|
||||
|
||||
/// One fresh critic over the goal's `says` rules: its verdict kept at review/goal.judge.json, stamped with when it was
|
||||
/// asked (so work changed while it judged counts as changed after). Returns the verdict.
|
||||
pub fn judge(g: &Goal, dir: &Path, by: &str) -> Result<Value, String> {
|
||||
if !g.rules.iter().any(|r| r.says.is_some()) {
|
||||
return Err("raea make judge: the goal has no `says` rules; its `run` and `file` rules are checked by raea make status".into());
|
||||
}
|
||||
let asked = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
|
||||
let p = prompt(g, dir);
|
||||
let mut cmd = match by {
|
||||
"claude" => {
|
||||
let mut c = std::process::Command::new("claude");
|
||||
c.args(["-p", &p, "--allowedTools", "Read Grep Glob", "--output-format", "json"]);
|
||||
c
|
||||
}
|
||||
"kimi" => {
|
||||
let mut c = std::process::Command::new("kimi");
|
||||
c.args(["-p", &p]);
|
||||
c
|
||||
}
|
||||
o => return Err(format!("raea make judge: --by {o}: the critics are {}", BY.join(", "))),
|
||||
};
|
||||
let out = cmd.current_dir(dir).stdin(std::process::Stdio::null()).output().map_err(|e| format!("raea make judge: couldn't run {by}: {e} (is its CLI installed and signed in?)"))?;
|
||||
let text = String::from_utf8_lossy(&out.stdout).to_string();
|
||||
// claude's json output is {result: "..."}; kimi's is the words
|
||||
let words = serde_json::from_str::<Value>(&text).ok().and_then(|v| v["result"].as_str().map(String::from)).unwrap_or(text);
|
||||
let tail = &words[words.floor_char_boundary(words.len().saturating_sub(300))..];
|
||||
let mut v = last_verdict(&words).ok_or_else(|| format!("raea make judge: {by} answered no verdict: {}", tail.trim()))?;
|
||||
v["at"] = json!(asked);
|
||||
v["by"] = json!(by);
|
||||
v["goal"] = json!(g.goal);
|
||||
let file: PathBuf = dir.join(VERDICT);
|
||||
if let Some(parent) = file.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("raea make judge: {}: {e}", parent.display()))?;
|
||||
}
|
||||
std::fs::write(&file, serde_json::to_string_pretty(&v).unwrap_or_default()).map_err(|e| format!("raea make judge: {}: {e}", file.display()))?;
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,84 @@
|
||||
use super::*;
|
||||
use raea_core_brief::goal::{Goal, GoalRule};
|
||||
|
||||
fn rule(id: &str) -> GoalRule {
|
||||
GoalRule { id: id.into(), run: None, timeout: None, file: None, says: None }
|
||||
}
|
||||
|
||||
fn tmp(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("raea-goal-plan-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_command_passes_or_says_why() {
|
||||
let d = tmp("run");
|
||||
let g = Goal { goal: "tests pass".into(), rules: vec![GoalRule { run: Some("true".into()), ..rule("ok") }, GoalRule { run: Some("echo broke; exit 3".into()), ..rule("bad") }] };
|
||||
let gs = gates(&g, &d);
|
||||
assert_eq!(gs.len(), 2);
|
||||
assert!(gs[0].clear, "{gs:?}");
|
||||
assert!(!gs[1].clear);
|
||||
assert!(gs[1].says.contains("exits 3") && gs[1].says.contains("broke"), "{}", gs[1].says);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_command_past_its_timeout_fails() {
|
||||
let d = tmp("slow");
|
||||
let (ok, said) = run("sleep 5", &d, 1);
|
||||
assert!(!ok);
|
||||
assert!(said.contains("still running after 1 s"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn words_need_a_fresh_critic() {
|
||||
let d = tmp("says");
|
||||
std::fs::write(d.join("work.txt"), "the work").unwrap();
|
||||
let g = Goal { goal: "a friendly reply".into(), rules: vec![GoalRule { says: Some("the reply is friendly".into()), ..rule("friendly") }] };
|
||||
// never judged
|
||||
let gs = gates(&g, &d);
|
||||
assert!(!gs[0].clear && gs[0].says.contains("raea make judge"), "{gs:?}");
|
||||
// judged after the work, and found true
|
||||
let later = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() + 5;
|
||||
std::fs::create_dir_all(d.join("review")).unwrap();
|
||||
let v = json!({"at": later, "by": "claude", "rules": {"friendly": {"pass": true, "why": "it says hello warmly"}}});
|
||||
std::fs::write(d.join(VERDICT), v.to_string()).unwrap();
|
||||
assert!(gates(&g, &d)[0].clear);
|
||||
// the critic's own file doesn't count as the work changing
|
||||
assert!(newest(&d).unwrap() < SystemTime::UNIX_EPOCH + Duration::from_secs(later));
|
||||
// judged before the work changed: stale
|
||||
let earlier = json!({"at": 1, "rules": {"friendly": {"pass": true, "why": ""}}});
|
||||
std::fs::write(d.join(VERDICT), earlier.to_string()).unwrap();
|
||||
let gs = gates(&g, &d);
|
||||
assert!(!gs[0].clear && gs[0].says.contains("changed after"), "{gs:?}");
|
||||
// judged and found not true
|
||||
let no = json!({"at": later, "rules": {"friendly": {"pass": false, "why": "it is curt"}}});
|
||||
std::fs::write(d.join(VERDICT), no.to_string()).unwrap();
|
||||
let gs = gates(&g, &d);
|
||||
assert!(!gs[0].clear && gs[0].says.contains("it is curt"), "{gs:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_rules_are_left_to_the_deliverables() {
|
||||
let d = tmp("file");
|
||||
let g = Goal { goal: "an export".into(), rules: vec![GoalRule { file: Some("out/final.mp4".into()), ..rule("export") }] };
|
||||
assert!(gates(&g, &d).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_verdict_is_the_last_json_with_rules() {
|
||||
let t = "the shape is {\"rules\": {\"ID\": ...}} so: {\"x\": 1} then {\"rules\": {\"a\": {\"pass\": true, \"why\": \"seen\"}}}";
|
||||
assert_eq!(last_verdict(t).unwrap()["rules"]["a"]["pass"], true);
|
||||
assert!(last_verdict("no json here").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_rules_are_doctored() {
|
||||
let g = Goal { goal: "".into(), rules: vec![GoalRule { run: Some("x".into()), says: Some("y".into()), ..rule("Two") }, rule("two")] };
|
||||
let d = raea_core_brief::goal::doctor(&g);
|
||||
assert!(d.iter().any(|l| l.contains("no `goal`")), "{d:?}");
|
||||
assert!(d.iter().any(|l| l.contains("`Two`: ids are")), "{d:?}");
|
||||
assert!(d.iter().any(|l| l.contains("exactly one") && l.contains("it has 2")), "{d:?}");
|
||||
assert!(d.iter().any(|l| l.contains("`two` needs exactly one") && l.contains("it has 0")), "{d:?}");
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "raea-runtime-kinds"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "A 3D scene's rows for the kinds placed as a whole: glTF models, panels, decals, plates, fog volumes, fires, Gaussian splats, mesh sequences and fields of grass"
|
||||
|
||||
[dependencies]
|
||||
raea-core-scene = { path = "../../core/scene" }
|
||||
raea-core-program = { path = "../../core/program" }
|
||||
raea-runtime-look = { path = "../look" }
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
|
||||
serde_json = "1"
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(super) fn rows(tracks: &[Track], p: &mut Program) {
|
||||
pub fn rows(tracks: &[Track], p: &mut Program) {
|
||||
for (k, (_, track)) in tracks.iter().enumerate() {
|
||||
let its = filled(track);
|
||||
let first = &its[0].props;
|
||||
@@ -0,0 +1,51 @@
|
||||
//! A 3D scene's rows for the kinds placed as a whole: glTF models, panels, decals, plates, fog volumes, fires, Gaussian
|
||||
//! splats, mesh sequences and fields of grass. raea-runtime-scene walks the scene into each kind's tracks and builds the
|
||||
//! rest (meshes, lights, text, the camera); a part's placement and name columns are shared by both.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use raea_core_program::ir::{Program, V};
|
||||
use raea_core_scene::*;
|
||||
use raea_runtime_look::*;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
/// One part's frames, by its key: the part as each frame has it, or none where it isn't there.
|
||||
pub type Track = (String, Vec<Option<Item>>);
|
||||
|
||||
mod models;
|
||||
pub use models::*;
|
||||
/// Gaussian splats' rows (<Splat>).
|
||||
pub mod splat;
|
||||
/// Baked simulations' and glitches' rows (<MeshSequence>, <Goo>, glitch props).
|
||||
pub mod meshseq;
|
||||
/// Fields of grass' rows (<Grass>).
|
||||
pub mod grass;
|
||||
|
||||
/// A part's SDK name as its row's `name` column: what a Bevy Entity field (a ChildOf's parent) names it by.
|
||||
pub fn name_column(row: &mut BTreeMap<String, V>, props: &Map<String, Value>) {
|
||||
if let Some(Value::String(n)) = props.get("name") {
|
||||
row.insert("name".into(), V::S(n.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
/// World position, rotation (Bevy's quaternion, q_x q_y q_z q_w: no Euler round trip, docs/control.feature FC1d) and
|
||||
/// scale of each frame; each frame's quaternion takes the sign nearer the frame before's, so keys turn the short way.
|
||||
pub fn placement(p: &mut Program, row: &mut BTreeMap<String, V>, id: &str, its: &[Item]) {
|
||||
let mut prev = bevy::math::Quat::IDENTITY;
|
||||
let per: Vec<[f64; 10]> = its.iter().map(|it| {
|
||||
let (s, q, t) = it.world.to_scale_rotation_translation();
|
||||
// a zero scale has no rotation (it comes out NaN, keyed on every frame since NaN never equals itself): the one before
|
||||
let q = if q.is_finite() { q } else { prev };
|
||||
prev = if q.dot(prev) < 0.0 { -q } else { q };
|
||||
[t.x as f64, t.y as f64, t.z as f64, prev.x as f64, prev.y as f64, prev.z as f64, prev.w as f64, s.x as f64, s.y as f64, s.z as f64]
|
||||
}).collect();
|
||||
for (k, name) in ["x", "y", "z", "q_x", "q_y", "q_z", "q_w"].iter().enumerate() {
|
||||
exact(p, row, id, name, &per.iter().map(|t| t[k]).collect::<Vec<_>>());
|
||||
}
|
||||
let sc: Vec<[f64; 3]> = per.iter().map(|t| [t[7], t[8], t[9]]).collect();
|
||||
if sc.iter().any(|s| s.iter().any(|v| (v - 1.0).abs() > 1e-9)) {
|
||||
for (k, name) in ["scale_x", "scale_y", "scale_z"].iter().enumerate() {
|
||||
exact(p, row, id, name, &sc.iter().map(|s| s[k]).collect::<Vec<_>>());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,7 @@ pub(super) fn cloth_columns(p: &mut Program, row: &mut BTreeMap<String, V>, id:
|
||||
/// Numeric props of a sequence and the columns they key (the default when a frame leaves one out).
|
||||
const KEYED: &[(&str, &str, f64)] = &[("frame", "frame", 0.0), ("roughness", "rough", 0.3), ("metalness", "metal", 0.0)];
|
||||
|
||||
pub(super) fn rows(tracks: &[Track], p: &mut Program) {
|
||||
pub fn rows(tracks: &[Track], p: &mut Program) {
|
||||
for (k, (_, track)) in tracks.iter().enumerate() {
|
||||
let its = filled(track);
|
||||
let id = format!("meshseq{k}");
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::*;
|
||||
|
||||
/// glTF models: the file, its clip and the clip's time (keyed: the component works it out from the frame)
|
||||
pub(crate) fn models_rows(tr: &Tracks, names: &[String], p: &mut Program) {
|
||||
for (k, (_, track)) in tr.models.iter().enumerate() {
|
||||
pub fn models_rows(tracks: &[Track], names: &[String], p: &mut Program) {
|
||||
for (k, (_, track)) in tracks.iter().enumerate() {
|
||||
let its = filled(&track);
|
||||
let id = format!("model{k}");
|
||||
let mut row = BTreeMap::new();
|
||||
@@ -64,7 +64,7 @@ pub(crate) fn models_rows(tr: &Tracks, names: &[String], p: &mut Program) {
|
||||
// attached to another model's bone: that model's row by its name
|
||||
if let Some(a) = first.get("attach") {
|
||||
let to = a.get("to").and_then(Value::as_str).unwrap_or("");
|
||||
if let Some(j) = tr.models.iter().position(|(_, t)| t.iter().flatten().next().and_then(|i| i.props.get("name")).and_then(Value::as_str) == Some(to)) {
|
||||
if let Some(j) = tracks.iter().position(|(_, t)| t.iter().flatten().next().and_then(|i| i.props.get("name")).and_then(Value::as_str) == Some(to)) {
|
||||
row.insert("attach_to".into(), V::S(format!("model{j}")));
|
||||
row.insert("attach_bone".into(), V::S(a.get("bone").and_then(Value::as_str).unwrap_or("").into()));
|
||||
} else {
|
||||
@@ -76,7 +76,7 @@ pub(crate) fn models_rows(tr: &Tracks, names: &[String], p: &mut Program) {
|
||||
let (mut joints, mut rows) = (Vec::new(), Vec::new());
|
||||
for (joint, to) in b {
|
||||
let to = to.as_str().unwrap_or("");
|
||||
match tr.models.iter().position(|(_, t)| t.iter().flatten().next().and_then(|i| i.props.get("name")).and_then(Value::as_str) == Some(to)) {
|
||||
match tracks.iter().position(|(_, t)| t.iter().flatten().next().and_then(|i| i.props.get("name")).and_then(Value::as_str) == Some(to)) {
|
||||
Some(j) => {
|
||||
joints.push(joint.clone());
|
||||
rows.push(format!("model{j}"));
|
||||
@@ -140,8 +140,8 @@ pub(crate) fn models_rows(tr: &Tracks, names: &[String], p: &mut Program) {
|
||||
}
|
||||
|
||||
/// pictures in space (raea-render's panel: unlit, painted once, moved by the GPU)
|
||||
pub(crate) fn panels_rows(tr: &Tracks, names: &[String], p: &mut Program) {
|
||||
for (k, (_, track)) in tr.panels.iter().enumerate() {
|
||||
pub fn panels_rows(tracks: &[Track], names: &[String], p: &mut Program) {
|
||||
for (k, (_, track)) in tracks.iter().enumerate() {
|
||||
let its = filled(&track);
|
||||
let id = format!("plane{k}");
|
||||
let mut row = BTreeMap::new();
|
||||
@@ -177,8 +177,8 @@ pub(crate) fn panels_rows(tr: &Tracks, names: &[String], p: &mut Program) {
|
||||
|
||||
/// decals: the picture and its surface from the first frame; placement, colour and opacity keyed (a stain that
|
||||
/// spreads, a label that fades in)
|
||||
pub(crate) fn decals_rows(tr: &Tracks, p: &mut Program) {
|
||||
for (k, (_, track)) in tr.decals.iter().enumerate() {
|
||||
pub fn decals_rows(tracks: &[Track], p: &mut Program) {
|
||||
for (k, (_, track)) in tracks.iter().enumerate() {
|
||||
let its = filled(&track);
|
||||
let id = format!("decal{k}");
|
||||
let mut row = BTreeMap::new();
|
||||
@@ -205,8 +205,8 @@ pub(crate) fn decals_rows(tr: &Tracks, p: &mut Program) {
|
||||
|
||||
/// footage behind the 3D (raea-render's plate: a video frame per frame on the camera's far plane, unlit): its source time
|
||||
/// keyed, the clip and its lens's distortion the first frame's
|
||||
pub(crate) fn plates_rows(tr: &Tracks, p: &mut Program) {
|
||||
for (k, (_, track)) in tr.plates.iter().enumerate() {
|
||||
pub fn plates_rows(tracks: &[Track], p: &mut Program) {
|
||||
for (k, (_, track)) in tracks.iter().enumerate() {
|
||||
let its = filled(&track);
|
||||
let id = format!("plate{k}");
|
||||
let mut row = BTreeMap::new();
|
||||
@@ -223,8 +223,8 @@ pub(crate) fn plates_rows(tr: &Tracks, p: &mut Program) {
|
||||
}
|
||||
|
||||
/// fog volumes (a <VolumetricFog>'s boxes of air): placement, density and colour keyed, the rest the first frame's
|
||||
pub(crate) fn fogs_rows(tr: &Tracks, p: &mut Program) {
|
||||
for (k, (_, track)) in tr.fogs.iter().enumerate() {
|
||||
pub fn fogs_rows(tracks: &[Track], p: &mut Program) {
|
||||
for (k, (_, track)) in tracks.iter().enumerate() {
|
||||
let its = filled(&track);
|
||||
let id = format!("fog{k}");
|
||||
let mut row = BTreeMap::new();
|
||||
@@ -253,8 +253,8 @@ pub(crate) fn fogs_rows(tr: &Tracks, p: &mut Program) {
|
||||
}
|
||||
|
||||
/// fires (<Fire>: a flame drawn as a volume): its foot, its box's size, its clock, brightness and colour keyed
|
||||
pub(crate) fn fires_rows(tr: &Tracks, p: &mut Program) {
|
||||
for (k, (_, track)) in tr.fires.iter().enumerate() {
|
||||
pub fn fires_rows(tracks: &[Track], p: &mut Program) {
|
||||
for (k, (_, track)) in tracks.iter().enumerate() {
|
||||
let its = filled(&track);
|
||||
let id = format!("fire{k}");
|
||||
let mut row = BTreeMap::new();
|
||||
@@ -33,7 +33,7 @@ const KEYED: &[(&str, &str, f64)] = &[
|
||||
/// Vector props: the prop, its three columns.
|
||||
const VECS: &[(&str, [&str; 3])] = &[("wind", ["wind_x", "wind_y", "wind_z"]), ("revealFrom", ["reveal_x", "reveal_y", "reveal_z"]), ("revealAxis", ["reveal_ax", "reveal_ay", "reveal_az"])];
|
||||
|
||||
pub(super) fn rows(tracks: &[Track], p: &mut Program) {
|
||||
pub fn rows(tracks: &[Track], p: &mut Program) {
|
||||
for (k, (_, track)) in tracks.iter().enumerate() {
|
||||
let its = filled(track);
|
||||
let id = format!("splat{k}");
|
||||
@@ -51,6 +51,9 @@ raea-core-alloc = { path = "../../core/alloc" }
|
||||
# a composition's TSX bundled into the script the engine runs
|
||||
raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
raea-core-scene = { path = "../../core/scene" }
|
||||
# a long BufferMesh kept on disk by its content (read.rs names3d, docs/render-memory.feature RM8)
|
||||
raea-core-shape = { path = "../../core/shape" }
|
||||
xxhash-rust = { version = "0.8", features = ["xxh3"] }
|
||||
raea-runtime-calls = { path = "../../runtime/calls" }
|
||||
raea-runtime-shared = { path = "../../runtime/shared" }
|
||||
raea-runtime-scene = { path = "../../runtime/scene" }
|
||||
|
||||
@@ -41,7 +41,7 @@ thread_local! {
|
||||
/// each part's data-props as last parsed: its text and the props, and the scene it was last read in
|
||||
static PROPS3D: std::cell::RefCell<bevy::ecs::entity::EntityHashMap<(String, std::sync::Arc<Map<String, Value>>, u64)>> = std::cell::RefCell::new(Default::default());
|
||||
/// each part's data-3d and data-shape as last read, shared
|
||||
static NAMES3D: std::cell::RefCell<bevy::ecs::entity::EntityHashMap<(std::sync::Arc<str>, Option<std::sync::Arc<str>>)>> = std::cell::RefCell::new(Default::default());
|
||||
static NAMES3D: std::cell::RefCell<bevy::ecs::entity::EntityHashMap<(std::sync::Arc<str>, Option<std::sync::Arc<str>>, Option<(usize, u64)>)>> = std::cell::RefCell::new(Default::default());
|
||||
/// each part's data-at (an <Instances>' placements) as last read, shared while its text is the same (issue 84)
|
||||
static AT3D: std::cell::RefCell<bevy::ecs::entity::EntityHashMap<std::sync::Arc<str>>> = std::cell::RefCell::new(Default::default());
|
||||
/// scenes read (scene_of): what's in PROPS3D but not read in the last two is let go
|
||||
|
||||
@@ -34,21 +34,33 @@ pub(crate) fn props3d(e: Entity, text: Option<&str>) -> std::sync::Arc<Map<Strin
|
||||
})
|
||||
}
|
||||
|
||||
/// A part's kind and shape, the shared ones from its last read when they're the same
|
||||
/// A part's kind and shape, the shared ones from its last read when they're the same. A long <BufferMesh> shape
|
||||
/// (`buffer:{json}`, raea_core_shape::KEEP_BUFFER_AT on) goes on as `buffer:@NAME`, its text kept on disk by its
|
||||
/// content (kept_buffer, docs/render-memory.feature RM8), and is known again by its length and xxh3 (about 2 ms for
|
||||
/// 51 MB), never named again while it's the same.
|
||||
pub(crate) fn names3d(e: Entity, kind: &str, shape: Option<&str>) -> (std::sync::Arc<str>, Option<std::sync::Arc<str>>) {
|
||||
let long = shape.filter(|s| s.len() >= raea_core_shape::KEEP_BUFFER_AT && s.starts_with("buffer:{"));
|
||||
let sig = long.map(|s| (s.len(), xxhash_rust::xxh3::xxh3_64(s.as_bytes())));
|
||||
NAMES3D.with_borrow_mut(|c| {
|
||||
if let Some((k, s)) = c.get(&e)
|
||||
if let Some((k, s, was)) = c.get(&e)
|
||||
&& &**k == kind
|
||||
&& s.as_deref() == shape
|
||||
&& match sig {
|
||||
Some(sig) => *was == Some(sig),
|
||||
None => was.is_none() && s.as_deref() == shape,
|
||||
}
|
||||
{
|
||||
return (k.clone(), s.clone());
|
||||
}
|
||||
let v: (std::sync::Arc<str>, Option<std::sync::Arc<str>>) = (kind.into(), shape.map(Into::into));
|
||||
let out: Option<std::sync::Arc<str>> = match long {
|
||||
Some(text) => Some(raea_core_shape::kept_buffer(text).map(Into::into).unwrap_or_else(|| text.into())),
|
||||
None => shape.map(Into::into),
|
||||
};
|
||||
let v: (std::sync::Arc<str>, Option<std::sync::Arc<str>>) = (kind.into(), out);
|
||||
// bounded well past a big scene's parts (many_cubes has 10,000; at 8,192 it was cleared every frame)
|
||||
if c.len() > 1 << 17 {
|
||||
c.clear();
|
||||
}
|
||||
c.insert(e, v.clone());
|
||||
c.insert(e, (v.0.clone(), v.1.clone(), sig));
|
||||
v
|
||||
})
|
||||
}
|
||||
|
||||
@@ -10,6 +10,8 @@ description = "A composition's 3D as raea-render rows: the camera, lights, meshe
|
||||
raea-core-scene = { path = "../../core/scene" }
|
||||
raea-core-program = { path = "../../core/program" }
|
||||
raea-runtime-look = { path = "../look" }
|
||||
# the rows of the kinds placed as a whole (models, splats, grass and the rest)
|
||||
raea-runtime-kinds = { path = "../kinds" }
|
||||
raea-runtime-scene2d = { path = "../scene2d" }
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
|
||||
serde_json = "1"
|
||||
|
||||
@@ -15,22 +15,15 @@ use raea_core_scene::*;
|
||||
pub use raea_runtime_look::{camera, column, rgba_of};
|
||||
use raea_runtime_look::*;
|
||||
|
||||
// the rows of the kinds placed as a whole (models, panels, decals, plates, fog, fire, splats, mesh sequences, grass)
|
||||
use raea_runtime_kinds::*;
|
||||
mod parts;
|
||||
use parts::*;
|
||||
mod models;
|
||||
use models::*;
|
||||
mod live;
|
||||
pub use live::{LiveScene, Shot};
|
||||
pub use raea_core_scene::{LIVE_GROUPS, cam_keyed, live_dynamic};
|
||||
mod fast;
|
||||
|
||||
/// Gaussian splats' rows (<Splat>).
|
||||
mod splat;
|
||||
/// Baked simulations' and glitches' rows (<MeshSequence>, <Goo>, glitch props).
|
||||
mod meshseq;
|
||||
/// Fields of grass' rows (<Grass>).
|
||||
mod grass;
|
||||
|
||||
/// The scene-wide parts placed by their parent alone, a camera column or a post effect each: node kind, item kind. An
|
||||
/// <Atmosphere> is Bevy's procedural sky round the scene, a <Skybox> Bevy's cubemap sky on the camera.
|
||||
const BY_PARENT: [(&str, &str); 19] = [("AmbientLight", "ambient"), ("Bloom", "bloom"), ("Atmosphere", "atmosphere"), ("Fog", "fog"), ("ToneMapping", "tonemapping"), ("DepthOfField", "dof"), ("Grade", "grade"), ("VolumetricFog", "volfog"), ("Environment", "environment"), ("Skybox", "skybox"),
|
||||
@@ -176,12 +169,6 @@ fn walk(n: &Node3, parent: Mat4, out: &mut Vec<Item>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A part's SDK name as its row's `name` column: what a Bevy Entity field (a ChildOf's parent) names it by.
|
||||
fn name_column(row: &mut BTreeMap<String, V>, props: &Map<String, Value>) {
|
||||
if let Some(Value::String(n)) = props.get("name") {
|
||||
row.insert("name".into(), V::S(n.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
/// The <BevyComponent> children of a part (a Mesh, a Model, a light, the camera) onto its item as `components`: Bevy's
|
||||
/// own reflected components, or a compiled-in plugin's, applied by raea-render through the TypeRegistry (plugins.rs).
|
||||
@@ -224,27 +211,6 @@ pub fn items_of(scene: &[Node3]) -> Vec<Item> {
|
||||
}
|
||||
|
||||
|
||||
/// World position, rotation (Bevy's quaternion, q_x q_y q_z q_w: no Euler round trip, docs/control.feature FC1d) and
|
||||
/// scale of each frame; each frame's quaternion takes the sign nearer the frame before's, so keys turn the short way.
|
||||
fn placement(p: &mut Program, row: &mut BTreeMap<String, V>, id: &str, its: &[Item]) {
|
||||
let mut prev = bevy::math::Quat::IDENTITY;
|
||||
let per: Vec<[f64; 10]> = its.iter().map(|it| {
|
||||
let (s, q, t) = it.world.to_scale_rotation_translation();
|
||||
// a zero scale has no rotation (it comes out NaN, keyed on every frame since NaN never equals itself): the one before
|
||||
let q = if q.is_finite() { q } else { prev };
|
||||
prev = if q.dot(prev) < 0.0 { -q } else { q };
|
||||
[t.x as f64, t.y as f64, t.z as f64, prev.x as f64, prev.y as f64, prev.z as f64, prev.w as f64, s.x as f64, s.y as f64, s.z as f64]
|
||||
}).collect();
|
||||
for (k, name) in ["x", "y", "z", "q_x", "q_y", "q_z", "q_w"].iter().enumerate() {
|
||||
exact(p, row, id, name, &per.iter().map(|t| t[k]).collect::<Vec<_>>());
|
||||
}
|
||||
let sc: Vec<[f64; 3]> = per.iter().map(|t| [t[7], t[8], t[9]]).collect();
|
||||
if sc.iter().any(|s| s.iter().any(|v| (v - 1.0).abs() > 1e-9)) {
|
||||
for (k, name) in ["scale_x", "scale_y", "scale_z"].iter().enumerate() {
|
||||
exact(p, row, id, name, &sc.iter().map(|s| s[k]).collect::<Vec<_>>());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The lights, meshes, models and pictures in space, as rows, from each frame's parts.
|
||||
pub fn rows(all: &[Vec<Item>], p: &mut Program) {
|
||||
@@ -261,7 +227,6 @@ pub fn rows(all: &[Vec<Item>], p: &mut Program) {
|
||||
}
|
||||
}
|
||||
|
||||
type Track = (String, Vec<Option<Item>>);
|
||||
|
||||
/// Each kind group's tracks, worked out once (a live frame worked them out twice: in rows_into and again for its ids)
|
||||
struct Tracks {
|
||||
@@ -315,12 +280,12 @@ fn rows_into_of(all: &[Vec<Item>], tr: &Tracks, p: &mut Program) {
|
||||
meshes_rows(tr, &names, p);
|
||||
entities_rows(tr, p);
|
||||
texts_rows(tr, &names, p);
|
||||
models_rows(tr, &names, p);
|
||||
panels_rows(tr, &names, p);
|
||||
decals_rows(tr, p);
|
||||
plates_rows(tr, p);
|
||||
fogs_rows(tr, p);
|
||||
fires_rows(tr, p);
|
||||
models_rows(&tr.models, &names, p);
|
||||
panels_rows(&tr.panels, &names, p);
|
||||
decals_rows(&tr.decals, p);
|
||||
plates_rows(&tr.plates, p);
|
||||
fogs_rows(&tr.fogs, p);
|
||||
fires_rows(&tr.fires, p);
|
||||
// fields of grass (<Grass>): grass.rs
|
||||
grass::rows(&tr.grasses, p);
|
||||
// gaussian splats (<Splat>): splat.rs
|
||||
|
||||
Loaded 100 of 400 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user