Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

RR0: done: today's numbers on the Mac, the Windows PC and an iPhone. Mac: six chunks joined with ffmpeg -c copy 16.3 s quiet (25-27 s loaded), one render 31-38 s, the six start-ups 10.5-16 s; Windows: chunked 71.0 s, 47.3 s of it raea media concat's re-encoding join, React 12 ms a frame on QuickJS (10x the Mac's); the note by hand 3.6 s on the Mac and 64.7 s on Windows, against 29-43 s and 38 s for the whole film again. bench.ps1 runs bench.sh and change.sh on Windows' own PowerShell; the film's shots move to shots.tsx. bench/rerender/ios renders the shots on an iPhone 13 Pro Max (A15: shots 3-5 at 61-265 ms a frame; the atmosphere's Rgba32Float LUTs can't be filtered there, and shot 2 is killed at its first 3D frame); raea-io-os builds for iOS, where its system calls answer as headless (rfd, arboard and opener have no iOS backend)

shinyobjectza3477d0721a5
diff --git a/Cargo.lock b/Cargo.lock
index 4e4e694d..e7706e14 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -14563,6 +14563,14 @@ dependencies = [
"wgpu",
]
+[[package]]
+name = "raea-rerender-ios"
+version = "0.1.0"
+dependencies = [
+ "raea-runtime-export",
+ "raea-runtime-react",
+]
+
[[package]]
name = "raea-rune-bevy"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index 6a6d3a88..a62e1705 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -136,6 +136,7 @@ members = [
"bench/bridge",
"bench/bevy-parity",
"bench/bridge/swatch",
+ "bench/rerender/ios",
"core/alloc",
"runtime/bake",
"runtime/bundle",
diff --git a/bench/rerender/bench.ps1 b/bench/rerender/bench.ps1
new file mode 100644
index 00000000..83da556a
--- /dev/null
+++ b/bench/rerender/bench.ps1
@@ -0,0 +1,135 @@
+# RR0 (docs/rerender.feature): bench.sh and change.sh for Windows, in the PowerShell every Windows PC has (5.1), with no
+# bash, jq or ffmpeg needed. The same runs and the same run.json / change.json as bench.sh and change.sh:
+# chunked the six shot compositions as six renders, -P at a time, joined with ffmpeg -c copy when ffmpeg is on PATH,
+# else with raea media concat (which re-encodes); run.json says which
+# one the "film" composition as one render (before RR1 it holds shot 1's look for all 900 frames)
+# -Note then change.sh's case: shot 4's NOIR line changed on a copy of shots.tsx, shot 4 rendered again and joined
+# again, and the whole film rendered again
+# powershell -ExecutionPolicy Bypass -File bench\rerender\bench.ps1 -Raea C:\path\raea.exe -Out C:\scratch\rr0 [-P 3] [-Note] [-Keep]
+param(
+ [Parameter(Mandatory = $true)][string]$Raea,
+ [Parameter(Mandatory = $true)][string]$Out,
+ [string]$Film = "",
+ [int]$P = 3,
+ [switch]$Note,
+ [switch]$Keep
+)
+# "Continue": under "Stop", a native command's stderr line (raea's startup trace) is a terminating error; a run is
+# judged by its exit code and its APPLIED line instead
+$ErrorActionPreference = "Continue"
+# PowerShell 5.1 leaves $PSScriptRoot empty in a param's default
+if (-not $Film) { $Film = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) "film.tsx" }
+if (-not (Test-Path $Raea)) { Write-Output "bench: no raea at $Raea"; exit 2 }
+New-Item -ItemType Directory -Force -Path $Out | Out-Null
+$env:RAEA_SIGN = "0"; $env:RAEA_MARK = "0"; $env:RAEA_EXPORT_CACHE = "0"; $env:RAEA_TIMES = "1"
+function Now { [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() / 1000.0 }
+$ffmpeg = Get-Command ffmpeg -ErrorAction SilentlyContinue
+
+# Start ID OUTFILE FILM: one render started, its logs in OUT\ID.{log,err,tsv}
+function Start-Render($id, $file, $src) {
+ $env:RAEA_STARTUP_TRACE = [string][DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
+ $env:RAEA_FRAME_LOG = Join-Path $Out "$id.tsv"
+ $p = Start-Process -FilePath $Raea -ArgumentList @("render", "`"$src`"", "--composition", $id, "-o", "`"$file`"") -NoNewWindow -PassThru `
+ -RedirectStandardOutput (Join-Path $Out "$id.log") -RedirectStandardError (Join-Path $Out "$id.err")
+ $null = $p.Handle # PowerShell 5.1: without it ExitCode is empty after the wait
+ [pscustomobject]@{ id = $id; proc = $p; t0 = (Now); t1 = $null }
+}
+function Wait-Render($r) {
+ $r.proc.WaitForExit()
+ $r.t1 = Now
+ $text = (Get-Content (Join-Path $Out "$($r.id).log") -Raw) + (Get-Content (Join-Path $Out "$($r.id).err") -Raw)
+ Set-Content -Path (Join-Path $Out "$($r.id).all") -Value $text
+ if ($r.proc.ExitCode -ne 0 -or $text -notmatch "(?m)^APPLIED") { Write-Output "bench: $($r.id) failed (exit $($r.proc.ExitCode))"; $script:status = 1 }
+}
+# Stats: one render's numbers, as bench.sh writes them
+function Stats($r) {
+ $text = Get-Content (Join-Path $Out "$($r.id).all") -Raw
+ $times = $null
+ $m = [regex]::Match($text, '(?m)^\{"direct".*$'); if ($m.Success) { $times = $m.Value | ConvertFrom-Json }
+ $first = $null
+ $marks = [regex]::Matches($text, "raea startup:\s+([0-9.]+) ms\s+the fed render's first frame"); if ($marks.Count) { $first = [double]$marks[$marks.Count - 1].Groups[1].Value }
+ $log = $null
+ $tsv = Join-Path $Out "$($r.id).tsv"
+ if (Test-Path $tsv) {
+ $rows = @(Import-Csv -Path $tsv -Delimiter "`t")
+ $rest = @($rows | Select-Object -Skip 1)
+ $mean = { param($k) if ($rest.Count) { [math]::Round((($rest | ForEach-Object { [double]$_.$k }) | Measure-Object -Sum).Sum / $rest.Count, 2) } else { 0 } }
+ $log = [ordered]@{ first = [ordered]@{ react = [double]$rows[0].react; sync = [double]$rows[0].sync; gpu = [double]$rows[0].gpu }
+ rest_mean = [ordered]@{ react = (& $mean "react"); sync = (& $mean "sync"); gpu = (& $mean "gpu") }; rows = $rows.Count }
+ }
+ [ordered]@{ id = $r.id; wall_s = [math]::Round($r.t1 - $r.t0, 3); first_frame_ms = $first; frames = $times.frames; encoder = $times.video
+ ms_per_frame = $times.times.ms_per_frame; fps_incl_encode = $times.fps_incl_encode; frame_log = $log }
+}
+function Join-Chunks($files, $dest) {
+ # the last render's trace and frame log aren't the join's
+ Remove-Item Env:RAEA_STARTUP_TRACE, Env:RAEA_FRAME_LOG -ErrorAction SilentlyContinue
+ if ($ffmpeg) {
+ $list = Join-Path $Out "list.txt"
+ Set-Content -Path $list -Value ($files | ForEach-Object { "file '$($_ -replace '\\', '/')'" })
+ & $ffmpeg.Source -y -loglevel error -f concat -safe 0 -i $list -c copy $dest
+ "ffmpeg -f concat -c copy"
+ } else {
+ & $Raea media concat @files -o $dest *> (Join-Path $Out "concat.log")
+ "raea media concat"
+ }
+}
+
+$status = 0
+$gpu = (Get-CimInstance Win32_VideoController | Select-Object -First 1).Name
+$machine = [ordered]@{ os = "Windows " + [Environment]::OSVersion.Version; gpu = $gpu; host = $env:COMPUTERNAME; raea = ((& $Raea --version 2>$null) | Select-Object -First 1) }
+
+Write-Output "bench: six shot renders, $P at a time"
+$t0 = Now
+$queue = 1..6; $running = @(); $done = @()
+foreach ($k in $queue) {
+ while ($running.Count -ge $P) {
+ $r = $running | Where-Object { $_.proc.HasExited } | Select-Object -First 1
+ if ($r) { Wait-Render $r; $done += $r; $running = @($running | Where-Object { $_ -ne $r }) } else { Start-Sleep -Milliseconds 50 }
+ }
+ $running += Start-Render "shot-$k" (Join-Path $Out "shot-$k.mp4") $Film
+}
+foreach ($r in $running) { Wait-Render $r; $done += $r }
+$t1 = Now
+$files = 1..6 | ForEach-Object { Join-Path $Out "shot-$_.mp4" }
+$j0 = Now; $joiner = Join-Chunks $files (Join-Path $Out "film-chunked.mp4"); $j1 = Now
+$shots = @($done | Sort-Object id | ForEach-Object { Stats $_ })
+$frames_s = 0; $startups = 0
+foreach ($s in $shots) { if ($s.frames) { $frames_s += $s.frames * $s.ms_per_frame.wall / 1000 }; if ($s.first_frame_ms) { $startups += $s.first_frame_ms / 1000 } }
+$chunked = [ordered]@{ p = $P; renders_s = [math]::Round($t1 - $t0, 3); joiner = $joiner; join_s = [math]::Round($j1 - $j0, 3)
+ total_s = [math]::Round($j1 - $t0, 3); startups_s = $startups; frames_s = $frames_s; shots = $shots }
+Write-Output "bench: chunked $($chunked.total_s) s (renders $($chunked.renders_s) s, join $($chunked.join_s) s, $joiner)"
+
+Write-Output "bench: the film as one render"
+$r = Start-Render "film" (Join-Path $Out "film-one.mp4") $Film; Wait-Render $r
+$one = Stats $r
+Write-Output "bench: one render $($one.wall_s) s, first frame $($one.first_frame_ms) ms"
+$run = [ordered]@{ film = [ordered]@{ frames = 900; width = 1920; height = 1080; fps = 30; shots = 6 }; machine = $machine; chunked = $chunked; one = $one
+ one_estimate_s = $frames_s + $shots[0].first_frame_ms / 1000 }
+$run | ConvertTo-Json -Depth 8 | Set-Content -Path (Join-Path $Out "run.json")
+
+if ($Note) {
+ # change.sh's note, on a copy of film.tsx and shots.tsx
+ $noteDir = Join-Path $Out "note"; New-Item -ItemType Directory -Force -Path $noteDir | Out-Null
+ $src = Join-Path $noteDir "film.tsx"
+ Copy-Item $Film $src
+ $shots = Join-Path (Split-Path -Parent $Film) "shots.tsx"
+ $text = (Get-Content $shots -Raw) -replace '(?m)^export const NOIR = .*$', 'export const NOIR = { saturation: 0.25, contrast: 1.5, temperature: 0.04, sun: 45000, ambient: 250 };'
+ if ($text -notmatch 'saturation: 0.25, contrast: 1.5') { Write-Output "change: shots.tsx's NOIR line wasn't found to change"; exit 1 }
+ [IO.File]::WriteAllText((Join-Path $noteDir "shots.tsx"), $text)
+ $c0 = Now
+ $r = Start-Render "shot-4" (Join-Path $noteDir "shot-4.mp4") $src; Wait-Render $r
+ $c1 = Now
+ $files = 1..6 | ForEach-Object { if ($_ -eq 4) { Join-Path $noteDir "shot-4.mp4" } else { Join-Path $Out "shot-$_.mp4" } }
+ $joiner = Join-Chunks $files (Join-Path $noteDir "film-chunked.mp4")
+ $c2 = Now
+ $r = Start-Render "film" (Join-Path $noteDir "film-one.mp4") $src; Wait-Render $r
+ $c3 = Now
+ $change = [ordered]@{ note = "shot 4 (150 of 900 frames): grade and sun"
+ chunks = [ordered]@{ shot_s = [math]::Round($c1 - $c0, 3); join_s = [math]::Round($c2 - $c1, 3); total_s = [math]::Round($c2 - $c0, 3); joiner = $joiner }
+ film = [ordered]@{ total_s = [math]::Round($c3 - $c2, 3) } }
+ $change | ConvertTo-Json -Depth 4 | Set-Content -Path (Join-Path $Out "change.json")
+ Write-Output "change: shot 4 again $($change.chunks.shot_s) s + join $($change.chunks.join_s) s; the whole film again $($change.film.total_s) s"
+}
+if (-not $Keep) { Get-ChildItem -Path $Out -Recurse -Filter *.mp4 | Remove-Item -Force }
+Write-Output "bench: $(Join-Path $Out 'run.json')"
+exit $status
diff --git a/bench/rerender/change.sh b/bench/rerender/change.sh
index 797d43ee..336d2cd3 100755
--- a/bench/rerender/change.sh
+++ b/bench/rerender/change.sh
@@ -1,10 +1,10 @@
#!/usr/bin/env bash
-# RR0 (docs/rerender.feature): the "one note" case. A note changes shot 4's grade and light (film.tsx's NOIR line), and
+# RR0 (docs/rerender.feature): the "one note" case. A note changes shot 4's grade and light (shots.tsx's NOIR line), and
# this times what it takes to have the whole film again:
# chunks today's way by hand: shot 4's chunk rendered again and the six chunks joined again (ffmpeg -c copy, or
# raea media concat where there's no ffmpeg); needs bench.sh's chunks (KEEP=1) in OUT
# film the film as one render again (what a render with no shot cache costs; before RR1 its picture isn't the film)
-# The note is made on a copy of film.tsx in OUT, never on the checkout. Writes OUT/change.json.
+# The note is made on a copy of film.tsx and shots.tsx in OUT, never on the checkout. Writes OUT/change.json.
# bench/rerender/change.sh OUT (OUT: a bench.sh run's folder, made with KEEP=1; RAEA_BIN as bench.sh)
set -u
cd "$(dirname "$0")/../.." || exit 2
@@ -21,8 +21,9 @@ span() { echo "$1 $2" | awk '{printf "%.3f", $2 - $1}'; }
# the note: shot 4 warmer, a little colour back, harder, under a stronger sun
NOTE=$OUT/note
mkdir -p "$NOTE"
-sed 's/^export const NOIR = .*/export const NOIR = { saturation: 0.25, contrast: 1.5, temperature: 0.04, sun: 45000, ambient: 250 };/' "$ROOT/bench/rerender/film.tsx" > "$NOTE/film.tsx"
-grep -q 'saturation: 0.25, contrast: 1.5' "$NOTE/film.tsx" || { echo "change: film.tsx's NOIR line wasn't found to change"; exit 1; }
+cp "$ROOT/bench/rerender/film.tsx" "$NOTE/film.tsx"
+sed 's/^export const NOIR = .*/export const NOIR = { saturation: 0.25, contrast: 1.5, temperature: 0.04, sun: 45000, ambient: 250 };/' "$ROOT/bench/rerender/shots.tsx" > "$NOTE/shots.tsx"
+grep -q 'saturation: 0.25, contrast: 1.5' "$NOTE/shots.tsx" || { echo "change: shots.tsx's NOIR line wasn't found to change"; exit 1; }
status=0
# today's way by hand: the changed chunk again, then the join again
diff --git a/bench/rerender/film.tsx b/bench/rerender/film.tsx
index 1246da5d..c247c92e 100644
--- a/bench/rerender/film.tsx
+++ b/bench/rerender/film.tsx
@@ -5,190 +5,8 @@
// "shot-1".."shot-6" each shot as its own composition, as agents split films today; bench.sh renders these as
// chunks and joins them, the baseline the overhaul is measured against
// Shot 4 (noir) is the one change.sh edits, as a note would.
-import { AbsoluteFill, Composition, registerRoot, useCurrentFrame } from "raea";
-import {
- AmbientOcclusion, AntiAliasing, Atmosphere, Bloom, Canvas3D, DepthOfField, Fog, FogVolume, Grade, Grass, Instances,
- ToneMapping, Shadows, VolumetricFog, grow, manifold, scatter,
-} from "raea/3d";
-import { Camera3d } from "raea/camera";
-import { AmbientLight, DirectionalLight, PointLight, SpotLight } from "raea/light";
-import { Mesh3d } from "raea/mesh";
-import { StandardMaterial } from "raea/pbr";
-import { Transform } from "raea/transform";
-
-export const FPS = 30;
-export const SHOT = 150;
-type V3 = [number, number, number];
-
-// ---------------------------------------------------------------- the set, built once
-
-const OAK = { height: 7, crown: "dome" as const, points: 1500, leaves: 4, leaf: 0.14, seed: 3 };
-const PINE = { height: 10, crown: "cone" as const, points: 1100, leaves: 5, leaf: 0.1, width: 0.5, seed: 4 };
-const OAK_WOOD = grow.tree(OAK, "wood");
-const OAK_LEAVES = grow.tree(OAK, "leaves");
-const PINE_WOOD = grow.tree(PINE, "wood");
-const PINE_LEAVES = grow.tree(PINE, "leaves");
-const ROCK = grow.boulder({ size: 1.4, rough: 0.5, seed: 5 });
-// the forest and meadow, west of the street; the room's walls and the street's blocks are kept clear
-const WOODS = { min: [-110, -70] as [number, number], max: [-8, 30] as [number, number] };
-const GLADE = [{ min: [-40, -12] as [number, number], max: [-22, 6] as [number, number] }];
-const OAKS = scatter({ area: WOODS, count: 110, spacing: 5, seed: 11, scale: [0.7, 1.3], avoid: GLADE });
-const PINES = scatter({ area: WOODS, count: 90, spacing: 5, seed: 13, scale: [0.8, 1.4], avoid: GLADE, clearOf: OAKS });
-// the meadow under the trees: grass the engine grows, about 40k clumps
-const MEADOW = { min: [-75, -40] as [number, number], max: [-5, 45] as [number, number] };
-const flat = () => 0;
-const ROCKS = scatter({ area: { min: [-90, -60], max: [-10, 30] }, count: 40, spacing: 3, seed: 12, scale: [0.4, 1.6] });
-// the room: a 10 x 4 x 8 box with its inside carved out and a window in the east wall
-const ROOM = manifold.box(10.4, 4.4, 8.4).minus(manifold.box(10, 4, 8)).minus(manifold.box(1, 1.6, 3).move(5, 0.4, 0));
-const TABLE = manifold.box(2.4, 0.08, 1.2).move(0, 0.76, 0)
- .union(manifold.box(0.08, 0.76, 0.08).move(-1.1, 0.38, -0.5)).union(manifold.box(0.08, 0.76, 0.08).move(1.1, 0.38, -0.5))
- .union(manifold.box(0.08, 0.76, 0.08).move(-1.1, 0.38, 0.5)).union(manifold.box(0.08, 0.76, 0.08).move(1.1, 0.38, 0.5));
-const CUP = manifold.cylinder(0.05, 0.11).minus(manifold.cylinder(0.042, 0.11).move(0, 0, 0.01)).rotate(-90, 0, 0);
-// the street: two rows of blocks with windows, lamps between them
-const BLOCK = [0, 1, 2, 3].reduce((s, i) => s.minus(manifold.box(1.2, 1.6, 0.4).move(-3 + i * 2, 2, 3)), manifold.box(8, 9, 6).move(0, 4.5, 0));
-const BLOCKS: { at: V3; h: number }[] = Array.from({ length: 36 }, (_, i) => ({ at: [40 + (i % 12) * 9, 0, [-8, 8, -22][Math.floor(i / 12)]], h: 0.8 + ((i * 37) % 5) / 6 }));
-// the room's shelves: 480 books along the back wall
-const BOOK = manifold.box(0.04, 0.24, 0.17);
-const BOOKS = Array.from({ length: 480 }, (_, i) => {
- const row = Math.floor(i / 120), col = i % 120;
- return { position: [-4.6 + col * 0.075, 0.6 + row * 0.42, 63.8] as V3, rotation: [0, 0, ((i * 13) % 7 - 3) * 0.02] as V3, scale: [1, 0.8 + ((i * 7) % 5) * 0.08, 1] as V3 };
-});
-const SHELF = manifold.box(9.2, 0.03, 0.3);
-const GROUND = manifold.box(400, 1, 400).move(0, -0.5, 0);
-const BULB = manifold.sphere(0.18);
-const LAMP_GLOW = "#ffd890";
-const LAMPS: V3[] = [0, 1, 2, 3, 4].map((i) => [42 + i * 10, 4, i % 2 ? 4 : -4]);
-
-function Set() {
- return (
- <>
- <Mesh3d name="ground" shape={GROUND}><StandardMaterial base_color="#5a5e48" perceptual_roughness={0.95} /></Mesh3d>
- <Instances at={OAKS} shape={OAK_WOOD}><StandardMaterial base_color="#4a3826" perceptual_roughness={0.9} /></Instances>
- <Instances at={OAKS} shape={OAK_LEAVES}><StandardMaterial base_color="#3f6b2c" perceptual_roughness={0.8} /></Instances>
- <Instances at={PINES} shape={PINE_WOOD}><StandardMaterial base_color="#3d2c1e" perceptual_roughness={0.9} /></Instances>
- <Instances at={PINES} shape={PINE_LEAVES}><StandardMaterial base_color="#28472a" perceptual_roughness={0.85} /></Instances>
- <Grass name="meadow" area={MEADOW} height={flat} density={7} />
- <Instances at={ROCKS} shape={ROCK}><StandardMaterial base_color="#77736a" perceptual_roughness={0.85} /></Instances>
- <Mesh3d name="room" shape={ROOM} transform={Transform.fromXyz(0, 2, 60)}><StandardMaterial base_color="#d8cdb8" perceptual_roughness={0.9} /></Mesh3d>
- <Mesh3d name="table" shape={TABLE} transform={Transform.fromXyz(0, 0, 60)}><StandardMaterial base_color="#6b4a2f" perceptual_roughness={0.6} /></Mesh3d>
- {[-0.6, 0, 0.5].map((x, i) => (
- <Mesh3d key={i} name={`cup-${i}`} shape={CUP} transform={Transform.fromXyz(x, 0.825, 60 + (i - 1) * 0.2)}><StandardMaterial base_color={["#e9e4da", "#2f4f6f", "#b34a2f"][i]} perceptual_roughness={0.3} /></Mesh3d>
- ))}
- {BLOCKS.map((b, i) => (
- <Mesh3d key={i} name={`block-${i}`} shape={BLOCK} transform={Transform.fromXyz(...b.at).withScale([1, b.h, 1])}><StandardMaterial base_color={i % 3 ? "#8b8580" : "#6d6660"} perceptual_roughness={0.8} /></Mesh3d>
- ))}
- <Instances at={BOOKS} shape={BOOK}><StandardMaterial base_color="#7a3b2e" perceptual_roughness={0.7} /></Instances>
- {[0, 1, 2, 3].map((r) => <Mesh3d key={r} name={`shelf-${r}`} shape={SHELF} transform={Transform.fromXyz(0, 0.465 + r * 0.42, 63.8)}><StandardMaterial base_color="#5b412b" perceptual_roughness={0.6} /></Mesh3d>)}
- {LAMPS.map((p, i) => (
- <Mesh3d key={i} name={`lamp-${i}`} shape={BULB} transform={Transform.fromXyz(...p)}><StandardMaterial base_color="#fff1c8" emissive={LAMP_GLOW} /></Mesh3d>
- ))}
- </>
- );
-}
-
-// ---------------------------------------------------------------- the six shots
-
-interface Look {
- sky: boolean;
- /** the sky's colour behind the set where no Atmosphere draws one */
- bg: string;
- sun: { from: V3; lux: number; color: string };
- ambient: number;
- tone: "agx" | "aces" | "tony" | "neutral";
- exposure: number;
- fog?: { color: string; near: number; far: number };
- volume?: { at: V3; size: V3; density: number };
- bloom?: number;
- ao?: boolean;
- dof?: number;
- grade: { temperature: number; tint?: number; saturation: number; contrast: number; vignette: number };
- lamps: number;
-}
-interface Shot {
- name: string;
- title: string;
- look: Look;
- /** the camera at t seconds into the shot */
- cam(t: number): { at: V3; look: V3; fov: number; focus?: number };
-}
-
-// shot 4's grade and light: the line change.sh rewrites, as a note would
-export const NOIR = { saturation: 0, contrast: 1.35, temperature: -0.02, sun: 25000, ambient: 400 };
-
-const lerp = (a: V3, b: V3, u: number): V3 => [a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u, a[2] + (b[2] - a[2]) * u];
-
-export const SHOTS: Shot[] = [
- {
- name: "dawn", title: "Dawn",
- look: { sky: true, bg: "#000000", sun: { from: [-60, 8, -40], lux: 30000, color: "#ffd2a0" }, ambient: 200, tone: "agx", exposure: 0, fog: { color: "#e8c9a8", near: 30, far: 160 }, grade: { temperature: 0.05, saturation: 1.05, contrast: 1, vignette: 0.2 }, lamps: 0 },
- cam: (t) => ({ at: lerp([-20, 2, 25], [-28, 2.2, 12], t / 5), look: [-45, 3, -10], fov: 40 }),
- },
- {
- name: "night", title: "Night",
- look: { sky: false, bg: "#06080e", sun: { from: [30, 40, 20], lux: 40, color: "#9fb4ff" }, ambient: 10, tone: "aces", exposure: 1.5, volume: { at: [62, 4, 0], size: [60, 10, 30], density: 0.12 }, bloom: 0.6, grade: { temperature: -0.08, tint: 0.06, saturation: 0.9, contrast: 1.1, vignette: 0.4 }, lamps: 400000 },
- cam: (t) => ({ at: [36, 2, lerp([-3, 0, 0], [3, 0, 0], t / 5)[0]], look: [70, 3, 0], fov: 45 }),
- },
- {
- name: "interior", title: "Interior",
- look: { sky: false, bg: "#1a1d22", sun: { from: [20, 10, 60], lux: 15000, color: "#fff0d8" }, ambient: 120, tone: "agx", exposure: 1, ao: true, dof: 1.8, grade: { temperature: 0.03, saturation: 1, contrast: 1.05, vignette: 0.3 }, lamps: 0 },
- cam: (t) => { const at = lerp([-3.5, 1.6, 57], [-1.6, 1.25, 58.8], t / 5); return { at, look: [0, 0.85, 60], fov: 35, focus: Math.hypot(at[0], at[1] - 0.85, at[2] - 60) }; },
- },
- {
- name: "noir", title: "Noir",
- look: { sky: false, bg: "#5a5a5a", sun: { from: [80, 30, -40], lux: NOIR.sun, color: "#ffffff" }, ambient: NOIR.ambient, tone: "tony", exposure: 1.5, grade: { temperature: NOIR.temperature, saturation: NOIR.saturation, contrast: NOIR.contrast, vignette: 0.55 }, lamps: 0 },
- cam: (t) => ({ at: lerp([38, 1.7, 0], [60, 1.7, 0], t / 5), look: lerp([48, 4, -6], [70, 4, -6], t / 5), fov: 50 }),
- },
- {
- name: "overcast", title: "Overcast",
- look: { sky: false, bg: "#c9ced4", sun: { from: [0, 60, 10], lux: 8000, color: "#e6ecf2" }, ambient: 600, tone: "neutral", exposure: 0.5, fog: { color: "#c9ced4", near: 10, far: 90 }, grade: { temperature: -0.02, saturation: 0.8, contrast: 0.95, vignette: 0.1 }, lamps: 0 },
- cam: (t) => ({ at: lerp([-30, 1.5, 30], [-30, 9, 30], t / 5), look: [-50, 4, -5], fov: 55 }),
- },
- {
- name: "sunset", title: "Sunset",
- look: { sky: true, bg: "#000000", sun: { from: [-100, 3, 20], lux: 40000, color: "#ff9a5a" }, ambient: 80, tone: "agx", exposure: 0.5, bloom: 0.35, dof: 2.8, grade: { temperature: 0.1, saturation: 1.15, contrast: 1.05, vignette: 0.5 }, lamps: 0 },
- cam: (t) => { const a = 0.6 + (t / 5) * 0.5; return { at: [-40 + Math.cos(a) * 30, 4, -5 + Math.sin(a) * 30], look: [-40, 3, -5], fov: 28, focus: 30 }; },
- },
-];
-
-/** One shot's frame: the set, the shot's look, its camera at t, and its title over the picture. */
-export function Frame({ k, t }: { k: number; t: number }) {
- const s = SHOTS[k];
- const L = s.look;
- const c = s.cam(t);
- return (
- <AbsoluteFill style={{ background: L.bg }}>
- <Canvas3D>
- <Camera3d key={k === 5 ? "B" : "A"} transform={Transform.fromXyz(...c.at).lookingAt(c.look, [0, 1, 0])} projection={{ Perspective: { fov: (c.fov * Math.PI) / 180, near: 0.1, far: 400 } }}>
- {L.dof ? <DepthOfField focal_distance={c.focus ?? 10} aperture_f_stops={L.dof} /> : null}
- </Camera3d>
- {L.sky ? <Atmosphere light /> : null}
- <DirectionalLight name="sun" transform={Transform.fromXyz(...L.sun.from).lookingAt([0, 0, 0], [0, 1, 0])} illuminance={L.sun.lux} color={L.sun.color} shadow_maps_enabled soft_shadow_size={1.5} />
- {L.ao ? <SpotLight name="pendant" transform={Transform.fromXyz(0, 3.6, 60).lookingAt([0, 0, 60], [1, 0, 0])} intensity={60000} color="#ffd9a8" range={12} outer_angle={0.9} inner_angle={0.4} radius={0.08} shadow_maps_enabled soft_shadows_enabled /> : null}
- <AmbientLight brightness={L.ambient} />
- {LAMPS.map((p, i) => <PointLight key={i} name={`lamp-light-${i}`} transform={Transform.fromXyz(...p)} intensity={L.lamps} color={LAMP_GLOW} range={18} volumetric={L.lamps > 0} shadow_maps_enabled={L.lamps > 0} visibility={L.lamps > 0 ? "Visible" : "Hidden"} />)}
- <ToneMapping mode={L.tone} exposure={L.exposure} />
- {L.fog ? <Fog color={L.fog.color} near={L.fog.near} far={L.fog.far} /> : null}
- {L.volume ? <><VolumetricFog steps={96} /><FogVolume name="haze" position={L.volume.at} scale={L.volume.size} density={L.volume.density} /></> : null}
- {L.bloom ? <Bloom intensity={L.bloom} threshold={0.9} /> : null}
- {L.ao ? <AmbientOcclusion quality="ultra" /> : null}
- <AntiAliasing mode={L.ao ? "smaa" : "msaa"} />
- <Shadows mapSize={8192} distance={L.ao ? 20 : 120} cascades={4} />
- <Grade temperature={L.grade.temperature} tint={L.grade.tint ?? 0} saturation={L.grade.saturation} midtones={{ contrast: L.grade.contrast }} vignette={L.grade.vignette} />
- <Set />
- </Canvas3D>
- <div style={{ position: "absolute", left: 120, bottom: 150, fontFamily: "Helvetica, Arial, sans-serif", color: "#fff", textShadow: "0 2px 12px rgba(0,0,0,0.7)" }}>
- <div style={{ fontSize: 22, letterSpacing: "0.3em", opacity: 0.8 }}>SHOT {k + 1}</div>
- <div style={{ fontSize: 64, fontWeight: 700, opacity: Math.min(1, t * 2) }}>{s.title}</div>
- </div>
- </AbsoluteFill>
- );
-}
-
-function Film() {
- const f = useCurrentFrame();
- return <Frame k={Math.min(5, Math.floor(f / SHOT))} t={(f % SHOT) / FPS} />;
-}
-const one = (k: number) => function OneShot() { return <Frame k={k} t={useCurrentFrame() / FPS} />; };
+import { Composition, registerRoot } from "raea";
+import { FPS, Film, SHOT, SHOTS, one } from "./shots";
registerRoot(() => (
<>
diff --git a/bench/rerender/ios/.gitignore b/bench/rerender/ios/.gitignore
new file mode 100644
index 00000000..a0c83c78
--- /dev/null
+++ b/bench/rerender/ios/.gitignore
@@ -0,0 +1,4 @@
+# bench.sh makes these: the shot bundles, and xcodegen's project
+app/Bundle/
+app/RerenderBench.xcodeproj/
+app/Sources/RerenderBench.entitlements
diff --git a/bench/rerender/ios/Cargo.toml b/bench/rerender/ios/Cargo.toml
new file mode 100644
index 00000000..2cc3ee27
--- /dev/null
+++ b/bench/rerender/ios/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "raea-rerender-ios"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "RR0's film on the iPhone (docs/rerender.feature): a static library the bench app calls to render one bundled composition in a fresh process, as bench.sh renders each on the Mac"
+
+[lib]
+name = "raea_rerender_ios"
+crate-type = ["staticlib", "rlib"]
+
+[dependencies]
+raea-runtime-export = { path = "../../../runtime/export" }
+raea-runtime-react = { path = "../../../runtime/react", default-features = false }
diff --git a/bench/rerender/ios/app/Sources/App.swift b/bench/rerender/ios/app/Sources/App.swift
new file mode 100644
index 00000000..41d5b5b7
--- /dev/null
+++ b/bench/rerender/ios/app/Sources/App.swift
@@ -0,0 +1,62 @@
+import SwiftUI
+
+// RR0's film on the iPhone (docs/rerender.feature, bench/rerender/ios/bench.sh). One launch renders one composition,
+// so each runs in a cold process as bench.sh renders each chunk on the Mac:
+// RR_COMP=NAME (launch environment) Bundle/NAME.comp.js rendered to Documents/NAME.mp4
+// What raea prints (its startup marks, RAEA_TIMES' line, APPLIED or REFUSED) goes to Documents/NAME.log, the frame log
+// to Documents/NAME.tsv, and Documents/NAME.json says the wall time and the peak physical footprint (what jetsam
+// counts). The app exits when it's done, which is what bench.sh's `devicectl ... launch --console` waits on.
+
+/// The process's peak physical footprint, in MB.
+func peakMB() -> Int {
+ var info = task_vm_info_data_t()
+ var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<natural_t>.size)
+ let kr = withUnsafeMutablePointer(to: &info) {
+ $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count) }
+ }
+ return kr == KERN_SUCCESS ? Int(info.ledger_phys_footprint_peak >> 20) : -1
+}
+
+@main
+struct RerenderBenchApp: App {
+ @State private var text = "rendering…"
+ var body: some Scene {
+ WindowGroup {
+ Text(text).font(.system(size: 13, design: .monospaced)).padding()
+ .task { text = await Self.run() }
+ }
+ }
+
+ static func run() async -> String {
+ guard let name = ProcessInfo.processInfo.environment["RR_COMP"] else { return "no RR_COMP: bench.sh launches this" }
+ let bundleDir = Bundle.main.resourceURL!.appendingPathComponent("Bundle")
+ let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
+ let js = bundleDir.appendingPathComponent(name + ".comp.js").path
+ let out = docs.appendingPathComponent(name + ".mp4")
+ let log = docs.appendingPathComponent(name + ".log").path
+ let report = docs.appendingPathComponent(name + ".json")
+ for f in [out, report] { try? FileManager.default.removeItem(at: f) }
+ FileManager.default.changeCurrentDirectoryPath(docs.path)
+ // as bench.sh renders on the Mac: no signing, no mark, no export cache, RAEA_TIMES' line, the frame log
+ setenv("RAEA_SIGN", "0", 1); setenv("RAEA_MARK", "0", 1); setenv("RAEA_EXPORT_CACHE", "0", 1)
+ setenv("RAEA_TIMES", "1", 1)
+ setenv("RAEA_FRAME_LOG", docs.appendingPathComponent(name + ".tsv").path, 1)
+ // iOS gives an app no JIT; said to JavaScriptCore too, before its first context
+ setenv("JSC_useJIT", "false", 1)
+ // a locked phone suspends the app and the run is lost
+ await MainActor.run { UIApplication.shared.isIdleTimerDisabled = true }
+ let said: String = await Task.detached {
+ freopen(log, "w", stdout); freopen(log, "a", stderr)
+ setvbuf(stdout, nil, _IOLBF, 0)
+ let t0 = Date()
+ let code = raea_rerender_run(js, out.path)
+ let wall = Date().timeIntervalSince(t0)
+ fflush(stdout); fflush(stderr)
+ let body = "{\"comp\": \"\(name)\", \"code\": \(code), \"wall_s\": \(String(format: "%.3f", wall)), \"peak_mb\": \(peakMB())}"
+ try? body.write(to: report, atomically: true, encoding: .utf8)
+ return body
+ }.value
+ exit(0)
+ return said
+ }
+}
diff --git a/bench/rerender/ios/app/Sources/bench.h b/bench/rerender/ios/app/Sources/bench.h
new file mode 100644
index 00000000..94bdd96e
--- /dev/null
+++ b/bench/rerender/ios/app/Sources/bench.h
@@ -0,0 +1,3 @@
+// bench/rerender/ios/src/lib.rs
+#include <stdint.h>
+int32_t raea_rerender_run(const char *bundle, const char *out);
diff --git a/bench/rerender/ios/app/project.yml b/bench/rerender/ios/app/project.yml
new file mode 100644
index 00000000..fcc3d508
--- /dev/null
+++ b/bench/rerender/ios/app/project.yml
@@ -0,0 +1,43 @@
+# RR0's iPhone bench app (bench/rerender/ios/bench.sh): xcodegen makes RerenderBench.xcodeproj from this. The Rust side
+# is libraea_rerender_ios.a (bench/rerender/ios, built for aarch64-apple-ios); Bundle/ holds the shot bundles bench.sh
+# makes. Signed with the App Store Connect key, as apps/ipad is: team BJJZ79J5NL, automatic.
+name: RerenderBench
+options:
+ bundleIdPrefix: io.raea
+ deploymentTarget:
+ iOS: "16.0"
+settings:
+ base:
+ DEVELOPMENT_TEAM: BJJZ79J5NL
+ CODE_SIGN_STYLE: Automatic
+ SWIFT_VERSION: "5.0"
+ TARGETED_DEVICE_FAMILY: "1"
+ GENERATE_INFOPLIST_FILE: YES
+ INFOPLIST_KEY_UILaunchScreen_Generation: YES
+ CURRENT_PROJECT_VERSION: "1"
+ MARKETING_VERSION: "1.0"
+ ENABLE_BITCODE: NO
+targets:
+ RerenderBench:
+ type: application
+ platform: iOS
+ sources:
+ - Sources
+ - path: Bundle
+ type: folder
+ buildPhase: resources
+ # shot 2 (five shadowed volumetric lamps) is killed at the default per-app memory limit; shots 3-5 peak at 2.4-2.8 GB
+ entitlements:
+ path: Sources/RerenderBench.entitlements
+ properties:
+ com.apple.developer.kernel.increased-memory-limit: true
+ settings:
+ base:
+ PRODUCT_BUNDLE_IDENTIFIER: io.raea.rerenderbench
+ SWIFT_OBJC_BRIDGING_HEADER: Sources/bench.h
+ LIBRARY_SEARCH_PATHS: $(RUST_LIB_DIR)
+ OTHER_LDFLAGS: -lraea_rerender_ios -lc++ -lz -liconv -lresolv -framework Metal -framework MetalKit -framework QuartzCore -framework AVFoundation -framework CoreMedia -framework CoreVideo -framework VideoToolbox -framework CoreText -framework CoreGraphics -framework CoreFoundation -framework Security -framework IOSurface -framework AudioToolbox -framework CoreImage -framework ImageIO -framework AVFAudio -framework MediaToolbox -framework CoreAudio -framework SystemConfiguration -framework UIKit -framework JavaScriptCore -framework GameController -framework CoreHaptics
+ INFOPLIST_KEY_CFBundleDisplayName: Rerender Bench
+ DEAD_CODE_STRIPPING: YES
+ # no dSYM: dsymutil on the 285 MB binary takes minutes, and a bench app's crashes are read from its log
+ DEBUG_INFORMATION_FORMAT: dwarf
diff --git a/bench/rerender/ios/bench.sh b/bench/rerender/ios/bench.sh
new file mode 100755
index 00000000..758a9751
--- /dev/null
+++ b/bench/rerender/ios/bench.sh
@@ -0,0 +1,123 @@
+#!/usr/bin/env bash
+# RR0's film on the iPhone (docs/rerender.feature): bench.sh's runs on an iPhone, so the A15 sits beside the Mac and the
+# Windows PC. Each shot composition is bundled on the Mac (`raea bundle --composition-bundle`, one wrapper per shot,
+# since a composition bundle holds one), the bench app (app/, on libraea_rerender_ios.a) is built, installed fresh and
+# launched once per render through `lane phone`, so each render is a cold process, as each chunk is on the Mac:
+# first shot 1 straight after the install: no pipeline or shader cache yet (the first-ever run)
+# chunked shots 1-6 one after another (a phone renders one at a time; there's no join on the phone)
+# one the "film" composition as one render (before RR1 it holds shot 1's look, as on the Mac)
+# Per render: the app's own wall time, the first frame's time from the process's start (read from the kernel, so no
+# clock is shared with the Mac), RAEA_TIMES' split a frame, RAEA_FRAME_LOG's react / sync / gpu, and the peak physical
+# footprint (what jetsam counts). Writes OUT/run.json.
+# bench/rerender/ios/bench.sh [OUT] (the phone unlocked; it stays awake while the app runs)
+# RAEA_BIN the raea that bundles the shots (target/release/raea)
+# DEVICE the phone's devicectl id (the iPhone 13 Pro Max)
+# BUILD=0 reuse the app already installed (no bundle, build or install; the "first" run is then skipped)
+# KEEP=1 copy each render's MP4 back to OUT
+# Exits 1 when a render fails.
+set -u
+cd "$(dirname "$0")/../../.." || exit 2
+ROOT=$PWD
+H=$ROOT/bench/rerender/ios
+APPD=$H/app
+BIN=${RAEA_BIN:-$ROOT/target/release/raea}
+OUT=${1:-${TMPDIR:-/tmp}/raea-rerender-ios}
+DEVICE=${DEVICE:-00008110-000C29AA26D9801E}
+APP=io.raea.rerenderbench
+KEY=$HOME/.appstoreconnect/private_keys/AuthKey_265V39N664.p8
+LIB=$ROOT/target/aarch64-apple-ios/release
+command -v jq > /dev/null || { echo "bench: needs jq"; exit 2; }
+mkdir -p "$OUT"
+now() { perl -MTime::HiRes=time -e 'printf "%.3f", time'; }
+span() { echo "$1 $2" | awk '{printf "%.3f", $2 - $1}'; }
+
+if [ "${BUILD:-1}" = 1 ]; then
+ [ -x "$BIN" ] || { echo "bench: no raea at $BIN (set RAEA_BIN)"; exit 2; }
+ # one wrapper a composition, each importing the film's shots.tsx
+ mkdir -p "$OUT/src" "$APPD/Bundle"
+ cp "$ROOT/bench/rerender/shots.tsx" "$OUT/src/shots.tsx"
+ for k in 1 2 3 4 5 6; do
+ printf '%s\n' 'import { Composition, registerRoot } from "raea";' 'import { FPS, SHOT, one } from "./shots";' \
+ "registerRoot(() => <Composition id=\"shot-$k\" component={one($((k - 1)))} width={1920} height={1080} fps={FPS} durationInFrames={SHOT} />);" > "$OUT/src/shot-$k.tsx"
+ done
+ printf '%s\n' 'import { Composition, registerRoot } from "raea";' 'import { FPS, SHOT, Film } from "./shots";' \
+ 'registerRoot(() => <Composition id="film" component={Film} width={1920} height={1080} fps={FPS} durationInFrames={SHOT * 6} />);' > "$OUT/src/film.tsx"
+ echo "bench: bundling the seven compositions"
+ for c in shot-1 shot-2 shot-3 shot-4 shot-5 shot-6 film; do
+ "$BIN" bundle "$OUT/src/$c.tsx" --composition-bundle -o "$APPD/Bundle/$c.comp.js" > "$OUT/bundle-$c.log" 2>&1 \
+ || { echo "bench: $c didn't bundle: $(tail -2 "$OUT/bundle-$c.log")"; exit 1; }
+ done
+ echo "bench: building libraea_rerender_ios.a"
+ lane build -- env CARGO_INCREMENTAL=0 IPHONEOS_DEPLOYMENT_TARGET=16.0 cargo build --release -p raea-rerender-ios --target aarch64-apple-ios -j 6 \
+ > "$OUT/cargo.log" 2>&1 || { echo "bench: the library didn't build: $(grep -E '^error' -A4 "$OUT/cargo.log" | head -8)"; exit 1; }
+ echo "bench: building the app"
+ (cd "$APPD" && xcodegen generate > /dev/null) || { echo "bench: xcodegen failed"; exit 1; }
+ lane build -- xcodebuild -project "$APPD/RerenderBench.xcodeproj" -target RerenderBench -configuration Release -sdk iphoneos \
+ -allowProvisioningUpdates -authenticationKeyPath "$KEY" -authenticationKeyID 265V39N664 \
+ -authenticationKeyIssuerID ca81fc03-e9d2-4af2-9273-b9d1a3052169 RUST_LIB_DIR="$LIB" SYMROOT="$OUT/xcode" build > "$OUT/xcode.log" 2>&1
+ grep -q "BUILD SUCCEEDED" "$OUT/xcode.log" || { echo "bench: the app didn't build: $(grep -E 'error:' "$OUT/xcode.log" | head -4)"; exit 1; }
+ echo "bench: installing it fresh"
+ # a fresh install: the first launch has no shader or pipeline cache, as raea's first-ever run on a machine
+ lane phone -- xcrun devicectl device uninstall app --device "$DEVICE" "$APP" > /dev/null 2>&1
+ lane phone -- xcrun devicectl device install app --device "$DEVICE" "$OUT/xcode/Release-iphoneos/RerenderBench.app" > "$OUT/install.log" 2>&1 \
+ || { echo "bench: install failed: $(tail -3 "$OUT/install.log")"; exit 1; }
+fi
+
+copy_from() {
+ xcrun devicectl device copy from --device "$DEVICE" --domain-type appDataContainer --domain-identifier "$APP" \
+ --source "Documents/$1" --destination "$2" > /dev/null 2>&1
+}
+
+# render ID COMP: one launch of the app rendering COMP; its log, frame log and report in OUT/ID.{log,tsv,json}
+render() {
+ local id=$1 comp=$2 t0 t1
+ echo "bench: $id ($comp)"
+ t0=$(now)
+ lane phone -- xcrun devicectl device process launch --terminate-existing --console --device "$DEVICE" \
+ --environment-variables "{\"RR_COMP\": \"$comp\"}" "$APP" > "$OUT/$id.console" 2>&1
+ t1=$(now)
+ span "$t0" "$t1" > "$OUT/$id.launch"
+ copy_from "$comp.log" "$OUT/$id.log"; copy_from "$comp.tsv" "$OUT/$id.tsv"; copy_from "$comp.json" "$OUT/$id.json"
+ [ "${KEEP:-0}" = 1 ] && copy_from "$comp.mp4" "$OUT/$id.mp4"
+ [ -s "$OUT/$id.json" ] && [ "$(jq -r .code "$OUT/$id.json")" = 0 ] && grep -q '^APPLIED' "$OUT/$id.log" \
+ || { echo "bench: $id failed: $(grep -hE 'REFUSED|error|panicked' "$OUT/$id.log" "$OUT/$id.console" 2> /dev/null | head -3)"; return 1; }
+}
+
+# stats ID: one render's numbers, as bench.sh's, plus the launch as the Mac saw it and the peak footprint
+stats() {
+ local id=$1 times first frames
+ times=$(grep -m1 '^{.*"fps_incl_encode"' "$OUT/$id.log" 2> /dev/null || echo '{}')
+ first=$(grep "the fed render's first frame" "$OUT/$id.log" 2> /dev/null | tail -1 | awk '{print $3}')
+ frames=$(awk -F'\t' 'NR == 2 { r0 = $2; s0 = $3; g0 = $8 }
+ NR > 2 { n++; r += $2; s += $3; g += $8 }
+ END { printf "{\"first\":{\"react\":%.2f,\"sync\":%.2f,\"gpu\":%.2f},\"rest_mean\":{\"react\":%.2f,\"sync\":%.2f,\"gpu\":%.2f},\"rows\":%d}", r0, s0, g0, (n ? r / n : 0), (n ? s / n : 0), (n ? g / n : 0), n + 1 }' "$OUT/$id.tsv" 2> /dev/null || echo '{}')
+ jq -n --arg id "$id" --argjson app "$(cat "$OUT/$id.json" 2> /dev/null || echo '{}')" --argjson launch "$(cat "$OUT/$id.launch")" \
+ --argjson first "${first:-null}" --argjson times "$times" --argjson log "$frames" \
+ '{id: $id, wall_s: $app.wall_s, launch_s: $launch, peak_mb: $app.peak_mb, first_frame_ms: $first, frames: $times.frames,
+ encoder: $times.video, ms_per_frame: $times.times.ms_per_frame, fps_incl_encode: $times.fps_incl_encode, frame_log: $log}'
+}
+
+status=0
+first=null
+if [ "${BUILD:-1}" = 1 ]; then
+ echo "bench: shot 1 on a fresh install"
+ render first shot-1 || status=1
+ first=$(stats first)
+fi
+echo "bench: six shot renders, one at a time"
+for k in 1 2 3 4 5 6; do render shot-$k shot-$k || status=1; done
+shots=$(for k in 1 2 3 4 5 6; do stats shot-$k; done | jq -s .)
+chunked=$(jq -n --argjson shots "$shots" \
+ '{p: 1, renders_s: ([$shots[].wall_s // 0] | add), launches_s: ([$shots[].launch_s] | add),
+ startups_s: ([$shots[].first_frame_ms // 0] | add / 1000),
+ frames_s: ([$shots[] | (.frames // 0) * (.ms_per_frame.wall // 0)] | add / 1000), shots: $shots}')
+echo "bench: chunked $(echo "$chunked" | jq -r '"\(.renders_s) s in the app (\(.launches_s) s launch to exit)"')"
+echo "bench: the film as one render"
+render film film || status=1
+one=$(stats film)
+echo "bench: one render $(echo "$one" | jq -r '"\(.wall_s) s, first frame \(.first_frame_ms) ms"')"
+info=$(xcrun devicectl device info details --device "$DEVICE" --json-output /dev/stdout 2> /dev/null | jq -c '.result | {os: ("iOS " + .deviceProperties.osVersionNumber), device: .hardwareProperties.marketingName, model: .hardwareProperties.productType}' 2> /dev/null || echo '{}')
+jq -n --argjson machine "$info" --argjson first "$first" --argjson chunked "$chunked" --argjson one "$one" \
+ '{film: {frames: 900, width: 1920, height: 1080, fps: 30, shots: 6}, machine: $machine, first: $first, chunked: $chunked, one: $one}' > "$OUT/run.json"
+echo "bench: $OUT/run.json"
+exit $status
diff --git a/bench/rerender/ios/src/lib.rs b/bench/rerender/ios/src/lib.rs
new file mode 100644
index 00000000..e2fab046
--- /dev/null
+++ b/bench/rerender/ios/src/lib.rs
@@ -0,0 +1,66 @@
+//! RR0's film on the iPhone (docs/rerender.feature, bench/rerender/ios/bench.sh). The bench app's main.m calls
+//! `raea_rerender_run` once a launch, so each composition renders in a process of its own, cold, as bench.sh renders
+//! each chunk on the Mac. What it prints goes to the console devicectl streams back: raea's startup marks (timed from the
+//! process's own start, read from the kernel, so no clock is shared with the Mac) and RAEA_TIMES' line; the frame log
+//! goes to the app's Documents.
+
+use std::ffi::{CStr, c_char};
+use std::path::Path;
+
+/// When this process started, in ms since the Unix epoch, from the kernel's process table: what RAEA_STARTUP_TRACE
+/// counts its marks from (raea-cli's spawner passes its own clock; here the process is its own spawner).
+fn started_ms() -> Option<u64> {
+ #[cfg(target_vendor = "apple")]
+ unsafe {
+ // struct kinfo_proc (648 bytes) opens with kp_proc, whose first member is a union holding p_starttime (a
+ // timeval: i64 seconds, i32 microseconds); read through sysctl, so no libc crate is needed for one call
+ unsafe extern "C" {
+ fn sysctl(name: *const i32, namelen: u32, oldp: *mut u8, oldlenp: *mut usize, newp: *const u8, newlen: usize) -> i32;
+ fn getpid() -> i32;
+ }
+ const CTL_KERN: i32 = 1;
+ const KERN_PROC: i32 = 14;
+ const KERN_PROC_PID: i32 = 1;
+ let mib = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()];
+ let mut buf = [0u8; 648];
+ let mut len = buf.len();
+ if sysctl(mib.as_ptr(), 4, buf.as_mut_ptr(), &mut len, std::ptr::null(), 0) != 0 || len < 16 {
+ return None;
+ }
+ let sec = i64::from_ne_bytes(buf[0..8].try_into().ok()?);
+ let usec = i32::from_ne_bytes(buf[8..12].try_into().ok()?);
+ Some((sec as u64) * 1000 + (usec as u64) / 1000)
+ }
+ #[cfg(not(target_vendor = "apple"))]
+ None
+}
+
+/// Renders the bundled composition `bundle` (NAME.comp.js) to `out` (an .mp4), its media under the bundle's folder, and
+/// returns raea's own line for it (APPLIED or REFUSED), as `raea render --bundle` prints it. 0 when it rendered.
+///
+/// # Safety
+/// `bundle` and `out` are NUL-terminated paths.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn raea_rerender_run(bundle: *const c_char, out: *const c_char) -> i32 {
+ let js = unsafe { CStr::from_ptr(bundle) }.to_string_lossy().into_owned();
+ let out = unsafe { CStr::from_ptr(out) }.to_string_lossy().into_owned();
+ if let Some(t0) = started_ms() {
+ // SAFETY: set before any thread of raea's starts (main.m calls this first)
+ unsafe { std::env::set_var("RAEA_STARTUP_TRACE", t0.to_string()) };
+ }
+ raea_runtime_react::startup_mark("main");
+ raea_runtime_react::native::register();
+ raea_runtime_react::startup_mark("native calls registered");
+ let js = Path::new(&js);
+ let dir = js.parent().unwrap_or(Path::new("."));
+ match raea_runtime_export::render_bundle(js, dir, Path::new(&out), None) {
+ Ok(said) => {
+ println!("{said}");
+ 0
+ }
+ Err(e) => {
+ println!("REFUSED {e}");
+ 1
+ }
+ }
+}
diff --git a/bench/rerender/shots.tsx b/bench/rerender/shots.tsx
new file mode 100644
index 00000000..07d93555
--- /dev/null
+++ b/bench/rerender/shots.tsx
@@ -0,0 +1,188 @@
+// RR0's film, its set and its six shots (docs/rerender.feature): film.tsx registers them as compositions, and the
+// iPhone bench (ios/bench.sh) bundles one composition at a time from these. See film.tsx for what the film is.
+import { AbsoluteFill, useCurrentFrame } from "raea";
+import {
+ AmbientOcclusion, AntiAliasing, Atmosphere, Bloom, Canvas3D, DepthOfField, Fog, FogVolume, Grade, Grass, Instances,
+ ToneMapping, Shadows, VolumetricFog, grow, manifold, scatter,
+} from "raea/3d";
+import { Camera3d } from "raea/camera";
+import { AmbientLight, DirectionalLight, PointLight, SpotLight } from "raea/light";
+import { Mesh3d } from "raea/mesh";
+import { StandardMaterial } from "raea/pbr";
+import { Transform } from "raea/transform";
+
+export const FPS = 30;
+export const SHOT = 150;
+type V3 = [number, number, number];
+
+// ---------------------------------------------------------------- the set, built once
+
+const OAK = { height: 7, crown: "dome" as const, points: 1500, leaves: 4, leaf: 0.14, seed: 3 };
+const PINE = { height: 10, crown: "cone" as const, points: 1100, leaves: 5, leaf: 0.1, width: 0.5, seed: 4 };
+const OAK_WOOD = grow.tree(OAK, "wood");
+const OAK_LEAVES = grow.tree(OAK, "leaves");
+const PINE_WOOD = grow.tree(PINE, "wood");
+const PINE_LEAVES = grow.tree(PINE, "leaves");
+const ROCK = grow.boulder({ size: 1.4, rough: 0.5, seed: 5 });
+// the forest and meadow, west of the street; the room's walls and the street's blocks are kept clear
+const WOODS = { min: [-110, -70] as [number, number], max: [-8, 30] as [number, number] };
+const GLADE = [{ min: [-40, -12] as [number, number], max: [-22, 6] as [number, number] }];
+const OAKS = scatter({ area: WOODS, count: 110, spacing: 5, seed: 11, scale: [0.7, 1.3], avoid: GLADE });
+const PINES = scatter({ area: WOODS, count: 90, spacing: 5, seed: 13, scale: [0.8, 1.4], avoid: GLADE, clearOf: OAKS });
+// the meadow under the trees: grass the engine grows, about 40k clumps
+const MEADOW = { min: [-75, -40] as [number, number], max: [-5, 45] as [number, number] };
+const flat = () => 0;
+const ROCKS = scatter({ area: { min: [-90, -60], max: [-10, 30] }, count: 40, spacing: 3, seed: 12, scale: [0.4, 1.6] });
+// the room: a 10 x 4 x 8 box with its inside carved out and a window in the east wall
+const ROOM = manifold.box(10.4, 4.4, 8.4).minus(manifold.box(10, 4, 8)).minus(manifold.box(1, 1.6, 3).move(5, 0.4, 0));
+const TABLE = manifold.box(2.4, 0.08, 1.2).move(0, 0.76, 0)
+ .union(manifold.box(0.08, 0.76, 0.08).move(-1.1, 0.38, -0.5)).union(manifold.box(0.08, 0.76, 0.08).move(1.1, 0.38, -0.5))
+ .union(manifold.box(0.08, 0.76, 0.08).move(-1.1, 0.38, 0.5)).union(manifold.box(0.08, 0.76, 0.08).move(1.1, 0.38, 0.5));
+const CUP = manifold.cylinder(0.05, 0.11).minus(manifold.cylinder(0.042, 0.11).move(0, 0, 0.01)).rotate(-90, 0, 0);
+// the street: two rows of blocks with windows, lamps between them
+const BLOCK = [0, 1, 2, 3].reduce((s, i) => s.minus(manifold.box(1.2, 1.6, 0.4).move(-3 + i * 2, 2, 3)), manifold.box(8, 9, 6).move(0, 4.5, 0));
+const BLOCKS: { at: V3; h: number }[] = Array.from({ length: 36 }, (_, i) => ({ at: [40 + (i % 12) * 9, 0, [-8, 8, -22][Math.floor(i / 12)]], h: 0.8 + ((i * 37) % 5) / 6 }));
+// the room's shelves: 480 books along the back wall
+const BOOK = manifold.box(0.04, 0.24, 0.17);
+const BOOKS = Array.from({ length: 480 }, (_, i) => {
+ const row = Math.floor(i / 120), col = i % 120;
+ return { position: [-4.6 + col * 0.075, 0.6 + row * 0.42, 63.8] as V3, rotation: [0, 0, ((i * 13) % 7 - 3) * 0.02] as V3, scale: [1, 0.8 + ((i * 7) % 5) * 0.08, 1] as V3 };
+});
+const SHELF = manifold.box(9.2, 0.03, 0.3);
+const GROUND = manifold.box(400, 1, 400).move(0, -0.5, 0);
+const BULB = manifold.sphere(0.18);
+const LAMP_GLOW = "#ffd890";
+const LAMPS: V3[] = [0, 1, 2, 3, 4].map((i) => [42 + i * 10, 4, i % 2 ? 4 : -4]);
+
+function Set() {
+ return (
+ <>
+ <Mesh3d name="ground" shape={GROUND}><StandardMaterial base_color="#5a5e48" perceptual_roughness={0.95} /></Mesh3d>
+ <Instances at={OAKS} shape={OAK_WOOD}><StandardMaterial base_color="#4a3826" perceptual_roughness={0.9} /></Instances>
+ <Instances at={OAKS} shape={OAK_LEAVES}><StandardMaterial base_color="#3f6b2c" perceptual_roughness={0.8} /></Instances>
+ <Instances at={PINES} shape={PINE_WOOD}><StandardMaterial base_color="#3d2c1e" perceptual_roughness={0.9} /></Instances>
+ <Instances at={PINES} shape={PINE_LEAVES}><StandardMaterial base_color="#28472a" perceptual_roughness={0.85} /></Instances>
+ <Grass name="meadow" area={MEADOW} height={flat} density={7} />
+ <Instances at={ROCKS} shape={ROCK}><StandardMaterial base_color="#77736a" perceptual_roughness={0.85} /></Instances>
+ <Mesh3d name="room" shape={ROOM} transform={Transform.fromXyz(0, 2, 60)}><StandardMaterial base_color="#d8cdb8" perceptual_roughness={0.9} /></Mesh3d>
+ <Mesh3d name="table" shape={TABLE} transform={Transform.fromXyz(0, 0, 60)}><StandardMaterial base_color="#6b4a2f" perceptual_roughness={0.6} /></Mesh3d>
+ {[-0.6, 0, 0.5].map((x, i) => (
+ <Mesh3d key={i} name={`cup-${i}`} shape={CUP} transform={Transform.fromXyz(x, 0.825, 60 + (i - 1) * 0.2)}><StandardMaterial base_color={["#e9e4da", "#2f4f6f", "#b34a2f"][i]} perceptual_roughness={0.3} /></Mesh3d>
+ ))}
+ {BLOCKS.map((b, i) => (
+ <Mesh3d key={i} name={`block-${i}`} shape={BLOCK} transform={Transform.fromXyz(...b.at).withScale([1, b.h, 1])}><StandardMaterial base_color={i % 3 ? "#8b8580" : "#6d6660"} perceptual_roughness={0.8} /></Mesh3d>
+ ))}
+ <Instances at={BOOKS} shape={BOOK}><StandardMaterial base_color="#7a3b2e" perceptual_roughness={0.7} /></Instances>
+ {[0, 1, 2, 3].map((r) => <Mesh3d key={r} name={`shelf-${r}`} shape={SHELF} transform={Transform.fromXyz(0, 0.465 + r * 0.42, 63.8)}><StandardMaterial base_color="#5b412b" perceptual_roughness={0.6} /></Mesh3d>)}
+ {LAMPS.map((p, i) => (
+ <Mesh3d key={i} name={`lamp-${i}`} shape={BULB} transform={Transform.fromXyz(...p)}><StandardMaterial base_color="#fff1c8" emissive={LAMP_GLOW} /></Mesh3d>
+ ))}
+ </>
+ );
+}
+
+// ---------------------------------------------------------------- the six shots
+
+interface Look {
+ sky: boolean;
+ /** the sky's colour behind the set where no Atmosphere draws one */
+ bg: string;
+ sun: { from: V3; lux: number; color: string };
+ ambient: number;
+ tone: "agx" | "aces" | "tony" | "neutral";
+ exposure: number;
+ fog?: { color: string; near: number; far: number };
+ volume?: { at: V3; size: V3; density: number };
+ bloom?: number;
+ ao?: boolean;
+ dof?: number;
+ grade: { temperature: number; tint?: number; saturation: number; contrast: number; vignette: number };
+ lamps: number;
+}
+interface Shot {
+ name: string;
+ title: string;
+ look: Look;
+ /** the camera at t seconds into the shot */
+ cam(t: number): { at: V3; look: V3; fov: number; focus?: number };
+}
+
+// shot 4's grade and light: the line change.sh rewrites, as a note would
+export const NOIR = { saturation: 0, contrast: 1.35, temperature: -0.02, sun: 25000, ambient: 400 };
+
+const lerp = (a: V3, b: V3, u: number): V3 => [a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u, a[2] + (b[2] - a[2]) * u];
+
+export const SHOTS: Shot[] = [
+ {
+ name: "dawn", title: "Dawn",
+ look: { sky: true, bg: "#000000", sun: { from: [-60, 8, -40], lux: 30000, color: "#ffd2a0" }, ambient: 200, tone: "agx", exposure: 0, fog: { color: "#e8c9a8", near: 30, far: 160 }, grade: { temperature: 0.05, saturation: 1.05, contrast: 1, vignette: 0.2 }, lamps: 0 },
+ cam: (t) => ({ at: lerp([-20, 2, 25], [-28, 2.2, 12], t / 5), look: [-45, 3, -10], fov: 40 }),
+ },
+ {
+ name: "night", title: "Night",
+ look: { sky: false, bg: "#06080e", sun: { from: [30, 40, 20], lux: 40, color: "#9fb4ff" }, ambient: 10, tone: "aces", exposure: 1.5, volume: { at: [62, 4, 0], size: [60, 10, 30], density: 0.12 }, bloom: 0.6, grade: { temperature: -0.08, tint: 0.06, saturation: 0.9, contrast: 1.1, vignette: 0.4 }, lamps: 400000 },
+ cam: (t) => ({ at: [36, 2, lerp([-3, 0, 0], [3, 0, 0], t / 5)[0]], look: [70, 3, 0], fov: 45 }),
+ },
+ {
+ name: "interior", title: "Interior",
+ look: { sky: false, bg: "#1a1d22", sun: { from: [20, 10, 60], lux: 15000, color: "#fff0d8" }, ambient: 120, tone: "agx", exposure: 1, ao: true, dof: 1.8, grade: { temperature: 0.03, saturation: 1, contrast: 1.05, vignette: 0.3 }, lamps: 0 },
+ cam: (t) => { const at = lerp([-3.5, 1.6, 57], [-1.6, 1.25, 58.8], t / 5); return { at, look: [0, 0.85, 60], fov: 35, focus: Math.hypot(at[0], at[1] - 0.85, at[2] - 60) }; },
+ },
+ {
+ name: "noir", title: "Noir",
+ look: { sky: false, bg: "#5a5a5a", sun: { from: [80, 30, -40], lux: NOIR.sun, color: "#ffffff" }, ambient: NOIR.ambient, tone: "tony", exposure: 1.5, grade: { temperature: NOIR.temperature, saturation: NOIR.saturation, contrast: NOIR.contrast, vignette: 0.55 }, lamps: 0 },
+ cam: (t) => ({ at: lerp([38, 1.7, 0], [60, 1.7, 0], t / 5), look: lerp([48, 4, -6], [70, 4, -6], t / 5), fov: 50 }),
+ },
+ {
+ name: "overcast", title: "Overcast",
+ look: { sky: false, bg: "#c9ced4", sun: { from: [0, 60, 10], lux: 8000, color: "#e6ecf2" }, ambient: 600, tone: "neutral", exposure: 0.5, fog: { color: "#c9ced4", near: 10, far: 90 }, grade: { temperature: -0.02, saturation: 0.8, contrast: 0.95, vignette: 0.1 }, lamps: 0 },
+ cam: (t) => ({ at: lerp([-30, 1.5, 30], [-30, 9, 30], t / 5), look: [-50, 4, -5], fov: 55 }),
+ },
+ {
+ name: "sunset", title: "Sunset",
+ look: { sky: true, bg: "#000000", sun: { from: [-100, 3, 20], lux: 40000, color: "#ff9a5a" }, ambient: 80, tone: "agx", exposure: 0.5, bloom: 0.35, dof: 2.8, grade: { temperature: 0.1, saturation: 1.15, contrast: 1.05, vignette: 0.5 }, lamps: 0 },
+ cam: (t) => { const a = 0.6 + (t / 5) * 0.5; return { at: [-40 + Math.cos(a) * 30, 4, -5 + Math.sin(a) * 30], look: [-40, 3, -5], fov: 28, focus: 30 }; },
+ },
+];
+
+/** One shot's frame: the set, the shot's look, its camera at t, and its title over the picture. */
+export function Frame({ k, t }: { k: number; t: number }) {
+ const s = SHOTS[k];
+ const L = s.look;
+ const c = s.cam(t);
+ return (
+ <AbsoluteFill style={{ background: L.bg }}>
+ <Canvas3D>
+ <Camera3d key={k === 5 ? "B" : "A"} transform={Transform.fromXyz(...c.at).lookingAt(c.look, [0, 1, 0])} projection={{ Perspective: { fov: (c.fov * Math.PI) / 180, near: 0.1, far: 400 } }}>
+ {L.dof ? <DepthOfField focal_distance={c.focus ?? 10} aperture_f_stops={L.dof} /> : null}
+ </Camera3d>
+ {L.sky ? <Atmosphere light /> : null}
+ <DirectionalLight name="sun" transform={Transform.fromXyz(...L.sun.from).lookingAt([0, 0, 0], [0, 1, 0])} illuminance={L.sun.lux} color={L.sun.color} shadow_maps_enabled soft_shadow_size={1.5} />
+ {L.ao ? <SpotLight name="pendant" transform={Transform.fromXyz(0, 3.6, 60).lookingAt([0, 0, 60], [1, 0, 0])} intensity={60000} color="#ffd9a8" range={12} outer_angle={0.9} inner_angle={0.4} radius={0.08} shadow_maps_enabled soft_shadows_enabled /> : null}
+ <AmbientLight brightness={L.ambient} />
+ {LAMPS.map((p, i) => <PointLight key={i} name={`lamp-light-${i}`} transform={Transform.fromXyz(...p)} intensity={L.lamps} color={LAMP_GLOW} range={18} volumetric={L.lamps > 0} shadow_maps_enabled={L.lamps > 0} visibility={L.lamps > 0 ? "Visible" : "Hidden"} />)}
+ <ToneMapping mode={L.tone} exposure={L.exposure} />
+ {L.fog ? <Fog color={L.fog.color} near={L.fog.near} far={L.fog.far} /> : null}
+ {L.volume ? <><VolumetricFog steps={96} /><FogVolume name="haze" position={L.volume.at} scale={L.volume.size} density={L.volume.density} /></> : null}
+ {L.bloom ? <Bloom intensity={L.bloom} threshold={0.9} /> : null}
+ {L.ao ? <AmbientOcclusion quality="ultra" /> : null}
+ <AntiAliasing mode={L.ao ? "smaa" : "msaa"} />
+ <Shadows mapSize={8192} distance={L.ao ? 20 : 120} cascades={4} />
+ <Grade temperature={L.grade.temperature} tint={L.grade.tint ?? 0} saturation={L.grade.saturation} midtones={{ contrast: L.grade.contrast }} vignette={L.grade.vignette} />
+ <Set />
+ </Canvas3D>
+ <div style={{ position: "absolute", left: 120, bottom: 150, fontFamily: "Helvetica, Arial, sans-serif", color: "#fff", textShadow: "0 2px 12px rgba(0,0,0,0.7)" }}>
+ <div style={{ fontSize: 22, letterSpacing: "0.3em", opacity: 0.8 }}>SHOT {k + 1}</div>
+ <div style={{ fontSize: 64, fontWeight: 700, opacity: Math.min(1, t * 2) }}>{s.title}</div>
+ </div>
+ </AbsoluteFill>
+ );
+}
+
+/** The whole film: shot k for the frame's 5 s, each from its own start. */
+export function Film() {
+ const f = useCurrentFrame();
+ return <Frame k={Math.min(5, Math.floor(f / SHOT))} t={(f % SHOT) / FPS} />;
+}
+/** Shot k alone, from its start. */
+export const one = (k: number) => function OneShot() { return <Frame k={k} t={useCurrentFrame() / FPS} />; };
diff --git a/docs/rerender.feature b/docs/rerender.feature
index f8188271..0359de84 100644
--- a/docs/rerender.feature
+++ b/docs/rerender.feature
@@ -18,12 +18,45 @@ Feature: Re-render, don't stitch: one render changes anything per frame, redraws
Rule: Measure first
+ @done
Scenario: RR0. A heavy multi-shot film to measure, and today's numbers on Mac and Windows
+ # Status 11-10: measured. The film is made from code (shots.tsx; content/rome's sets are gone) and its frames cost
+ # 10-45 ms on the Mac, so start-ups and joins weigh more than drawing does.
+ # Mac (M5 Pro, the 08:52 raea build): six chunks 3 at a time joined with ffmpeg -c copy, 16.3 s on a quiet machine
+ # and 25.0, 25.5, 26.9 s with 5-6 other jobs running; one render 31.4 s quiet, 30.9-38.5 s loaded. Each chunk's
+ # first frame comes 1.7-1.8 s after its spawn (about 0.6 s of it the restart when a render meets its first 3D
+ # frame; frame 0's sync 0.35-1.05 s, the pipelines being made), so the six chunks spend 10.5-16.2 s starting. A
+ # steady frame: React 1.0-1.7 ms, sync 6-15 ms, GPU wait 0-43 ms, readback and encode (VideoToolbox) under 1 ms.
+ # The note by hand (change.sh): shot 4 again 3.4-6.0 s and the join 0.15-0.23 s, against the whole film again
+ # 29.4-43.5 s.
+ # Windows (cuda-box, RTX 4070, v0.1.1-rc2, bench.ps1): no ffmpeg there, so the join is raea media concat, which
+ # re-encodes. Chunked 71.0 s: renders 23.6 s and the join 47.3 s. One render 39.0 s; its first frame 6.8 s, as it
+ # bakes all 900 frames' rows first (a chunk's 2.2-2.5 s; the first run on the machine 6.5-8.3 s). A steady frame:
+ # React 12 ms (10x the Mac's: QuickJS there, JavaScriptCore here), sync 12-24 ms, GPU wait 2-24 ms; openh264 isn't
+ # the bottleneck. The note by hand: 13.3 s and a 51.4 s join, 64.7 s, more than the whole film again (38.4 s).
+ # One render holding six looks, estimated from the chunks' frame costs without their start-ups: 27.7 s on the
+ # quiet Mac and 45.8 s on Windows (both over-counted: three chunks shared the GPU).
+ # The two biggest costs: on the Mac the start-ups (six cold processes) and GPU wait; on Windows the re-encoding
+ # join (47-51 s) and a frame's CPU side (React on QuickJS and sync, 24-36 ms). RR11-RR13 read their gates
+ # against these.
+ # The iPhone row (not a gate; ios/bench.sh on an iPhone 13 Pro Max, A15, iOS 27.0.1, jitless JavaScriptCore):
+ # shots 3-5 at 134, 61 and 265 ms a frame (GPU wait 64, 22 and 184 ms; React 4-13 ms), first frame 2.5-3.2 s
+ # after the launch and 5.0 s on a fresh install, peak footprint 2.4-2.8 GB. Shots 1 and 6 and the film can't be
+ # drawn there: Bevy 0.20's atmosphere samples its Rgba32Float medium LUTs with a filtering sampler, which the A15
+ # can't filter (RR9's, in vendor/ and upstream). raea said APPLIED on those videos without their 3D (handed to
+ # DR3's lane). Shot 2 is killed by iOS (SIGKILL, no report) at its first 3D frame, with the increased-memory
+ # entitlement as well.
+ # Noise: the same binary ran 16-27 s chunked across four runs as the machine's load changed, so later gates run
+ # the old and new binaries interleaved in one sitting.
Given the plan
| crate | file | lines | job |
- | - | bench/rerender/film.tsx | 220 | six shots of content/rome's sets, about 30 s at 1920x1080, a different look on each (grade, fog, bloom, depth of field, tonemapping) and two cameras; also each shot as its own composition, as agents render today |
+ | - | bench/rerender/shots.tsx | 220 | six 5 s shots on one set made from code (no media files, so it renders alike on every OS; content/rome's sets are gone), 900 frames at 1920x1080, a different look on each (grade, fog, bloom, depth of field, tonemapping, SSAO, volumetric fog, sky) and two cameras |
+ | - | bench/rerender/film.tsx | 40 | the film as one composition, and each shot as its own composition, as agents render today |
| - | bench/rerender/bench.sh | 160 | renders it with RAEA_FRAME_LOG and RAEA_TIMES and writes run.json: wall time, and per frame the split into start-up, React/JS, Bevy CPU, wgpu submit, GPU by pass, readback and encode |
| - | bench/rerender/change.sh | 80 | the "one note" case: changes shot 4's grade and lights, then times what it takes to get the whole film again |
+ | - | bench/rerender/bench.ps1 | 160 | bench.sh and change.sh for Windows, in its own PowerShell 5.1 (no bash, jq or ffmpeg there) |
+ | raea-rerender-ios | bench/rerender/ios/src/lib.rs | 80 | the iPhone row, not a gate: one composition bundle rendered in a cold process, its start-up marks timed from the kernel's process start |
+ | - | bench/rerender/ios/bench.sh | 140 | bench.sh's runs on the iPhone through a small app (ios/app), one launch a render, plus the first launch after a fresh install |
Then bench.sh runs on the Mac and on the Windows PC, and this scenario records both splits
And it records today's two ways to get the film: six chunk renders joined with ffmpeg (what agents do), and
what one render would cost if it could hold six looks (the chunks' frame costs without their start-ups)
diff --git a/io/os/Cargo.toml b/io/os/Cargo.toml
index e008d050..21176fbe 100644
--- a/io/os/Cargo.toml
+++ b/io/os/Cargo.toml
@@ -9,13 +9,17 @@ description = "The system's host calls both app targets answer (docs/targets.fea
[dependencies]
serde_json = "1"
base64 = "0.22"
+pollster = "0.4"
+
+# the system's side, on the desktops. iOS builds none of it (none of the three has an iOS backend) and answers every
+# call as a headless check does: raea renders there (bench/rerender/ios), with no app UI
+[target.'cfg(not(target_os = "ios"))'.dependencies]
# a URL in the system's handler
opener = "0.9"
# the system clipboard (text)
arboard = { version = "3.7", default-features = false }
# the system's file and message dialogs; on Linux the xdg portal, never GTK
rfd = { version = "0.17", default-features = false, features = ["xdg-portal"] }
-pollster = "0.4"
[features]
# recorded.rs: T2d's recorded system calls, headless, for each target's test
diff --git a/io/os/src/dialog.rs b/io/os/src/dialog.rs
index f6571ed4..6fe2d2a3 100644
--- a/io/os/src/dialog.rs
+++ b/io/os/src/dialog.rs
@@ -1,6 +1,7 @@
//! dialog.message: the system's message dialog (rfd), answered with the index of the button pressed; headless, the
//! answer a dialog step queued.
+#[cfg(not(target_os = "ios"))]
use rfd::{AsyncMessageDialog, MessageButtons, MessageDialogResult, MessageLevel};
use serde_json::{Value, json};
@@ -18,6 +19,12 @@ pub(crate) fn message(args: &Value, done: Done) {
None => Err("dialog.message: headless, and no dialog step answers it".into()),
});
}
+ #[cfg(not(target_os = "ios"))]
+ system(args, labels, done);
+}
+
+#[cfg(not(target_os = "ios"))]
+fn system(args: &Value, labels: Vec<String>, done: Done) {
let level = match args["kind"].as_str() {
Some("warning") => MessageLevel::Warning,
Some("error") => MessageLevel::Error,
diff --git a/io/os/src/fs.rs b/io/os/src/fs.rs
index 790f9aaa..42ae6465 100644
--- a/io/os/src/fs.rs
+++ b/io/os/src/fs.rs
@@ -39,10 +39,12 @@ fn described(p: &Path) -> Value {
json!({"id": id, "name": p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(), "size": std::fs::metadata(p).map(|m| m.len()).unwrap_or(0)})
}
+#[cfg(not(target_os = "ios"))]
fn accept(args: &Value) -> Vec<String> {
args["accept"].as_array().map(|a| a.iter().filter_map(Value::as_str).map(|e| e.trim_start_matches('.').to_string()).collect()).unwrap_or_default()
}
+#[cfg(not(target_os = "ios"))]
fn dialog(args: &Value) -> rfd::AsyncFileDialog {
let exts = accept(args);
let d = rfd::AsyncFileDialog::new();
@@ -58,6 +60,7 @@ pub(crate) fn call(name: &str, args: &Value, done: Done) {
}
}
+#[cfg_attr(target_os = "ios", expect(unused_variables, reason = "iOS builds no dialogs"))]
fn pick(args: &Value, done: Done) {
if headless() {
return done(match scripted(|s| if let Scripted::Pick(f) = s { Some(f.clone()) } else { None }) {
@@ -65,17 +68,21 @@ fn pick(args: &Value, done: Done) {
None => Err("fs.pick: headless, and no pick step answers it".into()),
});
}
- let (multiple, d) = (args["multiple"] == json!(true), dialog(args));
- std::thread::spawn(move || {
- let files: Vec<PathBuf> = if multiple {
- pollster::block_on(d.pick_files()).unwrap_or_default().iter().map(|h| h.path().to_path_buf()).collect()
- } else {
- pollster::block_on(d.pick_file()).map(|h| vec![h.path().to_path_buf()]).unwrap_or_default()
- };
- done(Ok(Value::Array(files.iter().map(|p| described(p)).collect())));
- });
+ #[cfg(not(target_os = "ios"))]
+ {
+ let (multiple, d) = (args["multiple"] == json!(true), dialog(args));
+ std::thread::spawn(move || {
+ let files: Vec<PathBuf> = if multiple {
+ pollster::block_on(d.pick_files()).unwrap_or_default().iter().map(|h| h.path().to_path_buf()).collect()
+ } else {
+ pollster::block_on(d.pick_file()).map(|h| vec![h.path().to_path_buf()]).unwrap_or_default()
+ };
+ done(Ok(Value::Array(files.iter().map(|p| described(p)).collect())));
+ });
+ }
}
+#[cfg_attr(target_os = "ios", expect(unused_variables, reason = "iOS builds no dialogs"))]
fn save(args: &Value, done: Done) {
if headless() {
return done(match scripted(|s| if let Scripted::Save(f) = s { Some(f.clone()) } else { None }) {
@@ -83,10 +90,11 @@ fn save(args: &Value, done: Done) {
None => Err("fs.save: headless, and no save step answers it".into()),
});
}
- let d = dialog(args).set_file_name(args["name"].as_str().unwrap_or("untitled"));
- std::thread::spawn(move || {
- done(Ok(pollster::block_on(d.save_file()).map_or(Value::Null, |h| json!({"id": keep(h.path().to_path_buf())}))));
- });
+ #[cfg(not(target_os = "ios"))]
+ {
+ let d = dialog(args).set_file_name(args["name"].as_str().unwrap_or("untitled"));
+ std::thread::spawn(move || done(Ok(pollster::block_on(d.save_file()).map_or(Value::Null, |h| json!({"id": keep(h.path().to_path_buf())})))));
+ }
}
fn read(args: &Value) -> Result<Value, String> {
diff --git a/io/os/src/lib.rs b/io/os/src/lib.rs
index f101f94f..45d9e957 100644
--- a/io/os/src/lib.rs
+++ b/io/os/src/lib.rs
@@ -37,8 +37,9 @@ pub fn set_headless() {
HEADLESS.store(true, Ordering::Relaxed);
}
+/// Also always on iOS, which builds none of the system's side (Cargo.toml).
fn headless() -> bool {
- HEADLESS.load(Ordering::Relaxed)
+ cfg!(target_os = "ios") || HEADLESS.load(Ordering::Relaxed)
}
/// A check step's answer for the next dialog of its kind.
@@ -125,7 +126,10 @@ fn open(args: &Value) -> Result<Value, String> {
opened_list().lock().unwrap().push(url.to_string());
return Ok(Value::Null);
}
- opener::open(url).map(|()| Value::Null).map_err(|e| format!("os.open {url}: {e}"))
+ #[cfg(not(target_os = "ios"))]
+ return opener::open(url).map(|()| Value::Null).map_err(|e| format!("os.open {url}: {e}"));
+ #[cfg(target_os = "ios")]
+ unreachable!("headless on iOS");
}
/// The clipboard's text ("" when it holds none): the system's, or the process's own when headless. A page's text
@@ -142,7 +146,6 @@ pub fn set_clipboard_text(text: String) -> Result<(), String> {
/// The clipboard's text, or `text` written to it: the process's own when headless.
fn clipboard(text: Option<String>) -> Result<Value, String> {
static OWN: Mutex<String> = Mutex::new(String::new());
- static SYSTEM: Mutex<Option<arboard::Clipboard>> = Mutex::new(None);
if headless() {
let mut own = OWN.lock().unwrap();
return Ok(match text {
@@ -153,6 +156,15 @@ fn clipboard(text: Option<String>) -> Result<Value, String> {
None => json!(*own),
});
}
+ #[cfg(not(target_os = "ios"))]
+ return system_clipboard(text);
+ #[cfg(target_os = "ios")]
+ unreachable!("headless on iOS");
+}
+
+#[cfg(not(target_os = "ios"))]
+fn system_clipboard(text: Option<String>) -> Result<Value, String> {
+ static SYSTEM: Mutex<Option<arboard::Clipboard>> = Mutex::new(None);
// kept open: on X11 a clipboard's text lives as long as the process that set it holds it
let mut sys = SYSTEM.lock().unwrap();
if sys.is_none() {
diff --git a/tools/layers.toml b/tools/layers.toml
index 1ec8dc33..7e2c02ed 100644
--- a/tools/layers.toml
+++ b/tools/layers.toml
@@ -59,6 +59,7 @@ raea-sys-footage = "systems"
raea-perceive = "tools"
raea-bridge-bench = "tools"
raea-bevy-parity = "tools" # Bevy's own examples with the parity probe (docs/control.feature FC0a)
+raea-rerender-ios = "tools" # RR0's film on the iPhone (bench/rerender/ios): a static library the bench app calls
raea-sys-parity = "systems" # the parity probe, in raea's App and the examples'
raea-bench-swatch = "systems" # a Blitz widget fixture (bench/bridge/swatch) the plugin catalog declares: a leaf on vendored crates, so a runtime crate may build it in
raea-render = "runtime"