Compare commits

..
Author SHA1 Message Date
shinyobjectz f4b63dfaa9 BK3: glossy layers at the bounces, and the offset that hid bench_strips: 0 of 198 meshes over 1/3 stop against Cycles' real materials
GGX with F82 for metals and a dielectric layer over Lambert, after Cycles' Principled (its formulas, BSD-3-Clause, in
NOTICE), with filter glossy and an energy table made on the CPU. Held to three of Cycles' own cases and to CPU sums
(sun 0.03%, panel 0.6%, white 0.997-0.9998). Against the atelier with its real materials and adaptive sampling off, by
each mesh's total light: 0 of 198 over 1/3 stop over a texel's whole (0.997 of the light), 1 over its open part (1.002);
Lambert alone was 108 and 0.858.

Rays start 1e-6 of the model's size off a surface (was 1e-5, 0.15 mm in the atelier, whose strips are 0.2 mm apart):
bench_strips 0.558 to 1.068. trace() refuses short or non-finite texels.

Beside it, uncommitted in another lane's files: lightbake.py and look.py take --no-adaptive (not the default) and refuse
a picture that isn't there. Not @done: baked lights, drawn albedo, Vulkan and DX12.
2026-11-29 16:02:31 -08:00
shinyobjectz 0198d2f1b2 BK3: the open part of a texel against its whole footprint, and the setup timed in release
Cycles' diffuse-only atelier with adaptive sampling off, by each mesh's total light: 3 of 198 over 1/3 stop when a texel
is lit by its open part (0.997 of the total), 1 of 198 over its whole footprint as Cycles averages it (0.993). Release
setup: the table set 0.85 s, the atelier 19.9 s. Not @done.
2026-11-29 16:02:31 -08:00
shinyobjectz e4e2498a8a BK3: the jittered trace against Cycles without adaptive sampling: 3 of 198 meshes over 1/3 stop, total light 0.997
The atelier's diffuse-only scene, unclamped and unsmoothed, by each mesh's total light (zeros counted). Not @done: the
specular and metal bounces (14% of the light), bench_strips and the setup's cost are open.
2026-11-29 16:02:31 -08:00
shinyobjectz ee1be7dcca BK3: a texel's light comes from over the texel, and the trace is its own crate
raea-sys-lighttrace holds the kernel (lib.rs, wgsl/), a facility systems/rt and LT5's path tracer may build on; the
lightbake crate keeps the texels and calls it. The samples of a texel start from the open ones of 16 points over its
footprint (on its triangle, clear of its edges, not inside other geometry as BK2's rays judge it), in place of its
centre, so a ledge narrower than a texel counts as the part of it that can be seen, and a texel partly inside a block
is lit by its open part. Two tests fail with centre starts. A sample's random seed no longer repeats when the count
isn't a multiple of the pass.

lightbake.py (the blender guide, another lane's, uncommitted here) has an opt-in --no-adaptive, used for the
references of this comparison: Cycles' adaptive sampling bakes dark pockets up to 2x too dark. Not @done.
2026-11-29 16:02:31 -08:00
shinyobjectz 285d99bd49 BK3: what the biased meshes were (footprint and the reference's adaptive sampling)
46 meshes were counted biased by the mean log error on smoothed maps. By each mesh's total light, unsmoothed and with
zeros counted, 8 of 198 are over 1/3 stop. Four are the trace's: it starts every ray at the texel's centre where Cycles
jitters over the texel (traced 8x8 points a texel, the same texels, they reach 0.96-1.07 of Cycles). Four are the reference's: Cycles' adaptive sampling
stops dark pockets early, so it bakes them up to 2x too dark (with it off, 1.01-1.07). Corrects BK3's text, which said
all 46 were a trace error. The test run can now trace fine points a texel (RAEA_BAKE_FINE), pick meshes (RAEA_BAKE_ONLY)
and keeps zero texels in its dump. Not @done.
2026-11-29 16:02:31 -08:00
shinyobjectz 46d7131dbc BK3: panorama, sun and textures in the trace, and the atelier against Cycles (in progress)
The trace takes a panorama at its strength and rotation, the sun at later hits by shadow rays (its direct light left
out at the texel), and base colour textures. own.rs reads a .glb on its own second UVs, so a map is held to
lightbake.py's texel for texel.

Fixes a NaN: a ray going exactly straight up has no longitude, and atan2(0, 0) was NaN on Metal. It cost one texel of
the atelier at 1024 samples, and would otherwise only show in someone's frame. A test casting 134 million such rays
failed before the guard (33 values not finite) and passes after.

Removes the trace's indirect clamp: at 3 it kept 0.869 of the light of Cycles at the same clamp, where unclamped it
keeps 0.994.

Measured on the atelier (198 meshes, 2.36M texels, no fitted gain; the tables are in BK3): on plain diffuse materials
the trace's total light is 0.994 of Cycles', median -0.005 stops; against the real materials unclamped it is 0.857, mean
0.389 stops, with 14% of the light being speculars and metals. Not settled: 46 meshes are biased by over 1/3 stop on
matched materials, where Cycles against itself has 2. Not @done.
2026-11-29 16:02:31 -08:00
shinyobjectz 35dcba6b3f BK3: the atelier against its Cycles bake, and what the trace needs first
Planned, not run: the set's own second UVs, the panorama, the sun and base colour textures come before it. Says what the
reference is and isn't.
2026-11-29 16:02:31 -08:00
shinyobjectz a2dc602be2 BK5: what dry means, and animated weather bakes once
The bounce matches the frame, so dry keeps the season's drawn values. Weather animated over a shot bakes at the composition's
first frame with the <LightBake>, whichever is rendered first, and the report says so. Blending two bakes is not built.
2026-11-29 16:02:31 -08:00
shinyobjectz f5280de0d7 BK3: what a bake bounces of raea/wear, and BK5's key
Caused wear bounces as any albedo; the weather and season layer bounces at the values the composition gives, dry with none
given, and the key holds the wear settings and those values. The kernel's modules stay (a texture-space draw was considered).
Left unsettled in the file: the default day's dust, and weather animated over frames.
2026-11-29 16:02:31 -08:00
shinyobjectz bb40f885ec BK3: what the drawn-albedo modules must take, and procmat's written as one (not compiled)
docs/bake.feature: the header's and BK3's account of the ray tracing agree (the bake's own BLAS and TLAS, not
systems/rt's); what the raster takes from screen derivatives, implicit-level reads and the eye, and what a ray hit gives in
place of each; a user's <ShaderExtension> bounces its base colour and is named; two questions left open. BK5 takes its
BLAS from the composition's own meshes.

systems/procmat/src/drawn.wesl: procmat.wesl's noise, patterns and use as functions with no bindings, imports or
derivatives. Nothing loads it yet and no compiler has read it; procmat.wesl is unchanged.
2026-11-29 16:02:31 -08:00
shaneandshinyobjectz e5f4743dee LX7's plan: the clipping check in a crate of its own (raea-sys-clip, systems/clip): raea-sys-contact plus a broad phase would pass 2000 lines (rask check failed scene-faults and render-memory on it), and the clipping check moving off the render's thread is its own job; contact's deepest, Hit and solid cache become its public interface (#274)
Co-authored-by: shinyobjectz <[email protected]>
2026-11-29 16:02:21 -08:00
shaneandshinyobjectz 4aff22e31a raea make motion --seeds N: the best of N takes by the body's faults (#271)
* raea motion: clips capped at 10 s (300 frames), Kimodo's documented limit

Past 10 s a clip drifts and breaks up (Kimodo docs, key_concepts/limitations.md). Measured 11-27: a 12.3 s talk
clip's feet spread 47 -> 69 cm, the shoulders rose 9 cm and the last half second glitched. The error says how to go
longer: 10 s clips chained through --keys holding the last frames of the one before.

* raea motion --seeds N: the best of N takes by the body's faults (foot drift while planted, shoulder rise, hip drop, a hand or forearm into the torso or head), each take's score printed and the kept one's written into the clip; examples/motion runs the verb alone

* Fold score.rs's vector helpers onto glam's Vec3 (the dupes gate: sub and dot matched core/grow's and core/sdf's): a point inside a capsule and a foot's sideways drift, the same arithmetic

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-11-29 15:20:10 -08:00
shaneandshinyobjectz c863adef82 raea motion: clips capped at 10 s (300 frames), Kimodo's documented limit (#270)
Past 10 s a clip drifts and breaks up (Kimodo docs, key_concepts/limitations.md). Measured 11-27: a 12.3 s talk
clip's feet spread 47 -> 69 cm, the shoulders rose 9 cm and the last half second glitched. The error says how to go
longer: 10 s clips chained through --keys holding the last frames of the one before.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-29 13:59:49 -08:00
shaneandshinyobjectz 8627ba7ab4 Paint fixes: canvas drawImage, boxed 3D view culling, grey emoji (#260, #261, #262) (#268)
* Three paint fixes: a canvas draws a loaded Image, a boxed 3D view culls by its box, grey bitmap emoji draw (raea #260, #261, #262)

#260: drawImage of a loaded Image onto a canvas made in a composition drew nothing. The canvas is read back off the
page, where there is no project folder to find staticFile's /media/x in. A loaded Image now carries the file the host
found as currentSrc (sdk/raea frame-globals.ts), which drawImage already prefers, and the canvas host takes a src that
is a file as it stands whatever its roots make of it (systems/canvas media_file).

#261: two causes, neither the plane's turn. Bevy's update_frusta culls by the projection's whole view at the target's
shape, so a camera drawing a page box wider than the frame (an <R3F> in a 1080 x 389 box of a 1080 x 600 frame) had
meshes inside the box's view culled: the shelf's side cards, where the same cards turned the other way reached into
the frame's view and drew. raea-sys-viewbox's sub_view_frusta gives a camera with a sub view that view's frustum,
after Bevy's own and before visibility is checked. And `raea render X.tsx -o x.png` with no --frame took the frames
path, which draws 3D from rows under the whole frame and ignored the box; a 3D piece's bare .png is now drawn as
--frame 0 draws it.

#262: Apple Color Emoji keeps 52 glyphs (💬, 🗨) as grey + alpha PNGs. Vello's glyph run asks png for RGBA with a
transformation that leaves grey as it is, logs "Unsupported `output_color_type`" and skips the glyph. The page's
painter (raea-sys-filters) takes those glyphs out of the run and draws them as images placed as Vello places a
bitmap glyph (emoji.rs); skrifa and png at Vello's versions.

* The export crate stays within its 2000 lines: the still's frame-0 branch in four lines (the size gate failed #268 at 2004)

* The emoji decoder widens a PNG's pixels in one loop: its three one-line closures matched closures elsewhere, and the duplicate gate failed #268 by two exact groups and one near

* A .png with no --frame goes through the stills branch as frame 0: the export crate stays at its 1996 lines (with LX6 and LT1's planned four it is at the 2000 limit, and the tasks gate failed #268)

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-11-29 11:49:23 -08:00
shinyobjectz 456fd1e153 An index job reserves 2 cores and 8 GB
It reserved 4 and 16, and from 11-17 to 11-29 raea-ingest's CPU and memory cost more than its GPU ($7.05 against
$5.97). A 52 s clip measured 1.9 cores busy and 4.9 GB across its processes. A job that takes more is billed for what
it takes. Deployed 11-29 and checked: /healthz on both servers, and the same clip indexed through the deployed job
(10 fragments, 9 posters, 23 s). The search server and the frame API keep their sizes, unmeasured.
2026-11-29 09:55:34 -08:00
shinyobjectz 3afc53d45b A raea render's GPU container reserves 2 cores and 8 GB, and each job says what it used
From 11-17 to 11-29 the farm's CPU and memory came to 65% on top of its GPUs: every GPU container reserved 4 cores
and 16 GiB. A 1080p cut measured 1.3 to 1.4 cores busy and 2.7 GB in its biggest process, so raea's containers now
reserve half (farm_plan.RESERVED); a run that takes more is billed for what it takes, as nothing here sets a limit.
The same cut rendered at the same speed after (262 to 268 ms a frame on a T4) for $0.013 against $0.017. Blender's
containers keep 4 and 16, unmeasured. Each job's last line now says the most cores busy and the biggest process of
its runs, so the next change is made from the jobs' own logs. Deployed 11-29.
2026-11-29 09:34:31 -08:00
shinyobjectz 7d79a24f33 Merge branch 'farm-version' 2026-11-29 09:27:03 -08:00
shaneandshinyobjectz 6af8bfa5bb Cut checks a box can fail on: raea sound check, text placement from the farm's scene read, and full render manifests (#267)
Shane on Dutch (11-29): words faded and cut in two, lines too quiet to hear, effects no one hears, and text laid
over the people and the dog the shot is about.

- raea sound check VIDEO (server/sound.ts): each voice clip's edit points against the take's words and its sound.
  A cut inside a word or on a word's sound is an error, and the message names the pause (or the boundary) to move
  it to. Lines more than 6 dB from the cut's median are an error, with the gainDb that evens them. An effect 10 dB
  or more under the voice is an error, since no one hears it. Buried or fighting music is a warning. offload.ts runs
  it after every render that has a manifest.
- The farm's POST /v1/scene (deploy/modal/farm_scene.py) reads a frame: people as a mask, faces, COCO's things,
  and words in the shot (four small OpenCV zoo models on the CPU, each pinned by its hash).
- server/place.ts turns a scene into costs. raea frames check now fails text over a face, a dog or a person when a
  clear place of its size exists, and names that place. raea frames place FILE lists the clear places in a take.
  Stacked lines move as one block, our own text isn't counted as the shot's words, and passers-by's small faces
  don't count.
- The farm wrote a split render's probe manifest (frame 0 only) as the render's. Each run now writes its own and
  the farm joins them, so the checks see every frame and every clip.

Tests: test/sound.ts (7), test/place.ts (4, on scene reads of three interview frames, boxes only),
test/farm_plan.py (the joined manifest).

Co-authored-by: shinyobjectz <[email protected]>
2026-11-29 09:20:52 -08:00
shinyobjectz 4b2225163e The farm renders with raea's newest release, and says which one it holds
farm.py took RAEA_VERSION or 0.1.6, and no deploy set the variable: on 11-29 the farm's health said 0.1.6 while the
boxes that send it their compositions ran 0.1.12. A container never had the variable either, so health said the
default whatever the image was built with. A deploy now takes the newest full release (GitHub's releases/latest, as
box.sh does) unless RAEA_VERSION pins one, with 0.1.12 when GitHub can't be asked, and the image carries the
version it was built with for its containers. Not deployed: the next modal deploy of raea-farm brings it.
2026-11-29 09:13:24 -08:00
shaneandshinyobjectz 57373a9901 skills: raea-skills main 8efd329 (#138: raea show --playable in cli.md) (#266)
tools/skills.sh check, strict, with a raea built at main 9ce8f53466: every reference and guide copy matches.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-28 14:58:30 -08:00
shaneandshinyobjectz 9ce8f53466 raea show GAME.tsx --playable, and a playable's page shown as itself (PA16) (#265)
--playable exports the game's preview (native.ts: raea playable --networks preview, in a folder of its own) and shows
that page, titled from it; the raea app plays it in a phone, sandboxed (raea-feed #124). raea show takes a
NAME-preview.html as it is too. The help line, the manual and the conformance tests say so.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-28 14:32:03 -08:00
shaneandshinyobjectz 28af820668 PA13, PA14: raea playable, and playables in the public engine (#264)
* PA13, PA14: raea playable, and playables in the public engine

Playables move from the private tree into the public engine (Shane 11-28: "public totally part of the engine"):
sdk/playable (raea/playable for authors, the browser host, check.ts, parity.ts, tony.ts), examples/playables and
docs/playables.feature, with raea/playable and @raea/playable back in sdk/tsconfig.base.json.

`raea playable GAME.tsx -o DIR` (apps/playable) replaces the Bun pipeline (playable.sh, bundle.ts, lint.ts, walk.ts,
alias.ts). It lints the source, renders each composition through `raea run` for its shapes and 3D kinds, bundles the
game and the host once with raea's own bundler, and writes each network's page or ZIP against its 5 MB cap.
engine/bundle gains `minify`, `inline` (inline.rs: pictures, sounds, fonts and .glb as data URLs, .bin as a
Uint8Array) and package-folder aliases (`three/=DIR`). brick-rush writes all nine targets in 7 s (1,384 KB a page);
mobile-ads' tiles and gates export; all play in WebKit, the Google and TikTok packages included.

check.ts lets a network's own page tags through; parity.ts draws in WebKit (chrome.ts is gone), 6.8/255 on
brick-rush frame 300. The craft guide motion/playable.md is `raea guide playable`. bench/live-3d skips brick-rush with
its real reason (PA18).

* tools/layers.toml: raea-app-playable in apps (PA13)

* Fonts travel with a playable, and an end card in a brand's type

An imported .ttf, .otf, .woff or .woff2 (and .jpeg) is its path in a native render (runtime/bundle rewrite.rs,
engine/bundle script.rs) and a data URL in a playable (inline.rs), so an @font-face names the same file either way.
<EndCard> takes font, color and button. Made for the real-brand playables in mobile-ads (ACANA, OLIPOP, HelloFresh),
which carry their brands' own type; the guide and docs/playables.feature say how.

* The preview page tells raea's review its ad events (PA16)

Inside a frame, the preview network posts {raeaPlayable: kind} to its parent on install and end, so the review can show
them beside the game.

* PA16 status: the review plays playables (raea-platform #99), on a host of their own

* The preview page tells the review when it's ready, seen or hidden, and the first touch (PA16)

Beside install and end, the preview build inside a frame posts ready (the game started), viewable and hidden (its page
shown or put away) and touch (the player took over from the game's own hand), so the review and the desktop show them.

* PA16 status: built in cloud (raea-platform #99, #101) and desktop (raea-feed #124), and raea show --playable

* raea playable says what the source can't have even when the game won't render for the lint

A fetch or a URL often stops the walk's render too, and the lint answered with the render's end ("lint.ts ended with
exit 1") and dropped the refusals it had found. Now the source's refusals are the answer, and a render that fails
for another reason is named by its error line.

* PA16 status: play.raea.io is live, checked with the ACANA export

* skills: raea-skills main ae81d0f (#135 notes hook, #136 and #137 the playable guide and raea playable in cli.md)

tools/skills.sh gen with a raea built at this branch and the feed app at main: every reference and guide copy matches it.

* raea-cli: export-game and playable dispatched in a line each, as the verbs around them, so the crate stays at the size gate's 2000 lines

* dupes: the playable's copies folded into what they copied

spec is raea-runtime-bundle's own (now pub), inline.rs's base64 is the base64 crate as raea's other crates use it,
the store and card JSON are json!, and the bundle FFI reads minify and inline as it reads z3 and stamps. tools/dupes.sh:
293 exact, 57 near, as allowed.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-11-28 13:53:48 -08:00
58 changed files with 3352 additions and 342 deletions

No files matched your search

Generated
+15 -3
View File
@@ -13919,6 +13919,7 @@ dependencies = [
name = "raea-app-motion"
version = "0.1.0"
dependencies = [
"glam 0.33.12",
"raea-io-home",
"raea-runtime-bundle",
"raea-sys-kimodo",
@@ -16054,7 +16055,9 @@ dependencies = [
"anyrender",
"anyrender_vello",
"blitz-paint",
"png 0.18.1",
"rustc-hash 2.1.3",
"skrifa 0.44.0",
"vello",
"wgpu",
]
@@ -16357,13 +16360,22 @@ dependencies = [
name = "raea-sys-lightbake"
version = "0.1.0"
dependencies = [
"bytemuck",
"gltf",
"image",
"parry3d",
"pollster 0.4.0",
"raea-gpu-device",
"raea-sys-atlas",
"raea-sys-lighttrace",
"rayon",
"serde_json",
]
[[package]]
name = "raea-sys-lighttrace"
version = "0.1.0"
dependencies = [
"bytemuck",
"pollster 0.4.0",
"raea-gpu-device",
"wgpu",
]
+1
View File
@@ -208,6 +208,7 @@ members = [
"apps/ask",
"apps/lightbake",
"systems/lightbake",
"systems/lighttrace",
"systems/atlas",
"apps/double",
"apps/check",
+22
View File
@@ -0,0 +1,22 @@
Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al. All Rights Reserved.
Copyright (c) 2011-2022 Blender Foundation
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+6
View File
@@ -13,6 +13,12 @@ HyperFrames: https://github.com/heygen-com/hyperframes
font rules. The ported files carry a header saying so: sdk/ui/src/html.ts and sdk/ui/src/html/compile.ts, fonts.ts
and runtime.ts. raea renamed the format's runtime names (window.__raea, data-raea-* attributes, the "html" profile).
Cycles: https://github.com/blender/cycles
Copyright 2009-2010 Sony Pictures Imageworks Inc., et al., and 2011-2022 Blender Foundation. BSD-3-Clause
(LICENSES/cycles-BSD-3-Clause.txt). systems/lighttrace's glossy layers (src/glossy.rs and src/wgsl/glossy.wgsl) are
written from its microfacet, Fresnel and sampling code (src/kernel/closure/bsdf_microfacet.h and bsdf_util.h,
src/kernel/sample/mapping.h), in part adapted from Open Shading Language.
muxide: vendor/muxide, MIT OR Apache-2.0 (its LICENSE-MIT and LICENSE-APACHE).
animato (MIT OR Apache-2.0), usvg and resvg (Apache-2.0 OR MIT), mediabunny (MPL-2.0, used unmodified), manifold-rust
+2
View File
@@ -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"
+12
View File
@@ -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
View File
@@ -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(),
))
}
+111
View File
@@ -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
)
}
}
+149 -10
View File
@@ -22,9 +22,9 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
2. What is baked is the light that bounces: the sky, emissive surfaces and the lights marked baked, through every
bounce, plus the sun's bounce. The sun's direct light stays live (as lightbake.py subtracts it), so anything
that moves still casts its shadow and is lit as before.
3. It runs on systems/rt: the same BLAS and TLAS the traced shadows and raea GI read, through wgpu ray queries
(Metal on Apple silicon's ray hardware, Vulkan, DX12). Every OS raea ships on; never Mac-only. A device without
ray queries is told so, with the reason, and the composition renders unbaked.
3. It runs on wgpu ray queries (Metal on Apple silicon's ray hardware, Vulkan, DX12), over a BLAS and TLAS the bake
builds from the meshes raea draws, not systems/rt's (BK3 says why). Every OS raea ships on; never Mac-only. A
device without ray queries is told so, with the reason, and the composition renders unbaked.
4. Shading is Cycles', from tools/cycles-port (each function held to Cycles' own output), so the bake and the
reference agree by construction, and LT5's path tracer (docs/realism.feature) reuses the same kernel.
5. It lights raea's own meshes (Mesh3d, solids, raea/room) directly, as well as a <Model>'s, with no export.
@@ -32,6 +32,7 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
Background:
Given systems/rt (raea-sys-rt): BLAS per mesh from Bevy's own buffers, a TLAS of visible opaque instances,
glass left out so sky and sun reach through windows; its traced AO, raea GI's world probes and cache (LT2, LT3)
And raea-sys-lighttrace, the kernel of BK3, split from the bake so systems/rt and LT5's path tracer can build on it
And tools/cycles-port/cycles_bsdf.wgsl: GGX/Beckmann D, G2, Fresnel, F82 conductors, VNDF sampling, passing against
Cycles on an M5 Pro; diffuse and energy-conserving Oren-Nayar next
And <Lightmap> (sdk/render/src/bevy3d/lightmap.tsx, systems/material lightmap.rs): Bevy's lightmap on a <Model>'s
@@ -147,7 +148,8 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
And built 11-23: `raea_sys_lightbake::texels::texels(glb, request)` lays the model out (BK1's layout, raea_sys_atlas::laid; the
light-only request is `request(texels, max_side)`, a worn model passes its wear bake's), takes
the model's world triangles as the parry3d BVH the atlas was laid out over, moves each point
off its surface by 1e-5 of the model's size or farthest coordinate (at least 10 microns), and casts 16
off its surface by 1e-6 of the model's size or farthest coordinate (at least a micron; 1e-5 and 10 until BK3 found
what it costs), and casts 16
cosine-weighted rays from each: a texel is inside when at least half its rays meet a back face and more meet
back faces than front ones (a floor that is one plane is met from below one way and not at all the other).
CPU and rayon for now, as weathering's own rays; BK3's GPU pass may take the test over
@@ -178,10 +180,15 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
Scenario: BK3. The light that bounces, traced on raea's ray tracer
Given the plan
| crate | file | lines | job |
| raea-sys-lightbake | systems/lightbake/src/trace/tests.rs | 160 | a white furnace, a wall's form factor, a glowing box, a red wall's bleed, the same bytes twice; the measured run |
| raea-sys-lightbake | systems/lightbake/src/wgsl/diffuse.wgsl | 60 | the diffuse BSDF and the paths' random numbers, a module systems/rt and LT5's path tracer can include as it is |
| raea-sys-lightbake | systems/lightbake/src/trace.rs | 260 | the passes: dispatch per atlas, samples accumulated over passes, progress, cancel |
| raea-sys-lightbake | systems/lightbake/src/wgsl/trace.wgsl | 320 | per texel: cosine-weighted paths against the bake's own TLAS; the sky from the composition's <Environment>, emissives, baked lights; Russian roulette; Cycles' BSDFs from cycles-port at each bounce |
| raea-sys-lightbake | systems/lightbake/src/trace_tests.rs | 240 | a white furnace, a wall's form factor, a glowing box, a red wall's bleed, the sun at a texel and at a hit, a panorama's direction, a ray straight up, a textured floor, the same bytes twice; the measured run |
| raea-sys-lightbake | systems/lightbake/src/own.rs | 185 | a model read on its own second UVs (a map a mesh, as lightbake.py lays them): its world triangles, base colour and textures, and each map's texels |
| raea-sys-lightbake | systems/lightbake/src/own/tests.rs | 150 | its texels on a known quad; the ignored run against a Cycles bake of the same .glb |
| raea-sys-lighttrace | systems/lighttrace/src/wgsl/diffuse.wgsl | 40 | the diffuse BSDF and the paths' random numbers, a module systems/rt and LT5's path tracer can include as it is |
| raea-sys-lighttrace | systems/lighttrace/src/glossy.rs | 130 | GGX on the CPU (Cycles'), and the table of a rough lobe's albedo the kernel reads |
| raea-sys-lighttrace | systems/lighttrace/src/wgsl/glossy.wgsl | 130 | a metal's and a dielectric's layers over Lambert: weights, evaluation, sampling |
| raea-sys-lighttrace | systems/lighttrace/src/tests.rs | 130 | white surfaces keep all their light; the sun and a panel off a floor against a CPU sum |
| raea-sys-lighttrace | systems/lighttrace/src/lib.rs | 265 | the passes: dispatch per atlas, samples accumulated over passes, progress, cancel |
| raea-sys-lighttrace | systems/lighttrace/src/wgsl/trace.wgsl | 250 | per texel: cosine-weighted paths against the bake's own TLAS; the sky from the composition's <Environment>, emissives, baked lights; Russian roulette; Cycles' BSDFs from cycles-port at each bounce |
Then each texel integrates the incoming diffuse light over its hemisphere along paths of up to `bounces`
(default 4) through a BLAS and TLAS the bake builds itself from the meshes raea draws, by the wgpu ray queries
systems/rt uses. (Not rt's own: a bake runs offline, before any frame, with no Bevy render world to hold them,
@@ -192,6 +199,126 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
the cause maps (sdk/wear), so a grimy brick wall bounces grimy brick. The kernel evaluates them from one WGSL
module shared with the raster, not a copy (Shane, 11-23); Blender's export drops these materials, so this is
a bake Cycles' round trip can't make
And what a module must take as arguments to be shared, read from the three sources 11-23 (nothing built): a
compute kernel has no screen derivatives, no implicit-level texture reads and no eye
| what the raster uses | where | what the kernel gives |
| fwidth of the normal over the position's (edges) | procmat.wesl, worn.ts | the turn of the triangle's vertex normals over its edges |
| fwidth of the plane, fading fine threads | procmat.wesl (fabric, brushed) | the hit's texel size |
| a pixel's size (cracks no thinner than one) | sdk/wear index.ts, wear_geo's px | the hit's texel size |
| textureSample of the four cause maps | sdk/wear causes.ts | textureSampleLevel, level 0 |
| the eye, for the parallax behind lost render | sdk/wear causes.ts, wear_geo | the normal (no parallax: a bounce has no one eye) |
| metallic, which the marks also change | worn.ts; iron, zinc, copper, brass | the bounce is base colour x (1 - metallic) |
| u_NAME(), tex_NAME, samp_NAME, from the hook | systems/shader's module() | the same names over the kernel's own bindings |
And systems/procmat's module is written as systems/procmat/src/drawn.wesl, not compiled or used yet; procmat.wesl
takes it, its own copy deleted, in the commit that builds it, with a frame before and after held to the same
bytes (fabric and brushed to one step of 8 bits: their scale moves outside the derivative). WearExtension and raea/wear are text made in TypeScript (worn.ts, sdk/wear), so the kernel gets theirs
from the composition's material, not from a file
And the atelier's static set is traced and held to the Cycles bake its own agent made of it (lightbake.py; the
eighth bake read 11-23: 202 meshes of one primitive, 699 902 triangles, 198 maps of 128-1024 a side), as soon as
the trace can: each mesh's map against Cycles' by map_stops, with its time and memory. Its light is a panorama (strength
0.366, rotation 2.449 in the blend its bake used), one sun and no lamps
And measured 11-23 on the M5 Pro, in progress: own.rs reads the .glb on its own second UVs, the .glb's positions
and second UVs being equal in every bake compared. Cycles 512 samples, 56 texels a metre, smooth 2; the trace
1024 samples, 4 bounces, with no fitted gain; 2 358 922 texels of 198 meshes, the same in every row. "biased" is
meshes whose mean signed error is over 1/3 stop; light is total over total. Rows 1-4 and 6 bake the scene with
every material plain diffuse (base colour x (1 - metallic)), unclamped, in a scratch copy, so the trace and
Cycles differ only in the tracing
| compared | mean stops | bias | light | over 1/3 | biased |
| noise: Cycles / Cycles, another seed | 0.161 | -0.001 | 1.000 | 54 | 2 |
| Cycles' clamp 3 / no clamp | 0.017 | -0.017 | 0.963 | 5 | 5 |
| materials: Cycles diffuse-only / real, no clamp | 0.284 | -0.272 | 0.863 | 132 | 128 |
| trace / Cycles, diffuse-only, no clamp | 0.218 | -0.064 | 0.994 | 94 | 46 |
| trace / Cycles, real materials, no clamp | 0.389 | -0.336 | 0.857 | 157 | 140 |
| trace / the atelier's own bake (clamp 3) | 0.384 | -0.319 | 0.889 | 155 | 135 |
And what they say: on matched materials the trace's total light is within 0.6% of Cycles' and the floor, deck,
walls and door are within 0.02 stops at the median. 14% of the light is the metals' and speculars' bounces, so
GGX and F82 were needed (built, below). The 46 "biased" meshes are not an
error of the trace's, except 5 of them (4 the footprint's, bench_strips the offset's): that count is by mean log error on smoothed maps and it drops texels
where one side is 0. By each mesh's total light, zeros counted and no smoothing, 8 of 198 are over 1/3 stop (Cycles
against itself, smoothed: 1, and 95% of meshes within 0.05). Time: the trace 17-25 s, 10 s at 256 samples and
119 s at 4096, peak 1.2 GB, setup 70-200 s in a debug build; Cycles' diffuse-only bake 5m33s, 2.7 GB, the
atelier's own 5m36s, 3.4 GB for its whole script
And the 8, by the trace's light over Cycles': 4 are the footprint. The trace starts every ray at the texel's
centre, and Cycles jitters its samples over the texel; on 30 mm texels a sheet's 6 mm ledge is all or nothing.
Traced 8x8 points a texel and averaged, over the same texels: bench_stock 0.333 -> 0.960, bench_mat 1.333 ->
1.006, dt_ledge 1.291 -> 0.997, dt_rule 0.765 -> 1.068; bench_strips only 0.616 -> 0.679 (the offset, below). Built after it:
a texel starts from the open ones of 16 points over its footprint (on its triangle, clear of its edges, not
inside other geometry, as BK2's rays judge them), so a partly buried texel is lit by what can be seen of it. A texel
under a sheet's edge, three quarters of it covered, reads 0.2495 for 0.249 where its centre alone reads 0; one
three quarters inside a block reads 0.52 from its open quarter
And 3 are the reference's (mug_coffee, books_5 and tower_base): Cycles' adaptive sampling (on by default, threshold 0.01; lightbake.py doesn't turn
it off) stops a dark pocket's pixel before it has seen the light, so a cup or a shelf's back bakes too dark. With
it off (1024 samples, the same meshes, raw floats): mug_coffee 1.94 -> 1.012, books_5 1.279 -> 1.021, meet_tea
1.216 -> 1.030, tower_base 1.183 -> 1.040, books_0 1.199 -> 1.072. Neither the sun's subtraction nor the PNGs'
16-bit clipping (0.92-1.05 of the raw floats) nor the sheets' gaps (a fixture of sheets 0.05-5 mm apart: both
black at 0.2 mm) explain it. BK0's own references were baked the same way
And against the honest reference, measured 11-23 with jittered starts, a release build: Cycles' diffuse-only atelier
with adaptive sampling off, unsmoothed, unclamped, 512 samples, raw floats (12m49s against 3m55s with it on, the
same scene), by each mesh's total light, zeros counted; the trace 1024 samples, 4 bounces. (Cycles' own second
seed, smoothed, is over 1/3 stop on 1 of 198.) The atelier's own bakes were made with adaptive sampling on
| a texel's samples start from | over 1/3 stop | over 1/10 | total light |
| the open part of it (what the bake does) | 3 of 198 | 21 | 0.997 |
| all of it, buried points too (as Cycles averages) | 1 of 198 | 10 | 0.993 |
| the open part, at the offset below | 1 of 198 | 15 | 1.000 |
| all of it, at the offset below | 0 of 198 | 5 | 0.995 |
They differ where a texel is partly buried: Cycles' average counts the dark inside, so it bakes such a texel darker
than what can be seen of it; the bake keeps the open part. Left, over the whole footprint: bench_stock 1.188,
site_base, site_contours, house_base and house_roof about 1.10, bench_strips 1.068; not explained
And the offset was bench_strips: rays started 1e-5 of the model's size off a surface, 0.15 mm in the atelier, whose
strips are stacked 0.2 mm apart, so a ray had 0.05 mm of each gap and the sun's first half millimetre in it was
lost. By offset (bench_strips, lamp_shade_in, dt_tape; whole footprint, over Cycles'): 0.15 mm 0.558, 1.376,
0.865; 50 microns 0.638, 1.117, 0.954; 20 1.007, 1.049, 0.980; 10 1.063, 1.022, 0.989; 2 1.059, 1.002, 0.997. It is
1e-6 now. No ray off a tilted plane meets it, from the texel or from a bounce, down to 3e-7 of its distance from
the origin (1 m to 5 km); the first do at 1e-7, on Metal. Vulkan and DX12 haven't run it. A fixed 0.1 mm under a
40 km floor does meet it (0.8% of the light lost)
And the times: setup in release, the atelier's own .glb 12.8 s to read and lay out, 2 992 000 texels on
its own UVs, and 16.7 s to trace 1024 samples, peak 1.5 GB. On the atlas bake of BK2 (64 texels a metre): the table
set 0.85 s with its texels, 0.84 s to trace 512 samples (1.5 M texels), and the atelier 19.9 s and 8.5 s (4.3 M texels).
Other sessions were rendering. The bar is 60 s on the table set, all in: not yet timed with reading,
cleaning (BK4) and writing in it. The 16-ray probe on the CPU is fast enough there, and 20 of the atelier's 28 s
And each bounce goes on by the surface's glossy layers over Lambert, as Cycles' Principled does: a metal (GGX, F82
with a white tint) and a dielectric of IOR 1.5 at Specular 0.5, what a rough lobe loses given back from a table
glossy.rs makes. GGX, its sampling and the Fresnels are Cycles' formulas (bsdf_microfacet.h, bsdf_util.h,
mapping.h at 6ea3d9bcd81a: BSD-3-Clause, in NOTICE, not Apache-2.0), written in systems/lighttrace until
tools/cycles-port is on main and then swapped for its functions; three cases of its oracle are copied into the
tests (D, G, lambda, the visible-normal sample). Filter glossy is Cycles' default 1: after a texel's diffuse turn a
lobe's alpha is at least 0.41. Held to a CPU sum: the sun off five surfaces within 0.03%, a panel found by the
paths' own turns within 0.6%, white surfaces keep 0.997-0.9998 of their light
And against Cycles' real materials, adaptive sampling off (unclamped, unsmoothed, 512 samples, 15m02s, peak 2.7 GB;
all 202 materials MULTI_GGX, IOR 1.5, Specular 0.5), the trace 1024 samples, 4 bounces, by each mesh's total light
| the trace | over 1/3 stop | over 1/10 | total light | time |
| Lambert only, the whole of a texel | 108 of 198 | 190 | 0.858 | 20.3 s |
| glossy layers, the whole of a texel | 0 of 198 | 5 | 0.997 | 22.1 s |
| glossy layers, its open part (what the bake does) | 1 of 198 | 16 | 1.002 | 18.1 s |
Off most over the whole: bench_stock 1.166 and the dim house, site and roof models 1.08-1.10, not explained; over
the open part: meet_sheet_0 1.325. (Other sessions' renders ran beside these.)
And where the energy table is read is ours: at the blurred alpha, so a blurred lobe keeps its light; Cycles reads it at
the material's own alpha, before the blur. Measured, the trace's light over Cycles' for ours, then Cycles' way:
all meshes 0.9972, 0.9952; the 36 with any metal 1.0021, 1.0002; the 17 of metallic 0.5 and over 0.9997, 0.9974.
Cycles' way is darker by at most 3.4% on one mesh (mug_coffee); the mean error a mesh is 0.0177 and 0.0175 stops
And trace() refuses a texel without the samples asked for, or light that isn't finite
And a picture a material reads that isn't there is refused by lightbake.py and look.py before they write (Cycles draws
it magenta and bounces it: a first reference made from a copy without its textures was 6 times too bright and is
discarded). They also have --no-adaptive, not the default. Both files are another lane's, not on main
And the trace's own indirect clamp is gone: at 3 it kept 0.869 of Cycles' light at the same clamp where unclamped
it keeps 0.994 (Cycles' own clamp keeps 0.963), so it was not Cycles' clamp. A bake is unclamped
And a ray straight up gave a non-finite value on Metal (a panorama's longitude, atan2(0, 0)), one texel of the
atelier at 1024 samples; a test casts 134 million of them
And that comparison is read knowing what the reference is: Cycles' own materials as the .glb has them, not raea's
drawn ones (the export drops uv_transform, _arm maps and tints; 39 materials are metal, which Cycles reflects
and Lambert here doesn't); clamped at 3, smoothed twice, its maps' light only where Cycles has some. Cycles'
map times its scale is the mean incoming light, as the trace's is, so the two are compared with no fitted gain
And a <ShaderExtension> a user wrote can't run in the kernel in general (its hook reads Bevy's PbrInput, the view
and its own textures): it bounces its base colour, and `raea bake light` names each material it did that for
And raea/wear's caused wear (touch, edges, cavity, run-off's stains and deposits, sun fade, soot, crumbling, age and
neglect) comes from the baked cause maps and the scene's settings, the same every frame, and bounces as any other
albedo does. Only its per-frame layer over that (wx: wet, snow, storm, ice; season: damp, dust, leaves, melt) is
not the surface's own, and the bake bounces it at the values the composition gives; with no weather given it
bakes dry (decided 11-23; BK5's key)
# Considered and not taken 11-23: drawing each material into the atlas in texture space, which would give a user's
# shader too but needs a Bevy render in the bake.
And the bounce matches the frame: the season's values are those wearShader draws, so "dry" is wx all 0 with the
season as drawn (with no weather given that is day 172, whose dust is 0.595, kept in the bake; decided 11-23)
And the sky is the composition's <Environment> panorama at its intensity and rotation; emissive surfaces light
the set; the sun's direct light is left out at the first hit and kept at every later bounce (so a sunlit floor
lights the ceiling), and a light marked `bake` is carried whole
@@ -207,8 +334,10 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
reads 2.004 for 2; breaking the cosine, the offset, the roulette, its weight, the emission or their order each
fails one of them. Only Metal has run it. At 512 samples and 4 bounces, every surface 0.7 grey under a white
sky, the trace alone takes 0.8 s on the table set, 0.3 s on the Cornell box and 0.9 s on the window room
(M5 Pro; linear in samples, 5.6 s at 4096). Not built: the <Environment> panorama, baked lights, the sun left
out at the first hit, textures, and the albedo raea draws under procmat, wear and sdk/wear
(M5 Pro; linear in samples, 5.6 s at 4096). Built since: the panorama
with its strength and rotation, the sun at later hits by shadow rays and out at the first, base colour textures.
Not built: baked lights, and the albedo raea draws under procmat, wear and sdk/wear; a metallic-roughness texture
(a material's factors only) and smooth normals at a hit (the triangle's own)
@needs:BK3
Scenario: BK4. A clean map: denoised, dilated, no seams
@@ -234,8 +363,18 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
| @raea/render | sdk/render/src/bevy3d/lightbake.tsx | 120 | <LightBake samples bounces texels> around the static parts it bakes; re-exported from raea/3d |
Then `<LightBake>` around a composition's static parts bakes them on the first frame a render, a play or a
`render --at` needs it, and every later frame and run reads the kept bake
And the BLAS come from the composition's own mesh data (Mesh3d, solids and room parts with their transforms, a
<Model>'s meshes), never from a re-export
And it lights raea's own Mesh3d, solids and raea/room parts in place, as well as a <Model>'s meshes, so the
parts stay parts: `raea scene lint`, `raea render --review` and `raea make` see each one, not one baked model
And the key holds each worn material's wear settings (age: years, soot, upkeep), its cause maps and its weather
and season values (wx, season), so each combination bakes once, when it's first used, and is kept; with no
weather given it bakes dry (wx 0, the season as wearShader draws it)
And a weather or season animated over the shot bakes once, at its values on the composition's first frame with the
<LightBake> in it, whichever frame is rendered first (so `render --at` and a full render read one bake and a
frame has one look); it isn't refused and isn't baked each frame, and the bake's report and `raea bake light`
name the values used and say the weather moves over the shot (decided 11-23)
# Not built, a later scenario: two bakes, at the start and the end of a weather change, mixed by its uniform.
And a change to a static part, a material, the sky or a setting changes the key and bakes again; a change to
anything outside <LightBake> (the camera, a moving part, the sun's direct light) doesn't
And `raea bake light EDIT.tsx` bakes ahead of a render and says what it baked (meshes, texels, samples, time)
+2 -2
View File
@@ -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)
+13 -2
View File
@@ -12,7 +12,7 @@ Body motion made on this machine by Kimodo (NVIDIA), on MLX on a Mac and on PyTo
## Usage
```sh
raea motion "LINE" [--keys KEYS.json] [--seconds 5 | --frames N] [--seed 1] [--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.
+1 -1
View File
@@ -51,7 +51,7 @@ raea show out/cut-v2.mp4 --replaces i-show-2f9c --done c-3 --done c-4 --note "Wa
## Usage
```sh
raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--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.
+34
View File
@@ -148,3 +148,37 @@ describe("raea show --fyi and --group", () => {
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"]);
});
});
+1 -1
View File
@@ -134,7 +134,7 @@ pub fn run(args: &[String]) -> R<String> {
IN_HELP.set(was);
// `raea library` (engine/cli/src/library.ts) and `raea show` (show.ts: in the raea app, not Preview, Shane 11-09), under render's usage
let usage = format!("{usage}\n raea library [new NAME [--cloud] | add LIBRARY PATH | files LIBRARY | tag SHA TAGS | status | scan ...] | raea library search \"WORDS\" [--library LIBRARY] [--kind KIND] [--limit N] [--sound] (the person's libraries in the raea app: folders and drives indexed on this machine, searched by meaning; a folder an agent adds waits for the person's yes)");
let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--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):
+14
View File
@@ -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}` };
}
+11 -3
View File
@@ -23,7 +23,9 @@ 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.
@@ -57,7 +59,7 @@ raea show FILE... --replaces ITEM --done ID...
`;
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"]);
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. */
@@ -155,7 +157,7 @@ export function parseShow(args: string[], cwd: string) {
if (labels.length && args.includes("--labels")) throw new Error(`--label or --labels, not both\n${SHOW_USAGE}`);
if (questions && files.length) throw new Error(`with several questions or previews, each file is a --preview of the question or choice it shows\n${SHOW_USAGE}`);
if (args.includes("--fyi") && (asked.length || marking(args))) throw new Error(`--fyi shows files only to be looked at: a question, or marking comments, is answered\n${SHOW_USAGE}`);
return { groups, fyi: args.includes("--fyi"), labels, labelsFile: one("--labels"), files, despite, choices, questions, open: args.includes("--open"), title: one("--title"), ask: one("--ask"), asks: many("--ask"), project: one("--project"), replaces: one("--replaces"), question: questions ? undefined : one("--question"), as: one("--as"), role: one("--role"), inbox: one("--inbox"), on: one("--on"), working: many("--working"), done: many("--done"), note: one("--note"), sub: one("--sub"), status: one("--status"), states: one("--states")?.split(",").map((s) => s.trim()).filter(Boolean), sign: one("--sign"), clip: one("--clip"), render: one("--render") };
return { 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). */
@@ -210,6 +212,12 @@ export function showVerb(ask: Ask, args: string[], cwd: string, env: Record<stri
if (a.done.length && !a.replaces) throw new Error(`--done with files settles comments on the item they replace: add --replaces ITEM\n${SHOW_USAGE}`);
if (a.labelsFile !== undefined && !listed) throw new Error(`--labels ${a.labelsFile}: its labels weren't read (raea's own handler reads the file)`);
const labels = a.labels.length ? a.labels : listed;
// --playable: the game's preview exported (raea playable --networks preview) and that page shown (docs/playables.feature PA16)
if (a.playable) {
if (a.files.length !== 1 || !/\.tsx$/.test(a.files[0]) || a.question || a.questions) throw new Error(`--playable shows one game's .tsx as its playable: raea show GAME.tsx --playable\n${SHOW_USAGE}`);
a.files = [(ask("playable", { file: a.files[0], cwd }) as { page: string }).page];
a.title ??= a.files[0].replace(/^.*[\\/]/, "").replace(/-preview\.html$/, "").replace(/[-_]+/g, " ").replace(/^\w/, (c) => c.toUpperCase());
}
const r = ask("show", { ...(labels?.length ? { labels } : {}), ...(a.fyi ? { intent: "fyi" } : {}), ...(a.groups.length ? { groups: a.groups } : {}), files: a.files, despite: a.despite, title: a.title, ask: askWith(a.ask, a.despite), question: a.question, choices: a.choices, questions: a.questions, open: a.open, project: a.project, replaces: a.replaces, cwd, by }) as
| { opened: string[] }
| { kind: "item" | "composition"; id: string; type: string; title: string; project: string; workspace: string; inbox: string; brought?: boolean };
+2
View File
@@ -225,6 +225,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)
+1 -1
View File
@@ -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")]
+10 -10
View File
@@ -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
+111 -10
View File
@@ -29,6 +29,7 @@ import contextlib
import json
import os
import re
import resource
import shutil
import subprocess
import time
@@ -38,7 +39,36 @@ import modal
HERE = os.path.dirname(os.path.abspath(__file__))
CLOUD = os.path.dirname(os.path.dirname(HERE))
RAEA = os.environ.get("RAEA_VERSION", "0.1.6")
def raea_version(env=os.environ, local=None, latest=None):
"""The raea the farm renders with: RAEA_VERSION when it's set (a deploy that pins one, and every container, whose
image carries the version it was built with), else, at a deploy, raea's newest release, as the boxes take
(deploy/sprites/box.sh). Until 11-29 this was "0.1.6" unless a deploy remembered the variable, and none did: the
farm drew 0.1.12 boxes' compositions with a raea six releases old, and a container, which never had the variable,
said 0.1.6 in /v1/health whatever its image held."""
if env.get("RAEA_VERSION"):
return env["RAEA_VERSION"]
if modal.is_local() if local is None else local:
try:
v = (latest or _latest_release)()
if re.fullmatch(r"\d+\.\d+\.\d+", v or ""):
return v
except Exception: # no network at a deploy: the fallback below, and the deploy's own log says which
pass
return RAEA_FALLBACK
def _latest_release():
import urllib.request
# releases/latest answers with a redirect to the newest full release's tag (never a pre-release)
with urllib.request.urlopen("https://github.com/shinyobjectz/raea/releases/latest", timeout=20) as r:
return r.geturl().rstrip("/").rsplit("/v", 1)[-1]
RAEA_FALLBACK = "0.1.12"
RAEA = raea_version()
BLENDER = os.environ.get("RAEA_FARM_BLENDER", "5.3.0")
# The GPUs each kind of job takes, the first Modal has free (bench/gpus.py, 11-17): raea's frames are bound by its CPU
# (React on QuickJS), so a T4 or an A10 draws them for the least a frame; Cycles gets the most samples a dollar on an
@@ -65,6 +95,8 @@ image = (
f"set -e; v={BLENDER}; curl -fsSL https://download.blender.org/release/Blender${{v%.*}}/blender-$v-linux-x64.tar.xz "
"| tar -xJ -C /opt && ln -s /opt/blender-$v-linux-x64/blender /usr/local/bin/blender && blender -b --version | head -1",
)
# what this image holds, for the containers: /v1/health says it, and the module agrees with the deploy that built it
.env({"RAEA_VERSION": RAEA})
.pip_install("fastapi[standard]==0.121.2")
# /v1/faces: OpenCV's YuNet face detector (232 KB, CPU), for the boxes' frames check (server/frames.ts): a box has
# no vision backend of its own (raea-perceive isn't in raea's Linux build), so a face cut by a 9:16 crop went unseen
@@ -74,6 +106,17 @@ image = (
"face_detection_yunet/face_detection_yunet_2023mar.onnx "
"&& echo '8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4 /opt/yunet.onnx' | sha256sum -c"
)
# /v1/scene (11-29): what's in a frame, for the boxes' text placement (farm_scene.py, server/place.ts): people as a
# mask, COCO's things, words in the shot, beside YuNet's faces. Three more of OpenCV's zoo, Apache-2.0, on the CPU
.run_commands(
"set -e; z=https://media.githubusercontent.com/media/opencv/opencv_zoo/main/models; "
"curl -fsSL -o /opt/pphumanseg.onnx $z/human_segmentation_pphumanseg/human_segmentation_pphumanseg_2023mar.onnx; "
"curl -fsSL -o /opt/yolox_s.onnx $z/object_detection_yolox/object_detection_yolox_2022nov.onnx; "
"curl -fsSL -o /opt/ppocr_det.onnx $z/text_detection_ppocr/text_detection_en_ppocrv3_2023may.onnx; "
"printf '%s %s\\n' 552d8a984054e59b5d773d24b9b12022b22046ceb2bbc4c9aaeaceb36a9ddf24 /opt/pphumanseg.onnx "
"c5c2d13e59ae883e6af3b45daea64af4833a4951c92d116ec270d9ddbe998063 /opt/yolox_s.onnx "
"03f550c6b406fda8bf54bd8327815f6c7e2edd98cea02348c93d879254366587 /opt/ppocr_det.onnx | sha256sum -c"
)
.add_local_file(os.path.join(CLOUD, "image", "nvidia_icd.json"), "/usr/share/vulkan/icd.d/nvidia_icd.json", copy=True)
.env({"WGPU_BACKEND": "vulkan", "NVIDIA_DRIVER_CAPABILITIES": "all", "RAEA_CLIP_CHECK": "0", "RAEA_AUDIO_MUTE": "1",
"RAEA_MODELS": "/models/raea", "RAEA_FEED_MODELS": "/models/feed", "RAEA_LIBRARY_MODELS": "/models/library",
@@ -83,7 +126,7 @@ image = (
"RAEA_TOKENSYNTH": "/models/tokensynth", "RAEA_TOKENSYNTH_DEVICE": "cuda", "RAEA_AUDIO_AUTOSETUP": "0",
# Stable Audio Open small on ONNX Runtime with CUDA, as deploy/modal/sao.py installs it (CR25)
"RAEA_SAO": "/models/sao"})
.add_local_python_source("farm_plan", "farm_media", "prices")
.add_local_python_source("farm_plan", "farm_media", "prices", "farm_scene")
)
app = modal.App(os.environ.get("RAEA_FARM_APP", "raea-farm"), image=image)
@@ -104,20 +147,32 @@ CACHES = {"__GL_SHADER_DISK_CACHE": "1", "__GL_SHADER_DISK_CACHE_PATH": f"{ROOT}
"__GL_SHADER_DISK_CACHE_SIZE": str(4 << 30), "XDG_CACHE_HOME": f"{ROOT}/cache/xdg"}
# the scene reader's models, loaded once a container (/v1/scene)
SCENE = None
# when this container's Python started, for the job's bill (farm_plan.Bill)
BOOTED = time.time()
# what this container's last run used: cores busy on average (its processes' CPU time over the run's time) and the
# biggest of them at its peak, for the job's last line (farm_plan.Bill), so what a GPU container reserves
# (farm_plan.RESERVED) is held against what renders take (11-29: CPU and memory were 65% on top of the farm's GPU bill)
USED = {}
def life():
return {"task": os.environ.get("MODAL_TASK_ID", ""), "boot": BOOTED, "end": time.time()}
return {"task": os.environ.get("MODAL_TASK_ID", ""), "boot": BOOTED, "end": time.time(), **USED}
def run(cmd, cwd=None, env=None, timeout=6 * 3600):
t = time.time()
for d in (CACHES["__GL_SHADER_DISK_CACHE_PATH"], CACHES["XDG_CACHE_HOME"]):
os.makedirs(d, exist_ok=True)
u0 = resource.getrusage(resource.RUSAGE_CHILDREN)
r = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, env={**os.environ, "HOME": "/tmp/home", **CACHES, **(env or {})}, timeout=timeout)
return r.returncode, r.stdout + r.stderr, time.time() - t
u1, s = resource.getrusage(resource.RUSAGE_CHILDREN), time.time() - t
USED.update(cores=round((u1.ru_utime + u1.ru_stime - u0.ru_utime - u0.ru_stime) / max(s, 0.001), 2), peak_mb=round(u1.ru_maxrss / 1024))
return r.returncode, r.stdout + r.stderr, s
def snapshot(d):
@@ -152,8 +207,15 @@ class Log:
SCALEDOWN = 2
def on(gpus):
return dict(gpu=gpus, cpu=4, memory=16384, volumes={ROOT: vol, "/models": models}, timeout=6 * 3600, max_containers=GPUS, scaledown_window=SCALEDOWN)
def on(gpus, job):
import sys
if HERE not in sys.path: # at a deploy this file is loaded by path; in a container the image carries the module
sys.path.insert(0, HERE)
import farm_plan
cpu, gib = farm_plan.RESERVED[job]
return dict(gpu=gpus, cpu=cpu, memory=gib * 1024, volumes={ROOT: vol, "/models": models}, timeout=6 * 3600, max_containers=GPUS, scaledown_window=SCALEDOWN)
def kind():
@@ -164,7 +226,7 @@ def kind():
return prices.kind_of(name)
@app.function(**on(RAEA_GPUS))
@app.function(**on(RAEA_GPUS, "raea"))
def raea_run(id: str, args: list[str], frames: list[int] | None = None, first: int = 0, probe: bool = False, video: bool = False) -> dict:
"""raea ARGS in the job's folder. With `frames`: those frames to the job's frames/ folder, from frame `first` on,
as one H.264 run (frames/run-FIRST.mp4, joined by the coordinator without encoding again) when `video`, else PNGs.
@@ -185,12 +247,19 @@ def raea_run(id: str, args: list[str], frames: list[int] | None = None, first: i
os.makedirs(dest, exist_ok=True)
if video:
seg = f"/tmp/run-{first:05d}.mp4"
code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", seg], cwd=work)
# the run's own manifest (its frames, each sound cut to them): the coordinator joins the runs' into the render's
# (farm_plan.joined), so a cut's whole edit comes back, not frame 0's alone (11-29, Dutch)
man = f"/tmp/run-{first:05d}.json"
code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", seg, "--manifest", man], cwd=work)
if os.path.exists(seg):
shutil.move(seg, f"{dest}/run-{first:05d}.mp4")
vol.commit()
ms = re.search(r"([\d.]+) ms a frame", out)
return {"code": code, "out": out[-2000:], "s": s, "frames": len(frames), "ms": float(ms.group(1)) if ms else None, "kind": kind(), **life()}
try:
m = json.load(open(man))
except Exception:
m = None
return {"code": code, "out": out[-2000:], "s": s, "frames": len(frames), "ms": float(ms.group(1)) if ms else None, "kind": kind(), "manifest": m, **life()}
tmp = f"/tmp/{uuid.uuid4().hex}"
code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", tmp], cwd=work)
# raea names --at's stills in order (frame-00000.png is the first frame asked for), beside its manifest
@@ -224,7 +293,7 @@ print("RAEA_INFO " + json.dumps({"start": s.frame_start, "end": s.frame_end, "fp
"""
@app.function(**on(BLENDER_GPUS))
@app.function(**on(BLENDER_GPUS, "blender"))
def blender_run(id: str, blend: str, start: int, end: int, opts: dict) -> dict:
vol.reload()
work = f"{JOBS}/{id}/work"
@@ -431,6 +500,38 @@ def api():
"seams": seams(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY).astype(np.int16))})
return {"model": "yunet-2023mar", "frames": out}
@web.post("/v1/scene")
async def scene(req: Request):
"""what's in a video's frames, for the boxes' frames check and `raea frames place` (farm_scene.py): the body is
{"frames": [base64 JPEG, ...]} (at most 400), the answer each frame's size, its faces and split-screen seams
(as /v1/faces gives them, each face [x, y, w, h, "face", score]), a grid of where people are, and its things
(COCO's, and words in the shot as "text") as [x, y, w, h, label, score], in that frame's pixels"""
import base64
import cv2
import numpy as np
import farm_scene
check(req)
body = await req.json()
frames = body.get("frames") if isinstance(body, dict) else None
if not isinstance(frames, list) or not frames:
raise HTTPException(400, 'the body is {"frames": [base64 JPEG, ...]}')
if len(frames) > 400:
raise HTTPException(413, "at most 400 frames a call")
global SCENE
if SCENE is None:
SCENE = farm_scene.Scene()
out = []
for b64 in frames:
im = cv2.imdecode(np.frombuffer(base64.b64decode(b64), np.uint8), cv2.IMREAD_COLOR)
if im is None:
out.append(None)
continue
r = SCENE.read(im)
r["seams"] = seams(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY).astype(np.int16))
out.append(r)
return {"model": "pphumanseg-2023mar+yolox-s-2022nov+ppocrv3-db-2023may+yunet-2023mar", "frames": out}
@web.post("/v1/words")
async def words(req: Request):
import base64
+67 -11
View File
@@ -87,7 +87,13 @@ def runs(first, last, k, warm=0):
return out
def price(kind, seconds, cpu=4, memory_gib=16):
# What a GPU container reserves beside its GPU, billed whether used or not; a run that takes more is billed for what
# it takes (Modal has no limit set here), so these are floors, not caps. raea's were 4 cores and 16 GiB until 11-29,
# when a 1080p cut measured 1.4 cores busy and 2.7 GB (the job's last line says each job's); Blender's is unmeasured.
RESERVED = {"raea": (2, 8), "blender": (4, 16)}
def price(kind, seconds, cpu=RESERVED["raea"][0], memory_gib=RESERVED["raea"][1]):
return prices.cost(kind, cpu=cpu, memory_gib=memory_gib, seconds=seconds)
@@ -97,21 +103,24 @@ BOOT = 3 # s a container is billed before its Python starts: the bench's cold s
class Bill:
"""What Modal bills for a job's GPU containers: each one's life from its boot (or the job's start, for one an
earlier job left up) to its last run's end, plus BOOT and SCALEDOWN, at its kind's price with 4 cores and 16 GiB."""
earlier job left up) to its last run's end, plus BOOT and SCALEDOWN, at its kind's price with what `job` ("raea", "blender") reserves."""
def __init__(self):
self.t0, self.tasks = time.time(), {}
def __init__(self, job="raea"):
self.t0, self.tasks, self.cores, self.peak_mb, self.cpu, self.gib = time.time(), {}, 0.0, 0, *RESERVED[job]
def add(self, r):
if isinstance(r, dict) and r.get("task"):
b, e = max(r["boot"], self.t0), r["end"]
k, b0, e0 = self.tasks.get(r["task"], (r.get("kind"), b, e))
self.tasks[r["task"]] = (k or r.get("kind"), min(b, b0), max(e, e0))
self.cores, self.peak_mb = max(self.cores, r.get("cores") or 0), max(self.peak_mb, r.get("peak_mb") or 0)
return r
def line(self):
up = [(k or "L4", e - b + BOOT + SCALEDOWN) for k, b, e in self.tasks.values()]
return f"raea farm: billed about ${sum(price(k, s) for k, s in up):.3f}: {len(up)} GPU containers up {sum(s for _, s in up):.0f} s in all"
# the busiest run's cores and biggest process, against what each container reserves (farm.py on())
used = f"; at most {self.cores:.1f} of {self.cpu} cores busy and {self.peak_mb / 1024:.1f} of {self.gib} GB in one process" if self.cores else ""
return f"raea farm: billed about ${sum(price(k, s, self.cpu, self.gib) for k, s in up):.3f}: {len(up)} GPU containers up {sum(s for _, s in up):.0f} s in all{used}"
def encode(frames_dir, out, fps, sound, run, start=0, frames=None):
@@ -145,9 +154,10 @@ def keep(frames_dir, out, start=0):
shutil.move(os.path.join(frames_dir, name), os.path.join(out, f"frame-{i:05d}.png"))
def spread(fn, kind, calls, log, what, bill=None, most=None):
def spread(fn, kind, calls, log, what, bill=None, most=None, got=None):
"""`calls` on `fn`, at most `most` GPUs at once when there are more calls than that (each GPU takes the next call
as it finishes one); each finished run said in the log as it lands. The first failure's code, else 0."""
as it finishes one); each finished run said in the log as it lands, and kept in `got` when given. The first
failure's code, else 0."""
code = 0
if most and len(calls) > most:
fn = fn.with_options(max_containers=most)
@@ -158,6 +168,8 @@ def spread(fn, kind, calls, log, what, bill=None, most=None):
continue
if bill:
bill.add(r)
if got is not None:
got.append(r)
log(f"raea farm: {r.get('frames')} {what} on a {r.get('kind') or kind} in {r['s']:.1f} s")
if r["code"]:
log(r["out"], err=True)
@@ -205,7 +217,8 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
return 3
# a video's runs can't drop warm-up frames without encoding again, so they have none
warm = 0 if video else opts.get("warm", 0)
code = spread(render, kind, [(id, rest, f, at, False, video) for f, at in runs(n0, length - 1, k * m, warm)], log, "frames", bill, k) if left else 0
got = [r0]
code = spread(render, kind, [(id, rest, f, at, False, video) for f, at in runs(n0, length - 1, k * m, warm)], log, "frames", bill, k, got) if left else 0
if code:
return code
# the sound's run finished first: its open files in the job's folder refuse the reload that brings the other
@@ -219,7 +232,7 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
path = os.path.join(work, manifest)
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
with open(path, "w") as f:
json.dump(p["manifest"], f, indent=2)
json.dump(joined(p["manifest"], [r.get("manifest") for r in got]), f, indent=2)
if video:
os.makedirs(os.path.dirname(dest) or ".", exist_ok=True)
c, o, s = join(frames, dest, sound, run)
@@ -229,6 +242,49 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
return 0
def joined(probe, parts):
"""The render's manifest from its runs' own (each holds its frames, and each sound cut to them, a clip's `at` its
source time at the run's first frame): every frame, and each clip made whole again where one run's piece ends on the
frame the next one's starts, at the source time it should. Frame 0's (the probe's) when no run brought one.
11-29 (Dutch): frame 0's alone was written, so a cut's edit was lost and nothing could check its edit points."""
parts = [m for m in parts if m]
if not parts:
return probe
out = {**probe, **{k: v for k, v in parts[0].items() if k not in ("frames", "sounds", "findings")}}
frames = {}
for m in parts:
for f in m.get("frames") or []:
frames.setdefault(f.get("frame"), f)
out["frames"] = [frames[k] for k in sorted(frames, key=lambda x: (x is None, x))]
seen, found = set(), []
for m in [probe, *parts]:
for x in m.get("findings") or []:
key = json.dumps(x, sort_keys=True)
if key not in seen:
seen.add(key)
found.append(x)
out["findings"] = found
snd = [m.get("sounds") for m in parts if isinstance(m.get("sounds"), dict)]
if snd:
fps = snd[0].get("fps") or out.get("fps") or 30
pieces = sorted((c for s in snd for c in s.get("clips") or []), key=lambda c: (c.get("from", 0), str(c.get("key"))))
clips = []
for c in pieces:
prev = next((p for p in reversed(clips) if p.get("key") == c.get("key") and p.get("src") == c.get("src") and p.get("to") == c.get("from")), None)
if prev is not None and abs(prev.get("at", 0) + (prev["to"] - prev["from"]) / fps - c.get("at", 0)) < 1.5 / fps:
prev["to"] = c["to"]
if "fadeOut" in c:
prev["fadeOut"] = c["fadeOut"]
continue
clips.append(dict(c))
notes, lines = [], []
for s in snd:
notes += [n for n in s.get("notes") or [] if n not in notes]
lines += [n for n in s.get("lines") or [] if n not in lines]
out["sounds"] = {**snd[0], "clips": clips, "notes": notes, "lines": lines}
return out
def blender_info(blend, work, run):
c, o, _ = run(["blender", "-b", blend, "--python-expr", BLENDER_INFO], cwd=work)
m = re.search(r"RAEA_INFO (\{.*\})", o)
@@ -275,7 +331,7 @@ def blender(args, opts, work, log, render, run, reload=lambda: None, bill=None):
left = last - first
k = gpus_for(left, frame_s, start_s, opts["gpus"])
m = parts_per_gpu(left, k, frame_s, start_s)
cost = price(kind, r0["s"] + k * m * start_s + left * frame_s)
cost = price(kind, r0["s"] + k * m * start_s + left * frame_s, *RESERVED["blender"])
parts = f" in {k * m} parts" if m > 1 else ""
log(f"raea farm: frame {first} on a {kind} in {r0['s']:.1f} s ({frame_s:.1f} s rendering); {left} left on {k} {kind}s{parts}, about ${cost:.3f} in all")
if opts.get("max_usd") is not None and cost > opts["max_usd"]:
@@ -302,7 +358,7 @@ def dispatch(args, opts, work, log, render, blender_render, cpu_env, run, reload
if opts.get("gpu"):
render, blender_render = (f.with_options(gpu=opts["gpu"]) for f in (render, blender_render))
if args and args[0] == "blender":
bill = Bill()
bill = Bill("blender")
code = blender(args, opts, work, log, blender_render, run, reload, bill)
log(bill.line())
return code
+143
View File
@@ -0,0 +1,143 @@
"""What's in a frame, for the boxes' text checks (server/frames.ts): where people are (a mask, hands and arms included),
their faces, and the things a person holds or a shot is about (a dog, a phone, a cup), so text isn't laid over them and
a clear place for it can be found (11-29, Shane on Dutch: "text being weirdly placed over footage where it blocks a
person or place, dont we have methods of correctly guessing where text needs to go based on the scene?").
Four small ONNX models from OpenCV's zoo, on the CPU through cv2.dnn, each pinned by its hash in farm.py's image:
PP-HumanSeg (2023mar, Apache-2.0): people, as a mask, at 192x192
YOLOX-S (2022nov, Apache-2.0): COCO's 80 things, as boxes, at 640x640
PP-OCRv3 DB (2023may, Apache-2.0): words in the shot (a sign someone holds, a shop's name), as boxes labelled "text"
YuNet (2023mar, MIT): faces, as boxes (the frames check's own)
A frame's answer: its size, a grid of how much of each cell is a person (0-9, a cell ~1/27 of the shorter side), the
faces and the things as [x, y, w, h, label, score] in the frame's pixels."""
import numpy as np
SEG = "/opt/pphumanseg.onnx"
DET = "/opt/yolox_s.onnx"
WORDS = "/opt/ppocr_det.onnx"
FACE = "/opt/yunet.onnx"
# COCO's classes, YOLOX's order
COCO = ("person bicycle car motorcycle airplane bus train truck boat traffic_light fire_hydrant stop_sign parking_meter "
"bench bird cat dog horse sheep cow elephant bear zebra giraffe backpack umbrella handbag tie suitcase frisbee skis "
"snowboard sports_ball kite baseball_bat baseball_glove skateboard surfboard tennis_racket bottle wine_glass cup "
"fork knife spoon bowl banana apple sandwich orange broccoli carrot hot_dog pizza donut cake chair couch "
"potted_plant bed dining_table toilet tv laptop mouse remote keyboard cell_phone microwave oven toaster sink "
"refrigerator book clock vase scissors teddy_bear hair_drier toothbrush").split()
# what a shot is about or a person holds: text over these hides them. Furniture, vehicles and the like are the place
KEEP = {"person", "bird", "cat", "dog", "horse", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee",
"sports_ball", "bottle", "wine_glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich",
"orange", "broccoli", "carrot", "hot_dog", "pizza", "donut", "cake", "laptop", "mouse", "remote", "keyboard",
"cell_phone", "book", "clock", "vase", "scissors", "teddy_bear", "hair_drier", "toothbrush"}
# grid cells along the frame's shorter side (40 px cells in a 1080-wide frame)
CELLS = 27
class Scene:
def __init__(self, seg=SEG, det=DET, face=FACE, words=WORDS):
import cv2
self.cv2 = cv2
self.seg = cv2.dnn.readNet(seg)
self.det = cv2.dnn.readNet(det)
self.words_model = cv2.dnn_TextDetectionModel_DB(words)
self.words_model.setBinaryThreshold(0.3)
self.words_model.setPolygonThreshold(0.5)
self.words_model.setMaxCandidates(200)
self.words_model.setUnclipRatio(2.0)
self.face_path = face
self.face, self.face_size = None, None
def people(self, im):
"""the share of each pixel that's a person, at the frame's size (PP-HumanSeg: RGB, 192x192, (x/255 - 0.5)/0.5)"""
cv2 = self.cv2
h, w = im.shape[:2]
x = cv2.resize(cv2.cvtColor(im, cv2.COLOR_BGR2RGB), (192, 192)).astype(np.float32) / 255.0
x = (x - 0.5) / 0.5
self.seg.setInput(x.transpose(2, 0, 1)[None])
out = self.seg.forward()[0] # [2, 192, 192], logits of background and person
e = np.exp(out - out.max(axis=0, keepdims=True))
p = e[1] / e.sum(axis=0)
return cv2.resize(p, (w, h), interpolation=cv2.INTER_LINEAR)
def things(self, im, least=0.35):
"""COCO things as [x, y, w, h, label, score] (YOLOX-S: BGR as is, letterboxed into 640x640 on grey 114)"""
cv2 = self.cv2
h, w = im.shape[:2]
r = min(640 / h, 640 / w)
pad = np.full((640, 640, 3), 114, np.uint8)
pad[: int(h * r), : int(w * r)] = cv2.resize(im, (int(w * r), int(h * r)))
self.det.setInput(pad.transpose(2, 0, 1)[None].astype(np.float32))
out = self.det.forward()[0] # [8400, 85]: x, y, w, h, objectness, 80 classes, on the strides' grids
grids, strides = [], []
for s in (8, 16, 32):
n = 640 // s
yv, xv = np.meshgrid(np.arange(n), np.arange(n), indexing="ij")
grids.append(np.stack((xv, yv), 2).reshape(-1, 2))
strides.append(np.full((n * n, 1), s))
grids, strides = np.concatenate(grids), np.concatenate(strides)
xy = (out[:, :2] + grids) * strides
wh = np.exp(out[:, 2:4]) * strides
scores = out[:, 4:5] * out[:, 5:]
cls = scores.argmax(1)
best = scores[np.arange(len(cls)), cls]
keep = best > least
boxes = np.concatenate([xy - wh / 2, wh], 1)[keep] / r
cls, best = cls[keep], best[keep]
idx = cv2.dnn.NMSBoxes(boxes.tolist(), best.tolist(), least, 0.45)
found = []
for i in np.array(idx).flatten() if len(idx) else []:
label = COCO[int(cls[i])]
if label not in KEEP:
continue
x, y, bw, bh = boxes[i]
x0, y0 = max(0.0, x), max(0.0, y)
found.append([round(float(x0), 1), round(float(y0), 1), round(float(min(w, x + bw) - x0), 1), round(float(min(h, y + bh) - y0), 1), label, round(float(best[i]), 3)])
return found
def words(self, im, least=0.6):
"""words in the shot as [x, y, w, h, "text", score] (PP-OCRv3 DB at the frame's size, rounded to 32s)"""
cv2 = self.cv2
h, w = im.shape[:2]
size = (max(32, round(w / 32) * 32), max(32, round(h / 32) * 32))
self.words_model.setInputParams(1.0 / 255.0, size, (122.67891434, 116.66876762, 104.00698793))
boxes, conf = self.words_model.detect(im)
out = []
for b, c in zip(boxes, conf):
if float(c) < least:
continue
x, y, bw, bh = cv2.boundingRect(np.array(b, np.int32))
out.append([float(max(0, x)), float(max(0, y)), float(bw), float(bh), "text", round(float(c), 3)])
return out
def faces(self, im):
cv2 = self.cv2
h, w = im.shape[:2]
if self.face is None or self.face_size != (w, h):
self.face, self.face_size = cv2.FaceDetectorYN.create(self.face_path, "", (w, h), 0.6, 0.3, 5000), (w, h)
_, found = self.face.detect(im)
return [[round(float(f[0]), 1), round(float(f[1]), 1), round(float(f[2]), 1), round(float(f[3]), 1), "face", round(float(f[14]), 3)] for f in (found if found is not None else [])]
def read(self, im):
h, w = im.shape[:2]
p = self.people(im)
return {"w": w, "h": h, "grid": grid(p, w, h), "things": self.things(im) + self.words(im), "faces": self.faces(im)}
def grid(p, w, h):
"""a person mask (0-1 a pixel) as a grid of digits, a row a string: how much of each cell is a person, 0-9"""
cell = min(w, h) / CELLS
cols, rows = max(1, round(w / cell)), max(1, round(h / cell))
out = []
for r in range(rows):
y0, y1 = int(r * h / rows), int((r + 1) * h / rows)
row = ""
for c in range(cols):
x0, x1 = int(c * w / cols), int((c + 1) * w / cols)
v = float(p[y0:y1, x0:x1].mean()) if y1 > y0 and x1 > x0 else 0.0
row += str(min(9, int(v * 10)))
out.append(row)
return {"cols": cols, "rows": rows, "people": out}
+4 -1
View File
@@ -187,7 +187,10 @@ server_image = indexer_image_for(None)
# one file indexed as a job (tools/library-index cloud-cli.ts), for a file of any length: raea cloud submits it through
# the API's POST /v1/index-jobs and collects it with GET /v1/index-jobs/ID on its next alarm (index-run.ts)
@app.function(image=indexer_image, gpu=GPU, cpu=4, memory=16384, secrets=[secret], timeout=3600, max_containers=12, scaledown_window=120)
# 2 cores and 8 GiB reserved (4 and 16 until 11-29): a 52 s clip measured 1.9 cores busy and 4.9 GB across its
# processes, and from 11-17 to 11-29 the app's CPU and memory cost more than its GPU. A job that takes more is billed
# for what it takes: these are floors, with no limit set
@app.function(image=indexer_image, gpu=GPU, cpu=2, memory=8192, secrets=[secret], timeout=3600, max_containers=12, scaledown_window=120)
def index_job(url: str, name: str, kind: str) -> dict:
import json
import subprocess as sp
+3
View File
@@ -13,5 +13,8 @@ case "${1:-}" in
words|transcribe) exec node /opt/raea-cloud/server/words.ts "$@" ;;
# faces cut by the frame or a seam, text too small (server/frames.ts, the farm's face detector)
frames) exec node /opt/raea-cloud/server/frames.ts "$@" ;;
# edit points inside words or on sound, lines too quiet to hear, effects no one hears (server/sound.ts, against each
# take's own words and sound); `raea sound` alone is raea's
sound) if [ "${2:-}" = check ]; then exec node /opt/raea-cloud/server/sound.ts "$@"; fi ;;
esac
exec /opt/raea/bin/raea "$@"
+105 -6
View File
@@ -9,6 +9,12 @@
// text: each text the render's manifest shows (raea render --manifest; a .tsx render through raea cloud writes
// VIDEO.render.json by itself), its font size in pixels of a 1080-wide frame: under 40 px is an error (no one
// reads it on a phone), under 48 px a warning (small for anything but a badge or small print).
// placement (11-29): each text against what's under it (the farm's POST /v1/scene: people, faces, the things a
// shot is about, words in the shot like a sign): text over a face, a thing or a person, where a clear place of
// its size exists, is said with that place (server/place.ts).
// raea frames place FILE [--at S[,S...]] [--box WxH] [-o REPORT.json]
// the clearest places in FILE (a take or an export, a picture or a video, at those seconds) for a box WxH in a
// 1080-wide frame (a caption, 840x110, by default): read the takes with it before laying text over them.
// Exit 1 on any error. A face at the edge that's meant (someone walking out of shot) is said, with its reason, in
// VIDEO.despite.txt beside the video: its findings are then warnings.
import { spawnSync } from "node:child_process"
@@ -16,6 +22,7 @@ import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSy
import os from "node:os"
import path from "node:path"
import { pathToFileURL } from "node:url"
import { placeReport, textOver, type Scene } from "./place.ts"
/** frames sampled a second, and the width they're read at (a face's place is in shares of the picture) */
const RATE = 2
@@ -27,7 +34,7 @@ export const FACE_MIN = 0.05
export const TEXT_ERROR = 40
export const TEXT_WARN = 48
export type Finding = { level: "error" | "warn"; kind: "face-cut" | "split" | "text-small"; at: number | null; until?: number; says: string }
export type Finding = { level: "error" | "warn"; kind: "face-cut" | "split" | "text-small" | "text-over"; at: number | null; until?: number; says: string }
/** a line where the picture jumps across nearly the whole frame (the farm's): its axis (h, a row), where, and its share */
export type Seam = [string, number, number]
export type Faces = { w: number; h: number; faces: number[][]; seams?: Seam[] } | null
@@ -149,6 +156,58 @@ function ffmpeg(args: string[]) {
if (r.status !== 0) throw new Error(`ffmpeg: ${(r.stderr ?? "").slice(-400)}`)
}
/** what the farm reads in a file's frames (`at`: those seconds, else RATE a second), from its POST /v1/scene, or from
* /v1/faces alone on a farm without it (then each scene is null) */
export async function scenes(file: string, at?: number[], f: typeof fetch = fetch): Promise<{ faces: Faces[]; scenes: Scene[] }> {
const url = process.env.RAEA_CLOUD_GPU_URL
const token = process.env.RAEA_CLOUD_GPU_TOKEN ?? ""
if (!url) throw new Error("the frames check needs the farm (RAEA_CLOUD_GPU_URL); this box has none set")
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-frames-"))
try {
const scale = `scale='if(gt(iw,ih),-2,${SIDE})':'if(gt(iw,ih),${SIDE},-2)'`
if (/\.(png|jpe?g|webp)$/i.test(file)) ffmpeg(["-v", "error", "-y", "-i", file, "-vf", scale, "-q:v", "4", path.join(dir, "f00001.jpg")])
else if (at?.length) at.forEach((s, i) => ffmpeg(["-v", "error", "-y", "-ss", String(s), "-i", file, "-frames:v", "1", "-vf", scale, "-q:v", "4", path.join(dir, `f${String(i + 1).padStart(5, "0")}.jpg`)]))
else ffmpeg(["-v", "error", "-y", "-i", file, "-vf", `fps=${RATE},${scale}`, "-q:v", "4", path.join(dir, "f%05d.jpg")])
const jpgs = readdirSync(dir).filter((n) => n.endsWith(".jpg")).sort()
const outF: Faces[] = []
const outS: Scene[] = []
let scene = true
for (let i = 0; i < jpgs.length; i += 300) {
const body = JSON.stringify({ frames: jpgs.slice(i, i + 300).map((n) => readFileSync(path.join(dir, n)).toString("base64")) })
const call = async (route: string) => {
let r: Response | undefined
let why = ""
for (let k = 0; k < 4; k++) {
r = await f(`${url.replace(/\/$/, "")}${route}`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body, signal: AbortSignal.timeout(600_000) })
if (r.ok || r.status === 404) break
why = `${r.status} ${(await r.text()).slice(0, 300)}`
if (r.status < 500) break
await new Promise((ok) => setTimeout(ok, 1000 * 2 ** k))
}
return { r, why }
}
let { r, why } = scene ? await call("/v1/scene") : { r: undefined as Response | undefined, why: "" }
if (scene && r?.status === 404) scene = false
if (!scene) ({ r, why } = await call("/v1/faces"))
if (!r?.ok) throw new Error(`the farm couldn't look at ${path.basename(file)}: ${why || r?.status}`)
const got = ((await r.json()) as { frames: (Record<string, unknown> | null)[] }).frames
for (const g of got) {
if (!g) {
outF.push(null)
outS.push(null)
continue
}
const fs = (g.faces as unknown[][]) ?? []
outF.push({ w: g.w as number, h: g.h as number, faces: fs.map((x) => (typeof x[4] === "string" ? [x[0], x[1], x[2], x[3], x[5]] : x) as number[]), seams: g.seams as Seam[] | undefined })
outS.push(scene && g.grid ? ({ w: g.w, h: g.h, grid: g.grid, things: g.things ?? [], faces: fs.map((x) => (typeof x[4] === "string" ? x : [x[0], x[1], x[2], x[3], "face", x[4]])) } as Scene) : null)
}
}
return { faces: outF, scenes: outS }
} finally {
rmSync(dir, { recursive: true, force: true })
}
}
/** VIDEO's faces, two frames a second, by the farm */
export async function faces(file: string, f: typeof fetch = fetch): Promise<Faces[]> {
const url = process.env.RAEA_CLOUD_GPU_URL
@@ -187,7 +246,40 @@ function flag(args: string[], name: string): string | undefined {
/** the manifest a render of VIDEO wrote: --manifest, or VIDEO.render.json beside it */
export const manifestOf = (video: string) => `${video.slice(0, video.length - path.extname(video).length)}.render.json`
/** `raea frames place FILE [--at S,...] [--box WxH]` */
async function place(a: string[]): Promise<number> {
const file = a.find((x, i) => !x.startsWith("-") && !["--at", "--box", "-o"].includes(a[i - 1] ?? ""))
if (!file || !existsSync(file)) {
console.error("usage: raea frames place FILE [--at S[,S...]] [--box WxH] [-o REPORT.json] (the clearest places in a take or an export for a box WxH in a 1080-wide frame; a caption, 840x110, by default)")
return 2
}
const box = (flag(a, "--box") ?? "840x110").split("x").map(Number) as [number, number]
if (box.length !== 2 || !box.every((v) => v > 0)) {
console.error("raea frames place: --box is WxH in a 1080-wide frame's pixels, like 840x110")
return 2
}
let at = flag(a, "--at")?.split(",").map(Number).filter(Number.isFinite)
if (!at?.length && !/\.(png|jpe?g|webp)$/i.test(file)) {
const r = spawnSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", file], { encoding: "utf8" })
const len = Number.parseFloat(r.stdout) || 1
const n = Math.min(12, Math.max(1, Math.floor(len)))
at = Array.from({ length: n }, (_, i) => Math.round(((i + 0.5) * len * 100) / n) / 100)
}
const { scenes: ss } = await scenes(file, at)
if (!ss.some(Boolean)) {
console.error("raea frames place: the farm has no scene reader yet (POST /v1/scene): nothing to place by")
return 1
}
const rep = placeReport(file, ss, box)
console.log(`${path.basename(file)}${at?.length ? ` at ${at.join(", ")} s` : ""}: the clearest places for a ${box[0]}x${box[1]} box in a ${rep.frame?.join("x")} frame, best first`)
for (const p of rep.places) console.log(` left ${p.left} px, top ${p.top} px (${p.at}) cost ${p.cost}${p.covers.length ? ` covers ${p.covers.join(", ")}` : " clear"}`)
const o = flag(a, "-o")
if (o) writeFileSync(o, JSON.stringify(rep, null, 1))
return 0
}
export async function main(args: string[]): Promise<number> {
if (args[0] === "place") return place(args.slice(1))
const a = args[0] === "check" ? args.slice(1) : args
const video = a.find((x, i) => !x.startsWith("-") && !["--manifest", "-o"].includes(a[i - 1] ?? ""))
if (!video || !existsSync(video)) {
@@ -197,14 +289,21 @@ export async function main(args: string[]): Promise<number> {
const m = flag(a, "--manifest") ?? manifestOf(video)
const found: Finding[] = []
let looked = 0
const man = existsSync(m) ? JSON.parse(readFileSync(m, "utf8")) : null
let placed: number | null = null
try {
const fr = await faces(video)
looked = fr.length
found.push(...cutFaces(fr))
const got = await scenes(video)
looked = got.faces.length
found.push(...cutFaces(got.faces))
if (man && got.scenes.some(Boolean)) {
const over = textOver(man, got.scenes, RATE)
placed = over.length
found.push(...over)
}
} catch (e) {
console.log(`WARN the faces check couldn't run: ${(e as Error).message}`)
}
const texts = existsSync(m) ? smallText(JSON.parse(readFileSync(m, "utf8"))) : null
const texts = man ? smallText(man) : null
if (texts) found.push(...texts)
const despite = `${video.slice(0, video.length - path.extname(video).length)}.despite.txt`
const why = existsSync(despite) ? readFileSync(despite, "utf8").trim() : ""
@@ -212,7 +311,7 @@ export async function main(args: string[]): Promise<number> {
for (const x of out) console.log(`${x.level === "error" ? "ERROR" : "WARN "} ${x.at === null ? "" : `${x.at.toFixed(1)} s `}${x.says}`)
const errors = out.filter((x) => x.level === "error").length
const report = flag(a, "-o") ?? `${video.slice(0, video.length - path.extname(video).length)}.frames-check.json`
writeFileSync(report, JSON.stringify({ video, looked_at: looked, text_checked: texts !== null, findings: out }, null, 1))
writeFileSync(report, JSON.stringify({ video, looked_at: looked, text_checked: texts !== null, placement_checked: placed !== null, findings: out }, null, 1))
console.log(`${errors ? "FAILED" : "PASSED"} ${path.basename(video)}: ${looked} frames looked at for faces, ${texts === null ? "no manifest for its text" : `${new Set(texts.map((t) => t.says)).size} small texts`}, ${errors} errors, ${out.length - errors} warnings; ${path.basename(report)}`)
return errors ? 1 : 0
}
+16 -1
View File
@@ -192,6 +192,21 @@ async function main() {
const code = await afterRender(made, say)
if (code) process.exitCode = code
}
// what its sound gets wrong (sound.ts), from the render's manifest against each take's own words and sound: an edit
// point inside a word or on its sound, a line too quiet to hear, an effect no one hears (11-29, Shane on Dutch)
if (!exit && /\.(mp4|mov|m4v|webm)$/i.test(made) && existsSync(made) && process.env.RAEA_CLOUD_SOUND !== "0") {
const mi = args.indexOf("--manifest")
const man = mi >= 0 ? path.resolve(process.cwd(), args[mi + 1] ?? "") : ""
if (man && existsSync(man)) {
const { main: sound } = await import("./sound.ts")
say(`the sound check: ${path.basename(made)}'s edit points, line levels and effects`)
const code = await sound(["check", made, "--manifest", man]).catch((e) => (say(`the sound check couldn't run: ${(e as Error).message}`), 0))
if (code) {
say(`${path.basename(made)}'s sound has faults a listener hears: fix every ERROR above (move each cut to the pause or boundary it names, set the gainDb it gives), then render again`)
process.exitCode = code
}
}
}
// what its pictures get wrong (frames.ts): faces cut by the frame or a split screen's seam, text too small to read
// (11-25, Shane: "it cuts out faces all the time", "it makes text too small")
if (!exit && /\.(mp4|mov|m4v|webm)$/i.test(made) && existsSync(made) && process.env.RAEA_CLOUD_FRAMES !== "0") {
@@ -200,7 +215,7 @@ async function main() {
const mi = args.indexOf("--manifest")
const code = await frames(["check", made, ...(mi >= 0 ? ["--manifest", path.resolve(process.cwd(), args[mi + 1] ?? "")] : [])]).catch((e) => (say(`the frames check couldn't run: ${(e as Error).message}`), 0))
if (code) {
say(`${path.basename(made)} has a face cut or text too small: fix every ERROR above (reframe on the person, make the text bigger), then render again. A face at the edge that's meant goes in ${path.basename(made, path.extname(made))}.despite.txt with why`)
say(`${path.basename(made)} has a face cut, text too small, or text over what the shot shows: fix every ERROR above (reframe on the person, make the text bigger, move the text to the place it names; raea frames place TAKE shows a take's clear places), then render again. A face at the edge that's meant goes in ${path.basename(made, path.extname(made))}.despite.txt with why`)
process.exitCode = code
}
}
+284
View File
@@ -0,0 +1,284 @@
// Where text can go in a shot, and text laid where it hides what the shot is about (11-29, Shane on Dutch: "text being
// weirdly placed over footage where it blocks a person or place, dont we have methods of correctly guessing where text
// needs to go based on the scene? ... the rule of thirds, and placement of things over the scene").
//
// A frame's scene (the farm's POST /v1/scene: a person mask as a grid, faces, and the things a shot is about, a dog, a
// phone, a cup) becomes a cost for each grid cell: a face most, then a thing, then a person in the shot (the body
// itself, and the box around them a little), then the edges a phone's own buttons and captions cover; open ground is
// free. A text's cost is the mean of the cells it covers. A text is badly placed when it covers a face or a thing, or
// a person, and a place of the same size costs much less; that place is what's said.
//
// raea frames place FILE [--at S[,S...]] [--box WxH] [-o REPORT.json]
// FILE (a take or an export, a picture or a video) read at those seconds (a video: one a second, at most 12):
// the clearest places for a box WxH (in a 1080-wide frame; a caption, 840x110, by default), best first, as its
// top-left in pixels and in shares of the frame, and what each covers.
import path from "node:path"
/** a frame's scene, as the farm reads it (deploy/modal/farm_scene.py), in the pixels of the frame it was sent */
export type Scene = { w: number; h: number; grid: { cols: number; rows: number; people: string[] }; things: Thing[]; faces: Thing[] } | null
/** [x, y, w, h, label, score] */
export type Thing = [number, number, number, number, string, number]
/** a box in shares of the frame: x, y, w, h */
export type Box = [number, number, number, number]
/** what each covered cell costs */
const COST = { face: 10, thing: 6, body: 4, subject: 2, crowd: 0.5, edge: 5 }
/** a person whose box is this share of the frame's height or more is in the shot; smaller ones are passers-by */
const SUBJECT_MIN = 0.25
/** a face this share of the frame's height or more is someone in the shot (frames.ts FACE_MIN); smaller, a passer-by */
const FACE_IN_SHOT = 0.05
/** a thing this share of the frame's area or more is what the shot shows (a dog at someone's feet, a phone held up) */
const THING_MIN = 0.006
/** a text is badly placed when it costs this much or more, and a clear place costs this much less */
export const BAD = 1.6
export const BETTER = 1.2
/** the edges a phone's own interface covers on a tall frame (Reels and TikTok: the header, the buttons on the right,
* the caption and the bar at the bottom), in shares; a wide or square frame keeps a 5% margin all round */
export function safe(w: number, h: number): { top: number; bottom: number; left: number; right: number } {
return h / w > 1.5 ? { top: 0.07, bottom: 0.2, left: 0.04, right: 0.12 } : { top: 0.05, bottom: 0.05, left: 0.05, right: 0.05 }
}
export type Cost = { cols: number; rows: number; cost: Float32Array; why: Uint8Array }
/** why a cell costs what it does: 0 open, 1 crowd, 2 a person's box, 3 a body, 4 a thing, 5 a face, 6 the edge */
export const WHY = ["open ground", "passers-by", "a person in the shot", "a person in the shot", "", "a face", "the phone's own interface", "other text on screen"]
/** a box (shares) overlapping another by this share of the smaller one is the same place */
const overlaps = (a: Box, b: Box, share: number) => {
const ix = Math.max(0, Math.min(a[0] + a[2], b[0] + b[2]) - Math.max(a[0], b[0]))
const iy = Math.max(0, Math.min(a[1] + a[3], b[1] + b[3]) - Math.max(a[1], b[1]))
return ix * iy > share * Math.min(a[2] * a[3], b[2] * b[3])
}
const shareOf = (s: NonNullable<Scene>, t: Thing): Box => [t[0] / s.w, t[1] / s.h, t[2] / s.w, t[3] / s.h]
/** a scene as a cost per grid cell, and what each cell holds. `ours`: the render's own texts on this frame (the words
* the farm read there are ours, not the shot's); `others`: the ones a place must also stay off */
export function costs(s: NonNullable<Scene>, ours: Box[] = [], others: Box[] = []): Cost {
const { cols, rows, people } = s.grid
const cost = new Float32Array(cols * rows)
const why = new Uint8Array(cols * rows)
const set = (c: number, r: number, v: number, k: number) => {
if (c < 0 || r < 0 || c >= cols || r >= rows) return
const i = r * cols + c
if (v > cost[i]) {
cost[i] = v
why[i] = k
}
}
const cells = (t: Thing, pad = 0, inset = 0) => {
const [x, y, w, h] = t
const c0 = Math.floor(((x + w * inset) / s.w) * cols) - pad
const c1 = Math.ceil(((x + w * (1 - inset)) / s.w) * cols) - 1 + pad
const r0 = Math.floor((y / s.h) * rows) - pad
const r1 = Math.ceil(((y + h) / s.h) * rows) - 1 + pad
const out: [number, number][] = []
for (let r = r0; r <= r1; r++) for (let c = c0; c <= c1; c++) out.push([c, r])
return out
}
const persons = s.things.filter((t) => t[4] === "person")
for (const p of persons) {
const inShot = p[3] >= s.h * SUBJECT_MIN
// a person's box is loose around the body (the air between arms and legs): its middle costs more than its sides
for (const [c, r] of cells(p)) set(c, r, inShot ? COST.subject : COST.crowd, inShot ? 2 : 1)
if (inShot) for (const [c, r] of cells(p, 0, 0.15)) set(c, r, COST.subject + 1, 2)
}
// the body itself, where the mask sees it (a light coat it can miss; a card laid over it hides it, hence the box)
for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) if (Number(people[r]?.[c] ?? 0) >= 4) set(c, r, COST.body, 3)
for (const t of s.things) {
if (t[4] === "person") continue
if (t[4] === "text" ? ours.some((o) => overlaps(o, shareOf(s, t), 0.4)) : (t[2] * t[3]) / (s.w * s.h) < THING_MIN) continue
for (const [c, r] of cells(t)) set(c, r, COST.thing, 4)
}
for (const o of others) for (const [c, r] of cells([o[0] * s.w, o[1] * s.h, o[2] * s.w, o[3] * s.h, "overlay", 1])) set(c, r, COST.thing, 7)
// a face and a cell around it: hair, chin, the mic at the mouth
for (const f of s.faces) {
if (f[3] >= s.h * FACE_IN_SHOT) for (const [c, r] of cells(f, 1)) set(c, r, COST.face, 5)
else for (const [c, r] of cells(f)) set(c, r, COST.crowd + 1, 1)
}
const sf = safe(s.w, s.h)
for (let r = 0; r < rows; r++)
for (let c = 0; c < cols; c++) {
const x = (c + 0.5) / cols
const y = (r + 0.5) / rows
if (y < sf.top || y > 1 - sf.bottom || x < sf.left || x > 1 - sf.right) set(c, r, COST.edge, 6)
}
return { cols, rows, cost, why }
}
/** labels of the things that make cells cost, for saying what a text covers */
function thingsUnder(s: NonNullable<Scene>, b: Box, ours: Box[] = []): string[] {
const out = new Set<string>()
for (const t of [...s.faces, ...s.things]) {
if (t[4] === "text" && ours.some((o) => overlaps(o, shareOf(s, t), 0.4))) continue
if (t[4] === "person" && t[3] < s.h * SUBJECT_MIN) continue
if (t[4] === "face" && t[3] < s.h * FACE_IN_SHOT) continue
if (t[4] !== "person" && t[4] !== "face" && (t[2] * t[3]) / (s.w * s.h) < THING_MIN) continue
const [x, y, w, h] = [t[0] / s.w, t[1] / s.h, t[2] / s.w, t[3] / s.h]
const ix = Math.max(0, Math.min(b[0] + b[2], x + w) - Math.max(b[0], x))
const iy = Math.max(0, Math.min(b[1] + b[3], y + h) - Math.max(b[1], y))
if (ix * iy > 0.12 * Math.min(w * h, b[2] * b[3])) out.add(t[4] === "person" ? "a person in the shot" : t[4] === "face" ? "a face" : t[4] === "text" ? "words in the shot (a sign)" : `a ${t[4].replace(/_/g, " ")}`)
}
return [...out]
}
/** the mean cost of the cells a box covers (each cell weighted by how much of it the box covers) */
export function boxCost(k: Cost, b: Box): number {
let sum = 0
let area = 0
const c0 = Math.max(0, Math.floor(b[0] * k.cols))
const c1 = Math.min(k.cols - 1, Math.ceil((b[0] + b[2]) * k.cols) - 1)
const r0 = Math.max(0, Math.floor(b[1] * k.rows))
const r1 = Math.min(k.rows - 1, Math.ceil((b[1] + b[3]) * k.rows) - 1)
for (let r = r0; r <= r1; r++)
for (let c = c0; c <= c1; c++) {
const ox = Math.min(b[0] + b[2], (c + 1) / k.cols) - Math.max(b[0], c / k.cols)
const oy = Math.min(b[1] + b[3], (r + 1) / k.rows) - Math.max(b[1], r / k.rows)
const a = Math.max(0, ox) * Math.max(0, oy)
sum += a * k.cost[r * k.cols + c]
area += a
}
return area ? sum / area : 0
}
/** where a box of this size costs least, over several frames together (a text's whole time on screen): candidates
* every 2% down and, for a box narrower than the frame's safe width, across too; a box on a third line (the rule of
* thirds) wins a tie */
export function places(ks: Cost[], w: number, h: number, size: [number, number], n = 3): { box: Box; cost: number }[] {
const sf = safe(w, h)
const out: { box: Box; cost: number }[] = []
const xs: number[] = []
const span = 1 - sf.left - sf.right - size[0]
if (span <= 0.02) xs.push(Math.max(0, (1 - size[0]) / 2))
else for (let x = sf.left; x <= sf.left + span + 1e-9; x += span / 4) xs.push(x)
for (let y = sf.top; y + size[1] <= 1 - sf.bottom + 1e-9; y += 0.02)
for (const x of xs) {
const b: Box = [x, y, size[0], size[1]]
const c = ks.reduce((s, k) => s + boxCost(k, b), 0) / ks.length
const mid = y + size[1] / 2
const third = Math.min(Math.abs(mid - 1 / 3), Math.abs(mid - 2 / 3))
// a wide box (a caption, a card) reads best centred; a narrow one may sit to a side
const centre = size[0] > 0.4 ? Math.abs(x + size[0] / 2 - (sf.left + (1 - sf.right)) / 2) * 1.5 : 0
out.push({ box: b, cost: c + third * 0.3 + centre })
}
out.sort((a, b) => a.cost - b.cost)
// the best few, apart from each other
const picked: { box: Box; cost: number }[] = []
for (const o of out) {
if (picked.some((p) => Math.abs(p.box[1] - o.box[1]) < size[1] && Math.abs(p.box[0] - o.box[0]) < size[0])) continue
picked.push(o)
if (picked.length >= n) break
}
return picked
}
export type Finding = { level: "error" | "warn"; kind: "text-over"; at: number | null; until?: number; says: string }
const px = (v: number, dim: number) => Math.round(v * dim)
/** each text the render's manifest shows, against the scenes of the frames it's on (sampled `rate` a second): one
* finding a text, when it covers a face, a thing or a person and a clearer place of its size exists */
export function textOver(manifest: any, scenes: Scene[], rate: number): Finding[] {
const W = Number(manifest?.width) || 1080
const H = Number(manifest?.height) || 1920
const fps = Number(manifest?.fps) || 30
// each text: its box (the ink with a margin, or the laid-out box when that's no bigger than twice the ink: a card's
// own box), and the sampled frames it's on
type On = { text: string; box: Box; from: number; to: number; frames: number[] }
// every text's box on each sampled frame
const onFrame = new Map<number, Box[]>()
const texts = new Map<string, On>()
for (const fr of (manifest?.frames ?? []) as any[]) {
const t0 = Number(fr?.frame ?? 0) / fps
const i = Math.round(t0 * rate)
if (Math.abs(i / rate - t0) > 0.5 / fps) continue
for (const t of (fr?.text ?? []) as any[]) {
const text = String(t?.text ?? "").trim()
if (!text || (t?.opacity ?? 1) <= 0.3) continue
const ink = (t?.ink ?? t?.box) as number[] | undefined
const lay = t?.box as number[] | undefined
if (!ink || ink.length < 4) continue
const useBox = lay && lay[2] * lay[3] <= 2 * ink[2] * ink[3]
const b = useBox ? lay! : [ink[0] - 12, ink[1] - 8, ink[2] + 24, ink[3] + 16]
const box: Box = [b[0] / W, b[1] / H, b[2] / W, b[3] / H]
const key = `${text}@${box.map((v) => v.toFixed(2)).join(",")}`
onFrame.set(i, [...(onFrame.get(i) ?? []), box])
const on = texts.get(key) ?? { text, box, from: t0, to: t0, frames: [] }
on.to = t0
if (!on.frames.includes(i)) on.frames.push(i)
texts.set(key, on)
}
}
// lines stacked into one block (a checklist, a two-line caption, a card's title and its line) move together: texts on
// the same frames whose boxes touch or nearly touch, one under the other
const all = [...texts.values()].sort((p, q) => p.box[1] - q.box[1])
const blocks: (On & { lines: number })[] = []
for (const t of all) {
const near = blocks.find((b) => {
const shared = t.frames.filter((f) => b.frames.includes(f)).length
const gap = t.box[1] - (b.box[1] + b.box[3])
const ox = Math.min(b.box[0] + b.box[2], t.box[0] + t.box[2]) - Math.max(b.box[0], t.box[0])
return shared * 2 >= Math.min(t.frames.length, b.frames.length) && gap < 0.02 && gap > -t.box[3] && ox > 0
})
if (!near) {
blocks.push({ ...t, frames: [...t.frames], lines: 1 })
continue
}
const x0 = Math.min(near.box[0], t.box[0])
const y0 = Math.min(near.box[1], t.box[1])
const x1 = Math.max(near.box[0] + near.box[2], t.box[0] + t.box[2])
const y1 = Math.max(near.box[1] + near.box[3], t.box[1] + t.box[3])
near.box = [x0, y0, x1 - x0, y1 - y0]
near.from = Math.min(near.from, t.from)
near.to = Math.max(near.to, t.to)
near.lines++
}
const out: Finding[] = []
for (const on of blocks) {
// the scene's cost on each of the block's frames: our own texts there aren't the shot's words, and the other texts
// on screen are places it can't go
const costAt = (i: number) => {
const s = scenes[i]
if (!s) return null
const ours = onFrame.get(i) ?? []
return costs(s, ours, ours.filter((b) => !overlaps(b, on.box, 0.5)))
}
const ks = on.frames.map(costAt).filter((k): k is Cost => !!k)
if (!ks.length) continue
const here = ks.reduce((s, k) => s + boxCost(k, on.box), 0) / ks.length
if (here < BAD) continue
const best = places(ks, W, H, [on.box[2], on.box[3]], 1)[0]
const under = [...new Set(on.frames.flatMap((i) => (scenes[i] ? thingsUnder(scenes[i]!, on.box, onFrame.get(i) ?? []) : [])))]
const what = under.length ? under.join(", ") : "what the shot shows"
const q = `${on.text.length > 40 ? `“${on.text.slice(0, 40)}...”` : `“${on.text}”`}${on.lines > 1 ? ` (and the ${on.lines - 1} line${on.lines > 2 ? "s" : ""} under it)` : ""}`
const when = on.to - on.from < 0.5 ? `at ${on.from.toFixed(1)} s` : `from ${on.from.toFixed(1)} s to ${on.to.toFixed(1)} s`
if (best && best.cost <= here - BETTER) {
const face = under.includes("a face")
out.push({ level: face || here >= BAD + 1.5 ? "error" : "warn", kind: "text-over", at: on.from, until: on.to, says: `${q} covers ${what} ${when}: move it to left ${px(best.box[0], W)} px, top ${px(best.box[1], H)} px (${Math.round(best.box[1] * 100)}% down), which is clear there. raea frames place shows the clear places in a shot` })
} else if (under.includes("a face")) {
out.push({ level: "error", kind: "text-over", at: on.from, until: on.to, says: `${q} covers a face ${when} and no place of its size is clear: make it smaller, put it on a shot with room, or cut to one` })
} else if (here >= BAD + 1.5) {
out.push({ level: "warn", kind: "text-over", at: on.from, until: on.to, says: `${q} covers ${what} ${when}, and no place of its size is clear in this shot: make it smaller, show it on a shot with room (a wider one, a cutaway), or as a card of its own` })
}
}
return out.sort((a, b) => (a.at ?? 0) - (b.at ?? 0))
}
/** `raea frames place`'s answer for a set of scenes and a box size (in a 1080-wide frame's pixels) */
export function placeReport(file: string, scenes: Scene[], size: [number, number]) {
const ss = scenes.filter((s): s is NonNullable<Scene> => !!s)
if (!ss.length) return { file, places: [] }
const w = ss[0].w
const h = ss[0].h
const scale = 1080 / Math.min(w, h)
const W = w * scale
const H = h * scale
const share: [number, number] = [size[0] / W, size[1] / H]
const ks = ss.map((s) => costs(s))
const ps = places(ks, w, h, share, 3)
return {
file: path.basename(file),
frame: [Math.round(W), Math.round(H)],
box: size,
places: ps.map((p) => ({ left: px(p.box[0], W), top: px(p.box[1], H), at: `${Math.round(p.box[1] * 100)}% down`, cost: Math.round(p.cost * 100) / 100, covers: [...new Set(ss.flatMap((s) => thingsUnder(s, p.box)))] })),
}
}
+298
View File
@@ -0,0 +1,298 @@
// `raea sound check` on a raea cloud box: what a cut's sound gets wrong that a listener hears at once, measured from the
// edit itself (its render manifest) against each source take's own words and sound, so it can't be passed by editing
// what the cut is "meant" to say (11-29, Shane on Dutch: "a lot of it is audio cuts, fading out words, putting in audio
// that is too low to hear but whisper picks up ... i dont really hear any sound effects being used").
//
// raea sound check VIDEO [--manifest RENDER.json] [-o REPORT.json]
// edit points: each voice clip's in and out against its take's words (TAKE.words.json beside the take; heard by
// the farm's Whisper when it has none) and its take's own level every 10 ms. A clip that starts or ends inside
// a word, or on sound (a word's tail, its first consonant), is an error, with the nearest gap to move it to.
// levels: each voice clip's speech level (its take's, plus its gainDb) against the cut's other lines: 6 dB or
// more apart is an error (a line too quiet to hear, that a transcriber still hears), 4 dB a warning; the
// gainDb that evens it is said.
// effects and music: an effect 10 dB or more under the voice is an error (no one hears it); music more than
// 26 dB under the voice, or within 6 dB of it, a warning.
// Exit 1 on any error. The report is VIDEO.sound-check.json beside it.
import { spawnSync } from "node:child_process"
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import { pathToFileURL } from "node:url"
import { hear, levels, type Word } from "./words.ts"
/** a voice clip's speech level is its take's loud 10 ms frames (the 90th percentile) inside the clip */
const SPEECH_Q = 0.9
/** at a cut point, sound this close to the speech level (dB) is speech still going: a word's tail or first consonant */
const ON_SOUND = 10
/** a gap to cut in: 40 ms at least this far under the speech level (dB), or, in a noisy take (a street), within
* GAP_FLOOR of its own quietest sound, but never closer than GAP_LEAST to the speech */
const GAP = 18
const GAP_FLOOR = 6
const GAP_LEAST = 8
/** a take's floor: its quietest 10 ms frames (the 10th percentile) around the clip */
const FLOOR_Q = 0.1
/** how far either side of a cut point a gap is looked for (s) */
const NEAR = 0.4
/** lines this far apart (dB) are an error, a warning */
const LEVEL_ERROR = 6
const LEVEL_WARN = 4
/** an effect this far under the voice (dB) isn't heard */
const SFX_UNDER = 10
/** music: further under than this isn't heard, closer than this fights the words */
const MUSIC_LOST = 26
const MUSIC_FIGHTS = 6
export type Finding = { level: "error" | "warn"; kind: "edit-in-word" | "edit-on-sound" | "level" | "effect-unheard" | "music" | "manifest"; at: number | null; says: string }
export type Clip = { key?: string; from: number; to: number; src: string; at: number; gainDb?: number; bus?: string; fadeIn?: number; fadeOut?: number }
export type Manifest = { fps?: number; length?: number; frames?: unknown[]; sounds?: { fps?: number; clips?: Clip[] } }
/** a take's level every 10 ms (dB) from `start` s on */
export type Levels = { start: number; db: number[] }
const MUSIC = /music|bed|score/i
const SFX = /sfx|fx|effect|foley|sting/i
export const busOf = (c: Clip): "voice" | "music" | "sfx" => (c.bus && MUSIC.test(c.bus) ? "music" : c.bus && SFX.test(c.bus) ? "sfx" : c.bus === "voice" || !c.bus ? (SFX.test(path.basename(c.src)) ? "sfx" : MUSIC.test(path.basename(c.src)) ? "music" : "voice") : "voice")
const pct = (xs: number[], q: number) => {
if (!xs.length) return -100
const s = [...xs].sort((a, b) => a - b)
return s[Math.min(s.length - 1, Math.floor(q * s.length))]
}
const at = (l: Levels, t: number) => l.db[Math.round((t - l.start) * 100)] ?? -100
/** the loudest 10 ms frame in [a, b] */
const peak = (l: Levels, a: number, b: number) => {
let m = -100
for (let t = a; t <= b + 1e-9; t += 0.01) m = Math.max(m, at(l, t))
return m
}
const secs = (t: number) => `${t.toFixed(2)} s`
/** the speech level of a clip's stretch of its take: its loud frames, inside its words when it has any */
export function speechLevel(l: Levels, a: number, b: number, words: Word[]): number {
const inWords = words.filter((w) => w.end > a && w.start < b)
const frames: number[] = []
for (let t = a; t < b; t += 0.01) if (!inWords.length || inWords.some((w) => t >= w.start && t <= w.end)) frames.push(at(l, t))
return pct(frames, SPEECH_Q)
}
/** the nearest time to `t` (within NEAR, never past `limit` on the clip's inside) that is a gap: 40 ms around it at
* least GAP dB under the speech level and inside no word */
/** the level under which a take is quiet enough to cut in: GAP under the speech, or near the take's own floor */
export const quietUnder = (l: Levels, ref: number) => Math.min(ref - GAP_LEAST, Math.max(ref - GAP, pct(l.db, FLOOR_Q) + GAP_FLOOR))
export function nearestGap(l: Levels, t: number, ref: number, words: Word[], inside: 1 | -1, limit: number): number | null {
const under = quietUnder(l, ref)
const quiet = (c: number) => (inside === 1 ? c <= limit : c >= limit) && peak(l, c - 0.02, c + 0.02) <= under && !words.some((w) => c > w.start - 0.01 && c < w.end + 0.01)
for (let d = 0; d <= NEAR + 1e-9; d += 0.01) {
for (const s of d ? [-1, 1] : [1]) {
const c = t + s * d
if (!quiet(c)) continue
// the middle of the gap it's in (a cut at a gap's edge takes a breath or a consonant with it), kept near t
let a = c
let b = c
while (a - 0.01 >= t - NEAR && quiet(a - 0.01)) a -= 0.01
while (b + 0.01 <= t + NEAR && quiet(b + 0.01)) b += 0.01
return Math.round(((a + b) / 2) * 100) / 100
}
}
return null
}
/** how close (s) a cut is to a boundary between two words that run together to count as on it (word timings are good
* to about 30 ms) */
const SEAM = 0.03
/** boundaries between words with no pause (under 80 ms) between them */
export function seams(words: Word[]): { at: number; before: string; after: string }[] {
const out: { at: number; before: string; after: string }[] = []
for (let i = 1; i < words.length; i++) {
const a = words[i - 1]
const b = words[i]
if (b.start - a.end < 0.08) out.push({ at: Math.round(((a.end + b.start) / 2) * 1000) / 1000, before: a.text, after: b.text })
}
return out
}
/** a voice clip's in and out: inside a word, or on sound */
export function editPoints(c: Clip, fps: number, words: Word[], l: Levels): Finding[] {
const out: Finding[] = []
const dur = (c.to - c.from) / fps
const tin = c.at
const tout = c.at + dur
const ref = speechLevel(l, tin, tout, words)
const name = path.basename(c.src)
for (const [edge, t, cutAt, inside] of [["in", tin, c.from / fps, 1], ["out", tout, c.to / fps, -1]] as const) {
const where = `the ${edge === "in" ? "start" : "end"} of the clip at ${secs(cutAt)} (${name} ${secs(t)})`
// speech that runs on with no pause still has its boundaries between words: a cut on one is tight, not a cut word
const seam = seams(words).find((x) => Math.abs(x.at - t) <= SEAM)
if (seam) {
const here = edge === "in" ? peak(l, t, t + 0.01) : peak(l, t - 0.01, t)
if (here >= ref - ON_SOUND)
out.push({ level: "warn", kind: "edit-on-sound", at: cutAt, says: `${where} is between “${seam.before}” and “${seam.after}” with no pause: a tight cut. Look at it on the waveform, or move it to a pause if one is near` })
continue
}
const word = words.find((w) => w.start + 0.02 < t && w.end - 0.02 > t)
const gap = nearestGap(l, t, ref, words, inside, inside === 1 ? tout - 0.1 : tin + 0.1)
const ms = (x: number) => `${x >= t ? "+" : ""}${Math.round((x - t) * 1000)} ms`
const bound = gap === null ? seams(words).filter((x) => Math.abs(x.at - t) <= NEAR && (inside === 1 ? x.at < tout - 0.1 : x.at > tin + 0.1)).sort((p, q) => Math.abs(p.at - t) - Math.abs(q.at - t))[0] : undefined
const move =
gap !== null
? `move it to ${secs(gap)} in ${name} (${ms(gap)}), the gap ${edge === "in" ? "before" : "after"} the words`
: bound
? `there's no pause within ${NEAR * 1000} ms; the nearest boundary between words is ${secs(bound.at)} in ${name} (${ms(bound.at)}, between “${bound.before}” and “${bound.after}”): cut there, or at another pause`
: `no pause or word boundary within ${NEAR * 1000} ms: cut at another pause, or take another line`
if (word) {
out.push({ level: "error", kind: "edit-in-word", at: cutAt, says: `${where} cuts “${word.text}” (${secs(word.start)}–${secs(word.end)}) in two: ${move}` })
continue
}
// the 10 ms just inside the cut: a word's onset a frame or two after an in point is a tight cut, not a cut one
const here = edge === "in" ? peak(l, t, t + 0.01) : peak(l, t - 0.01, t)
if (here >= Math.max(ref - ON_SOUND, pct(l.db, FLOOR_Q) + GAP_FLOOR + 2)) {
const near = words.reduce<Word | null>((b, w) => (Math.min(Math.abs(w.start - t), Math.abs(w.end - t)) < (b ? Math.min(Math.abs(b.start - t), Math.abs(b.end - t)) : 9) ? w : b), null)
out.push({ level: "error", kind: "edit-on-sound", at: cutAt, says: `${where} lands on sound ${Math.max(0, ref - here).toFixed(0)} dB under the speech${near ? `, ${Math.round(Math.min(Math.abs(near.start - t), Math.abs(near.end - t)) * 1000)} ms from “${near.text}”` : ""}: the word's ${edge === "in" ? "first sound" : "tail"} is cut. ${move[0].toUpperCase()}${move.slice(1)}` })
}
}
return out
}
export type Heard = { clip: Clip; kind: "voice" | "music" | "sfx"; level: number }
/** each voice line against the cut's others; effects and music against the voice */
export function balance(heard: Heard[], fps: number): Finding[] {
const out: Finding[] = []
const voice = heard.filter((h) => h.kind === "voice" && (h.clip.to - h.clip.from) / fps >= 0.4)
if (!voice.length) return out
const mid = pct(voice.map((h) => h.level), 0.5)
for (const h of voice) {
const d = h.level - mid
if (Math.abs(d) < LEVEL_WARN) continue
const g = (h.clip.gainDb ?? 0) - d
out.push({ level: Math.abs(d) >= LEVEL_ERROR ? "error" : "warn", kind: "level", at: h.clip.from / fps, says: `the line at ${secs(h.clip.from / fps)} (${path.basename(h.clip.src)} ${secs(h.clip.at)}) is ${Math.abs(d).toFixed(0)} dB ${d < 0 ? "under" : "over"} the cut's other lines${d < 0 ? ": too quiet to hear, though a transcriber still hears it" : ""}. Set its gainDb to ${g.toFixed(1)} (now ${(h.clip.gainDb ?? 0).toFixed(1)})` })
}
for (const h of heard.filter((x) => x.kind === "sfx")) {
const d = h.level - mid
if (d <= -SFX_UNDER)
out.push({ level: "error", kind: "effect-unheard", at: h.clip.from / fps, says: `the effect at ${secs(h.clip.from / fps)} (${path.basename(h.clip.src)}) peaks ${(-d).toFixed(0)} dB under the voice: no one hears it. Set its gainDb to about ${((h.clip.gainDb ?? 0) - d - 4).toFixed(1)} (4 dB under the voice), or cut it` })
}
for (const h of heard.filter((x) => x.kind === "music")) {
const d = h.level - mid
if (d < -MUSIC_LOST) out.push({ level: "warn", kind: "music", at: h.clip.from / fps, says: `the music (${path.basename(h.clip.src)}) sits ${(-d).toFixed(0)} dB under the voice: it's barely there. A bed under speech sits 12 to 20 dB under: gainDb about ${((h.clip.gainDb ?? 0) - d - 16).toFixed(1)}` })
else if (d > -MUSIC_FIGHTS) out.push({ level: "warn", kind: "music", at: h.clip.from / fps, says: `the music (${path.basename(h.clip.src)}) is within ${MUSIC_FIGHTS} dB of the voice: it fights the words. gainDb about ${((h.clip.gainDb ?? 0) - d - 16).toFixed(1)}` })
}
return out
}
/** the take a manifest names, on this box: its own path, or the part after a farm job's work/ under the project */
export function onBox(src: string, roots: string[]): string | null {
if (existsSync(src)) return src
const rel = src.includes("/work/") ? src.slice(src.lastIndexOf("/work/") + 6) : src.replace(/^\/+/, "")
for (const r of roots) {
const p = path.resolve(r, rel)
if (existsSync(p)) return p
}
return null
}
const wordsOf = (file: string) => `${file.slice(0, file.length - path.extname(file).length)}.words.json`
async function takeWords(file: string): Promise<Word[]> {
for (const p of [wordsOf(file), `${file}.words.json`]) {
if (existsSync(p)) {
const raw = JSON.parse(readFileSync(p, "utf8")) as ({ text: string; start_ms: number; end_ms: number } | Word)[] | { words: { text: string; start_ms: number; end_ms: number }[] }
const list = Array.isArray(raw) ? raw : raw.words
return list.map((w) => ("start_ms" in w ? { text: w.text, start: w.start_ms / 1000, end: w.end_ms / 1000 } : w))
}
}
const heard = await hear(file)
writeFileSync(wordsOf(file), `${JSON.stringify(heard.map((w) => ({ text: w.text, start_ms: Math.round(w.start * 1000), end_ms: Math.round(w.end * 1000) })))}\n`)
return heard
}
/** a take's level every 10 ms over [a, b] */
function takeLevels(file: string, a: number, b: number): Levels {
const start = Math.max(0, a)
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-sound-"))
try {
const raw = path.join(dir, "a.raw")
const r = spawnSync("ffmpeg", ["-v", "error", "-y", "-ss", String(start), "-t", String(Math.max(0.05, b - start)), "-i", file, "-vn", "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", "-f", "s16le", raw], { encoding: "utf8" })
if (r.status !== 0 || !existsSync(raw)) return { start, db: [] }
const buf = readFileSync(raw)
return { start, db: levels(new Int16Array(buf.buffer, buf.byteOffset, Math.floor(buf.length / 2))) }
} finally {
rmSync(dir, { recursive: true, force: true })
}
}
function flag(args: string[], name: string): string | undefined {
const i = args.indexOf(name)
return i >= 0 ? args[i + 1] : undefined
}
const stem = (v: string) => v.slice(0, v.length - path.extname(v).length)
/** the render's manifest: --manifest, else VIDEO.render.json (what raea cloud writes), else VIDEO.manifest.json */
export const manifestFor = (video: string, given?: string) => given ?? [`${stem(video)}.render.json`, `${stem(video)}.manifest.json`].find(existsSync) ?? `${stem(video)}.render.json`
export async function check(video: string, manifestPath: string, roots: string[]): Promise<{ findings: Finding[]; voice: number }> {
const m = JSON.parse(readFileSync(manifestPath, "utf8")) as Manifest
const fps = m.sounds?.fps ?? m.fps ?? 30
const found: Finding[] = []
const length = m.length ?? 0
const frames = m.frames?.length ?? 0
if (length > 1 && frames < length * 0.9)
found.push({ level: "error", kind: "manifest", at: null, says: `${path.basename(manifestPath)} holds ${frames} of the cut's ${length} frames, so its edit can't be checked: render the cut again (a render on raea cloud's GPUs before 11-29 kept frame 0's alone)` })
const clips = m.sounds?.clips ?? []
const heard: Heard[] = []
let voice = 0
for (const c of clips) {
const kind = busOf(c)
const file = onBox(c.src, roots)
if (!file) {
found.push({ level: "warn", kind: "manifest", at: c.from / fps, says: `${c.src} isn't on this box: its clip at ${secs(c.from / fps)} isn't checked` })
continue
}
const dur = (c.to - c.from) / fps
if (kind === "voice") {
voice++
const words = await takeWords(file)
const l = takeLevels(file, c.at - NEAR - 0.1, c.at + dur + NEAR + 0.1)
found.push(...editPoints(c, fps, words, l))
heard.push({ clip: c, kind, level: speechLevel(l, c.at, c.at + dur, words) + (c.gainDb ?? 0) })
} else {
const l = takeLevels(file, c.at, c.at + Math.min(dur, kind === "sfx" ? 2 : 20))
const level = kind === "sfx" ? pct(l.db, 0.98) : pct(l.db.filter((x) => x > -70), 0.5)
heard.push({ clip: c, kind, level: level + (c.gainDb ?? 0) })
}
}
found.push(...balance(heard, fps))
return { findings: found.sort((a, b) => (a.at ?? -1) - (b.at ?? -1)), voice }
}
export async function main(args: string[]): Promise<number> {
const a = args[0] === "check" ? args.slice(1) : args
const video = a.find((x, i) => !x.startsWith("-") && !["--manifest", "-o"].includes(a[i - 1] ?? ""))
if (!video || !existsSync(video)) {
console.error("usage: raea sound check VIDEO [--manifest RENDER.json] [-o REPORT.json] (edit points inside words or on sound, lines too quiet to hear, effects no one hears)")
return 2
}
const man = manifestFor(video, flag(a, "--manifest"))
if (!existsSync(man)) {
console.error(`raea sound check: no manifest for ${path.basename(video)} (${path.basename(man)}): render it with --manifest, or on raea cloud, which writes VIDEO.render.json`)
return 2
}
// the project the takes are under: here, and each folder above the video up to here
const roots = [process.cwd()]
for (let d = path.dirname(path.resolve(video)); d.startsWith(process.cwd()) && d !== process.cwd(); d = path.dirname(d)) roots.push(d)
const { findings, voice } = await check(video, man, roots)
for (const x of findings) console.log(`${x.level === "error" ? "ERROR" : "WARN "} ${x.at === null ? "" : `${x.at.toFixed(2)} s `}${x.says}`)
const errors = findings.filter((x) => x.level === "error").length
const report = flag(a, "-o") ?? `${stem(video)}.sound-check.json`
writeFileSync(report, `${JSON.stringify({ object: "sound.check", video, manifest: man, voice_clips: voice, passed: errors === 0, errors, warnings: findings.length - errors, findings }, null, 1)}\n`)
console.log(`${errors ? "FAILED" : "PASSED"} ${path.basename(video)}: ${voice} voice clips, ${errors} errors, ${findings.length - errors} warnings; ${path.basename(report)}`)
return errors ? 1 : 0
}
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
const a = process.argv.slice(2)
main(a[0] === "sound" ? a.slice(1) : a).then(
(c) => process.exit(c),
(e) => (console.error(`raea sound: ${(e as Error).message}`), process.exit(1)),
)
}
+19 -1
View File
@@ -45,7 +45,17 @@ class FakeGpu:
if video:
# the run as one H.264 video, as raea render --at FRAMES -o run.mp4 writes it
run(["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi", "-i", "color=c=gray:s=16x16:r=30", "-frames:v", str(len(frames)), "-c:v", "libx264", "-pix_fmt", "yuv420p", f"{dest}/run-{first:05d}.mp4"])
return {"code": 0, "out": "", "s": 12 + 0.5 * len(frames), "frames": len(frames), "ms": 500.0}
# and its manifest, as raea writes one for --at's frames: those frames, and each sound cut to them (a clip's
# `at` is its source time at the run's first frame). One voice clip over frames 0-39, another from 40
a, z = frames[0], frames[-1] + 1
clips = []
if a < 40:
clips.append({"key": "n3", "from": a, "to": min(z, 40), "src": "/w/media/take.mov", "at": 1.0 + a / 30, "gainDb": 0.0, "bus": "voice", **({"fadeIn": 0.012} if a == 0 else {})})
if z > 40:
f = max(a, 40)
clips.append({"key": "n8", "from": f, "to": z, "src": "/w/media/take.mov", "at": 9.0 + (f - 40) / 30, "gainDb": -2.0, "bus": "voice", **({"fadeOut": 0.012} if z == self.length else {})})
man = {"width": 1920, "height": 1080, "fps": 30, "length": self.length, "frames": [{"frame": f, "videos": [], "text": [{"text": f"t{f}"}]} for f in frames], "findings": [], "sounds": {"fps": 30, "clips": clips, "notes": [], "lines": []}}
return {"code": 0, "out": "", "s": 12 + 0.5 * len(frames), "frames": len(frames), "ms": 500.0, "manifest": man}
for f in frames:
if f >= first:
self.png(f"{dest}/frame-{f:05d}.png")
@@ -104,6 +114,14 @@ assert code == 0, lines
assert all("--manifest" not in a and "--quality" in a for a in m.args), m.args
assert json.load(open(os.path.join(root, "jobs", "jm", "work", "out", "a.render.json")))["length"] == 60
ok("a render's own --manifest isn't passed to the GPUs (the probe would lose the length), and is written at the end")
# 11-29 (Dutch): the manifest written was frame 0's alone, so a cut's edit (every clip, where it starts in its source) was
# lost and nothing could check its edit points. It's the runs' own manifests joined: every frame, each clip whole
man = json.load(open(os.path.join(root, "jobs", "jm", "work", "out", "a.render.json")))
assert [f["frame"] for f in man["frames"]] == list(range(60)), [f["frame"] for f in man["frames"]][:12]
clips = sorted(man["sounds"]["clips"], key=lambda c: c["from"])
assert [(c["key"], c["from"], c["to"]) for c in clips] == [("n3", 0, 40), ("n8", 40, 60)], clips
assert abs(clips[0]["at"] - 1.0) < 1e-6 and abs(clips[1]["at"] - 9.0) < 1e-6 and clips[0].get("fadeIn") == 0.012 and clips[1].get("fadeOut") == 0.012, clips
ok("a split render's manifest is its runs' joined: all 60 frames, and each clip whole with its source time")
lines.clear()
long = FakeGpu(root, length=1000)
+1
View File
@@ -0,0 +1 @@
{"a": {"w": 540, "h": 960, "grid": {"cols": 27, "rows": 48, "people": ["222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222456542222222222222", "222222246777763222222222222", "222222267777776322222222222", "222222277777777522222222222", "222222267777777732222222222", "222222267777777752222222222", "222222267777777773222222222", "222222247777777775222222222", "222222224677777777322222222", "222222222677777777522222222", "222223322677777777632222222", "222323323777777777732222222", "225533324777777777752222222", "224653224777777777763222222", "222554325777777777774222222", "222454435777777777776222222", "222444334777777777776222222", "222433333567777777777322222", "222223323445677777777422222", "222222322333345666666422222", "222222322333345666666422222", "222222232344445666664222222", "222222233344545556663222222", "222222223344444555553222222", "222222223334444444443222222", "222222222223332323332222222", "222222222223332222232222222", "222222222333333222232222222", "222222222333333222332222222", "222222222223322222322222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222"]}, "things": [[26.2, 134.5, 409.7, 600.0, "person", 0.887], [422.1, 49.1, 117.8, 310.0, "person", 0.87], [96.8, 73.6, 26.0, 77.0, "person", 0.752], [318.6, 59.3, 34.7, 64.6, "person", 0.682], [0.2, 95.0, 29.7, 92.3, "person", 0.575], [384.2, 56.3, 49.6, 71.9, "person", 0.566], [148.7, 94.7, 25.4, 35.7, "person", 0.49], [202.9, 65.2, 35.5, 71.9, "person", 0.479], [421.5, 57.1, 55.3, 213.8, "person", 0.377], [1.3, 65.8, 24.1, 46.5, "person", 0.357], [176.0, 878.0, 165.0, 76.0, "text", 0.978], [362.0, 844.0, 149.0, 57.0, "text", 0.94], [179.0, 816.0, 182.0, 65.0, "text", 0.978], [366.0, 776.0, 171.0, 62.0, "text", 0.987], [183.0, 742.0, 191.0, 80.0, "text", 0.986], [180.0, 677.0, 180.0, 35.0, "text", 0.993], [181.0, 611.0, 182.0, 36.0, "text", 0.99], [154.0, 573.0, 238.0, 25.0, "text", 0.991], [146.0, 529.0, 258.0, 25.0, "text", 0.989]], "faces": [[131.1, 174.9, 82.5, 143.1, "face", 0.878], [332.9, 60.6, 12.0, 15.0, "face", 0.788], [435.5, 67.1, 20.6, 23.9, "face", 0.711], [421.1, 61.4, 11.2, 13.5, "face", 0.678]]}, "b": {"w": 540, "h": 960, "grid": {"cols": 27, "rows": 48, "people": ["222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222234332222222222", "222222222223677764222222222", "222222222225777777322222222", "222222222227777777622222222", "222222222237777777732222222", "222222222227777777752222222", "222222222226777777762222222", "222222222225777777773222222", "222222222225777777775222222", "222222222456777777776322222", "222222224777777777777622222", "222222236667777777777732222", "222222256667777777777752222", "222222366666677777777762222", "222222366666677777777762222", "222222456666777777777762222", "222222466666777777777762222", "222223566666777777777763222", "222223566667777777777653222", "222223466667777777777543222", "222223356667777777777432222", "222223335666777777776332222", "222222335666666666764222222", "222222356556556554543222222", "222222365555444333332222222", "222222354443333333222222222", "222222343333222222222222222", "222222343322222222222222222", "222222333222222222222222222", "222222232222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222"]}, "things": [[112.8, 117.2, 356.1, 835.9, "person", 0.867], [145.0, 677.0, 252.0, 37.0, "text", 0.994]], "faces": [[216.5, 193.3, 78.6, 128.6, "face", 0.902], [138.4, 362.6, 54.1, 79.0, "face", 0.739]]}, "c": {"w": 540, "h": 960, "grid": {"cols": 27, "rows": 48, "people": ["222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222332222222222", "222222222222225664222222222", "222222222222247777322222222", "222222222222257777522222222", "222222222222367777522222222", "222222222223677777522222222", "222222222236777777622222222", "222222222367777777622222222", "222222222577777777733Line truncated
+40
View File
@@ -0,0 +1,40 @@
// Text placement (server/place.ts) on three frames of street interviews, read by the farm's scene models
// (deploy/modal/farm_scene.py; the fixture holds only their boxes and grids): node test/place.ts
// 11-29 (Dutch): a caption laid over the dog the shot is about, a checklist on a woman's lap, beside a sign that is the
// ad's own hook
import assert from "node:assert/strict"
import { readFileSync } from "node:fs"
import { placeReport, textOver } from "../server/place.ts"
const ok = (m: string) => console.log(`ok ${m}`)
const sc = JSON.parse(readFileSync(new URL("./fixtures/scenes-interview.json", import.meta.url), "utf8"))
const t = (text: string, x: number, y: number, w: number, h: number) => ({ text, box: [x, y, w, h], ink: [x + 10, y + 6, w - 20, h - 12], opacity: 1, size: 48 })
const man = (texts: unknown[]) => ({ width: 1080, height: 1920, fps: 30, frames: [{ frame: 0, text: texts }] })
// c: a woman sitting with her dog; the caption on the dog, the hook over the crowd behind her
const c = textOver(man([t("$1,000 for one vet visit?", 116, 236, 848, 112), t("He hurt his little", 290, 1335, 630, 90)]), [sc.c], 1)
assert.equal(c.length, 1, JSON.stringify(c))
assert.equal(c[0].level, "error")
assert.match(c[0].says, /“He hurt his little” covers a dog/)
const top = Number(/top (\d+) px/.exec(c[0].says)?.[1])
assert.ok(top >= 1380, `moved below the dog, not ${top}`)
ok("a caption over the dog is an error, moved to the clear ground under it; the hook over passers-by is fine")
// a: a checklist on a woman's lap, a sign under her, a man standing behind: no clear place for a block that size
const a = textOver(man([t("✓ 24/7 virtual vet care", 256, 1044, 568, 80), t("✓ Price-matched Rx", 280, 1130, 520, 76), t("✓ Free delivery", 336, 1214, 410, 76)]), [sc.a], 1)
assert.equal(a.length, 1, "the checklist's three lines are one block")
assert.match(a[0].says, /and the 2 lines under it\) covers a person in the shot/)
assert.match(a[0].says, /no place of its size is clear/)
ok("a checklist on a person is said once for its block, and that no place its size is clear")
// the clearest places for a caption in a: never on the sign, which is the ad's hook
const pa = placeReport("a.jpg", [sc.a], [840, 110])
assert.ok(pa.places.length >= 2)
assert.ok(!pa.places[0].covers.includes("words in the shot (a sign)"), JSON.stringify(pa.places[0]))
assert.ok(pa.places[0].top < 400, JSON.stringify(pa.places[0]))
ok("raea frames place keeps a caption off the sign in the shot")
// b: a woman filling the frame; a caption over her coat is at most a warning
const b = textOver(man([t("Did you know you", 272, 1344, 536, 88)]), [sc.b], 1)
assert.ok(b.every((x) => x.level === "warn"), JSON.stringify(b))
ok("a caption over a person who fills the frame is at most a warning")
+80
View File
@@ -0,0 +1,80 @@
// `raea sound check`'s measures (server/sound.ts), on made-up takes: node test/sound.ts
// 11-29 (Dutch): words cut in two at a clip's edge, a guest's line 15 dB under the host's, effects 18 dB under the voice
import assert from "node:assert/strict"
import { balance, busOf, editPoints, nearestGap, type Clip, type Heard, type Levels } from "../server/sound.ts"
const ok = (m: string) => console.log(`ok ${m}`)
// a take: words at 1.00-1.40, 1.50-1.90 ("very" "loud") and 2.40-2.80 ("next"); speech at -20 dB, the street at -50
const words = [
{ text: "very", start: 1.0, end: 1.4 },
{ text: "loud", start: 1.5, end: 1.9 },
{ text: "next", start: 2.4, end: 2.8 },
]
const db: number[] = []
for (let t = 0; t < 4; t += 0.01) db.push(words.some((w) => t >= w.start - 0.005 && t <= w.end + 0.005) ? -20 : -50)
const take: Levels = { start: 0, db }
const fps = 30
const clip = (at: number, dur: number, extra: Partial<Clip> = {}): Clip => ({ key: "n1", from: 30, to: 30 + Math.round(dur * fps), src: "/w/work/media/raw/take.mov", at, gainDb: 0, bus: "voice", ...extra })
// cut in the gaps: 0.90 to 2.10 (both edges in silence)
assert.deepEqual(editPoints(clip(0.9, 1.2), fps, words, take), [])
ok("a clip cut in the gaps around its words passes")
// out at 1.70: inside "loud"
const inWord = editPoints(clip(0.9, 0.8), fps, words, take)
assert.equal(inWord.length, 1)
assert.equal(inWord[0].kind, "edit-in-word")
assert.match(inWord[0].says, /“loud”/)
assert.match(inWord[0].says, /move it to 1\.4\d s/)
ok("an out point inside a word is an error, with the gap before it to move to")
// in at 1.01: a hair past the start of "very" (inside the 20 ms grace), so it's on sound, not inside the word
const onSound = editPoints(clip(1.01, 1.0), fps, words, take)
assert.equal(onSound[0]?.kind, "edit-on-sound", JSON.stringify(onSound))
assert.match(onSound[0].says, /first sound/)
ok("an in point on a word's first sound is an error")
// "loud" and "next" run together with no pause: a cut on their boundary is tight (a warning), not a cut word
const run = [{ text: "say", start: 1.0, end: 1.4 }, { text: "so", start: 1.42, end: 1.7 }, { text: "then", start: 1.72, end: 2.0 }]
const runDb: number[] = []
for (let t = 0; t < 4; t += 0.01) runDb.push(t >= 0.995 && t <= 2.005 ? -20 : -50)
const tight = editPoints(clip(0.9, 0.81), fps, run, { start: 0, db: runDb })
assert.deepEqual(tight.map((x) => [x.level, x.kind]), [["warn", "edit-on-sound"]], JSON.stringify(tight))
assert.match(tight[0].says, /between “so” and “then”/)
const cutSo = editPoints(clip(0.9, 0.65), fps, run, { start: 0, db: runDb })
assert.equal(cutSo[0]?.level, "error")
assert.match(cutSo[0].says, /no pause within 400 ms; the nearest boundary between words is 1\.71 s/)
ok("a cut on the boundary of words that run together is a warning; inside one, the nearest boundary is said")
assert.equal(nearestGap(take, 1.7, -20, words, -1, 1.0), 1.45)
assert.equal(nearestGap({ start: 0, db: db.map(() => -20) }, 1.7, -20, [], -1, 0), null)
ok("the nearest gap is found, and a take with none says so")
// levels: three lines at -14, one guest at -29 (15 dB under: Gigi's hook B); an effect at -32; music at -50
const line = (from: number, level: number, extra: Partial<Clip> = {}): Heard => ({ clip: { ...clip(1, 2), from, to: from + 60, ...extra }, kind: "voice", level })
const heard: Heard[] = [
line(0, -14),
line(60, -29, { src: "/w/work/media/raw/guest.mov" }),
line(120, -15),
line(180, -13),
{ clip: { ...clip(0, 1), from: 90, to: 120, src: "/w/work/media/elevenlabs/sfx_pop.mp3", bus: "sfx", gainDb: -14 }, kind: "sfx", level: -32 },
{ clip: { ...clip(0, 20), from: 0, to: 600, src: "/w/work/media/elevenlabs/music.mp3", bus: "music", gainDb: -20 }, kind: "music", level: -50 },
]
const b = balance(heard, fps)
const quiet = b.find((x) => x.kind === "level")
assert.equal(quiet?.level, "error")
assert.match(quiet!.says, /guest\.mov/)
assert.match(quiet!.says, /15 dB under/)
assert.match(quiet!.says, /gainDb to 15\.0/)
assert.equal(b.filter((x) => x.kind === "level").length, 1, "the lines within 4 dB of each other pass")
const sfx = b.find((x) => x.kind === "effect-unheard")
assert.equal(sfx?.level, "error")
assert.match(sfx!.says, /18 dB under the voice/)
assert.equal(b.find((x) => x.kind === "music")?.level, "warn")
ok("a line 15 dB under the others is an error with the gain that evens it; an effect 18 dB under is unheard; buried music is said")
assert.equal(busOf({ ...clip(0, 1), bus: undefined, src: "/x/media/elevenlabs/sfx_tap.mp3" }), "sfx")
assert.equal(busOf({ ...clip(0, 1), bus: undefined, src: "/x/media/raw/Interview1.MOV" }), "voice")
assert.equal(busOf({ ...clip(0, 1), bus: "music", src: "/x/a.mp3" }), "music")
ok("a clip's kind from its bus, or its file's name when it has none")
+15 -7
View File
@@ -4,6 +4,7 @@
// frame draws runs at the next frame. `new Image()` loads: setting its src fires load (and onload) on the next microtask,
// so a preload resolves, and by then naturalWidth and naturalHeight are the picture's size (#253): a data: URL's from its
// header, a file's or URL's from the host (native asset.load, which finds staticFile's /media/ paths as <Img> does).
// currentSrc is then the file the host found, which a canvas's drawImage draws from (#260).
// width and height are the ones given (the constructor's, or set) else the natural size, as a browser has them. A file
// the host can't find fires error (and onerror) instead. Under plain bun, with no host, a file's size stays 0.
@@ -59,13 +60,14 @@ export function frameCallbacks(f: number, fps: number): void {
type Listener = (e: { type: string; target: unknown; currentTarget: unknown }) => void;
/** A picture's size: a data: URL's from its header, anything else from the host (asset.load); null when it has none
* (no host, or a format the header doesn't say). Throws the host's error for a file that isn't there. */
function pictureSize(src: string): [number, number] | null {
if (src.startsWith("data:")) return sniffSize(src);
if (src.startsWith("blob:") || !hasNative()) return null;
/** A picture's size, and the file the host found for it: a data: URL's size from its header, anything else from the host
* (asset.load); no size when it has none (no host, or a format the header doesn't say). Throws the host's error for a
* file that isn't there. */
function picture(src: string): { size: [number, number] | null; file?: string } {
if (src.startsWith("data:")) return { size: sniffSize(src) };
if (src.startsWith("blob:") || !hasNative()) return { size: null };
const got = native("asset.load", { path: src });
return got && typeof got.width === "number" && typeof got.height === "number" ? [got.width, got.height] : null;
return { size: got && typeof got.width === "number" && typeof got.height === "number" ? [got.width, got.height] : null, file: typeof got?.path === "string" ? got.path : undefined };
}
/** A preloadable image: its src set, load fires, with the picture's size. */
@@ -75,6 +77,10 @@ class FrameImage {
complete = true;
naturalWidth = 0;
naturalHeight = 0;
/** the picture as it loaded: the file the host found for the src (staticFile's /media/x is the project's media/x),
* which is what a canvas's drawImage draws from (#260: read back off the page, a canvas has no project folder to
* find /media/ in, and the picture drew nothing); "" until it loads, as in a browser */
currentSrc = "";
alt = "";
crossOrigin: string | null = null;
decoding = "auto";
@@ -116,14 +122,16 @@ class FrameImage {
this.complete = false;
this.naturalWidth = 0;
this.naturalHeight = 0;
this.currentSrc = "";
const load = ++this.#loads;
queueMicrotask(() => {
// a src set again before this one loaded: only the last one's load fires, as in a browser
if (load !== this.#loads) return;
let type = "load";
try {
const size = pictureSize(src);
const { size, file } = picture(src);
if (size) [this.naturalWidth, this.naturalHeight] = size;
this.currentSrc = file ?? src;
} catch (err) {
type = "error";
console.warn(`new Image(): ${src} didn't load: ${err instanceof Error ? err.message : String(err)}`);
+1 -1
Submodule skills updated: ae81d0fdb3...8efd329239.
+5 -3
View File
@@ -143,11 +143,13 @@ pub(crate) fn page_options() -> usvg::Options<'static> {
/// Where a video's or a picture's src is as a file, for drawing it on a canvas (`videos`).
static VIDEO_PATHS: std::sync::RwLock<Option<fn(&str) -> Option<std::path::PathBuf>>> = std::sync::RwLock::new(None);
/// A src as a file: by the host's roots (`videos`), else as a path (a file:// URL's too).
/// A src as a file: by the host's roots (`videos`), else as a path (a file:// URL's too); a src that is a file as it
/// stands (a loaded Image's currentSrc, the file its host found: #260) is that file whatever the roots make of it.
fn media_file(src: &str) -> Option<std::path::PathBuf> {
let plain = std::path::PathBuf::from(src.strip_prefix("file://").unwrap_or(src));
match *VIDEO_PATHS.read().unwrap() {
Some(f) => f(src),
None => Some(std::path::PathBuf::from(src.strip_prefix("file://").unwrap_or(src))),
Some(f) => f(src).filter(|p| p.exists() || !(plain.is_absolute() && plain.is_file())).or(Some(plain)),
None => Some(plain),
}
}
+3
View File
@@ -14,4 +14,7 @@ blitz-paint = { version = "=0.3.0-beta.4", default-features = false }
# every call's arguments hashed, so the same print draws the same picture
rustc-hash = "2"
vello = { version = "=0.11.0", default-features = false, features = ["wgpu"] }
# a bitmap emoji's strike and its PNG, for the grey ones Vello's glyph run skips (emoji.rs, #262): Vello's own versions
skrifa = "0.44.0"
png = "0.18.1"
wgpu = "=30.0.1"
+136
View File
@@ -0,0 +1,136 @@
//! Bitmap emoji whose PNG Vello doesn't draw: grey ones. Apple Color Emoji keeps 52 of its glyphs as grey + alpha PNGs
//! (💬 and 🗨 among them), and Vello's glyph run asks png for RGBA with a transformation that adds alpha and leaves
//! grey as it is, logs "Unsupported `output_color_type`" and skips the glyph: its space was kept and nothing drawn
//! (#262). Those glyphs are taken out of the run and drawn here, as images placed the way Vello places a bitmap glyph.
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::Arc;
use anyrender::Glyph;
use skrifa::bitmap::{BitmapData, BitmapFormat, Origin};
use skrifa::raw::TableProvider;
use skrifa::{GlyphId, MetadataProvider, instance::Size};
use vello::kurbo::{Affine, Vec2};
use vello::peniko::{Blob, FontData, ImageAlphaType, ImageData, ImageFormat};
thread_local! {
/// a font (its data's id and index) with bitmap strikes: its units per em, and whether it's Apple Color Emoji; None for a font with none
static FONTS: RefCell<HashMap<(u64, u32), Option<(f32, bool)>>> = RefCell::new(HashMap::new());
/// a glyph's picture once decoded (font, glyph, strike), so the same image is drawn each frame
static PICTURES: RefCell<HashMap<(u64, u32, u32, u32), Option<ImageData>>> = RefCell::new(HashMap::new());
}
/// A PNG's colour type Vello's glyph run draws: truecolour, with alpha or without (2 and 6); grey and palette ones it skips.
fn vello_draws(png: &[u8]) -> bool {
png.get(25).is_none_or(|t| matches!(t, 2 | 6))
}
/// A PNG as RGBA8, grey and palette ones expanded.
pub(crate) fn rgba(data: &[u8]) -> Option<(u32, u32, Vec<u8>)> {
let mut decoder = png::Decoder::new(std::io::Cursor::new(data));
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16 | png::Transformations::ALPHA);
let mut reader = decoder.read_info().ok()?;
let mut buf = vec![0; reader.output_buffer_size()?];
let info = reader.next_frame(&mut buf).ok()?;
buf.truncate(info.buffer_size());
if info.color_type == png::ColorType::Indexed {
return None;
}
// each pixel's samples as four: grey (1 or 2 samples) spread over the three colours, and alpha the last sample
// of an even count, opaque otherwise
let n = info.color_type.samples();
let mut px = Vec::with_capacity(buf.len() / n * 4);
for p in buf.chunks_exact(n) {
let a = if n % 2 == 0 { p[n - 1] } else { 255 };
px.extend_from_slice(&if n < 3 { [p[0], p[0], p[0], a] } else { [p[0], p[1], p[2], a] });
}
(px.len() as u64 == u64::from(info.width) * u64::from(info.height) * 4).then_some((info.width, info.height, px))
}
/// The glyphs of a run Vello would skip, each as its picture and where it goes in the run's space, and the rest of the
/// run for Vello; None when the run has none (every font without bitmaps, nearly every emoji).
pub(crate) fn skipped(font: &FontData, font_size: f32, glyph_transform: Option<Affine>, glyphs: impl Iterator<Item = Glyph> + Clone) -> Option<(Vec<Glyph>, Vec<(ImageData, Affine)>)> {
let key = (font.data.id(), font.index);
let known = FONTS.with_borrow(|f| f.get(&key).copied());
if known == Some(None) {
return None;
}
let face = skrifa::FontRef::from_index(font.data.as_ref(), font.index).ok()?;
let strikes = face.bitmap_strikes();
let (upem, apple) = match known {
Some(Some(k)) => k,
_ => {
let k = strikes.format().and_then(|format| {
let upem = f32::from(face.head().ok()?.units_per_em());
let apple = format == BitmapFormat::Sbix && face.localized_strings(skrifa::string::StringId::POSTSCRIPT_NAME).any(|n| n.chars().eq("AppleColorEmoji".chars()));
Some((upem, apple))
});
FONTS.with(|f| f.borrow_mut().insert(key, k));
k?
}
};
let png_of = |g: &Glyph| match strikes.glyph_for_size(Size::new(font_size), GlyphId::new(g.id)) {
Some(b) => match b.data {
BitmapData::Png(d) if !vello_draws(d) => Some((b, d)),
_ => None,
},
None => None,
};
if !glyphs.clone().any(|g| png_of(&g).is_some()) {
return None;
}
let (mut rest, mut ours) = (Vec::new(), Vec::new());
for g in glyphs {
let Some((b, data)) = png_of(&g) else {
rest.push(g);
continue;
};
let pic = PICTURES.with(|p| {
p.borrow_mut()
.entry((key.0, key.1, g.id, b.ppem_y.to_bits()))
.or_insert_with(|| rgba(data).filter(|&(w, h, _)| w == b.width && h == b.height).map(|(width, height, px)| ImageData { data: Blob::new(Arc::new(px)), format: ImageFormat::Rgba8, alpha_type: ImageAlphaType::Alpha, width, height }))
.clone()
});
// one png can't read is left out, as Vello leaves it
let Some(pic) = pic else { continue };
// Vello's placement of a bitmap glyph (scene.rs, after Skia's): Apple Color Emoji an eighth of the size down
let outer = if apple { Vec2::new(0.0, f64::from(font_size) / 8.0) } else { Vec2::new(f64::from(b.bearing_x * font_size / upem), -f64::from(b.bearing_y * font_size / upem)) };
let mut at = Affine::translate((f64::from(g.x), f64::from(g.y))) * Affine::translate(outer) * Affine::scale(f64::from(font_size / b.ppem_y)) * Affine::translate((f64::from(b.inner_bearing_x), -f64::from(b.inner_bearing_y)));
if matches!(b.placement_origin, Origin::BottomLeft) {
at *= Affine::translate((0.0, -f64::from(pic.height)));
}
if let Some(t) = glyph_transform {
at *= t;
}
ours.push((pic, at));
}
Some((rest, ours))
}
#[cfg(test)]
mod tests {
use super::*;
/// a 2 x 1 PNG of colour type `kind`, 8 bits a channel, its rows given unfiltered
fn png_of(kind: png::ColorType, row: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
let mut e = png::Encoder::new(&mut out, 2, 1);
e.set_color(kind);
e.set_depth(png::BitDepth::Eight);
e.write_header().unwrap().write_image_data(row).unwrap();
out
}
#[test]
fn a_grey_png_is_the_one_vello_skips_and_reads_as_rgba() {
// #262: 💬 in Apple Color Emoji is grey + alpha
let grey = png_of(png::ColorType::GrayscaleAlpha, &[200, 255, 10, 128]);
assert!(!vello_draws(&grey));
assert_eq!(rgba(&grey), Some((2, 1, vec![200, 200, 200, 255, 10, 10, 10, 128])));
let colour = png_of(png::ColorType::Rgba, &[1, 2, 3, 4, 5, 6, 7, 8]);
assert!(vello_draws(&colour) && vello_draws(&png_of(png::ColorType::Rgb, &[1, 2, 3, 4, 5, 6])));
assert_eq!(rgba(&colour), Some((2, 1, vec![1, 2, 3, 4, 5, 6, 7, 8])));
assert_eq!(rgba(&png_of(png::ColorType::Grayscale, &[7, 9])), Some((2, 1, vec![7, 7, 7, 255, 9, 9, 9, 255])));
}
}
+1
View File
@@ -7,6 +7,7 @@
//! The passes work as Chrome's do: on premultiplied, sRGB-encoded values (no linearising), blur radii scaled by the
//! layer's transform; edges are transparent (CSS's `EdgeMode::None`).
mod emoji;
mod painter;
mod passes;
mod premul;
+8
View File
@@ -387,6 +387,14 @@ impl PaintScene for Painter<'_> {
self.hash.write_u32(g.y.to_bits());
}
let (scene, at) = self.top();
// the bitmap emoji Vello skips (grey PNGs: 💬, #262) drawn here, the rest of the run by Vello
if let Some((rest, ours)) = crate::emoji::skipped(font, font_size, glyph_transform, glyphs.clone()) {
VelloScenePainter::new(scene).draw_glyphs(font, font_size, hint, normalized_coords, embolden, style, brush, brush_alpha, at * transform, glyph_transform, rest.into_iter());
for (pic, place) in &ours {
scene.draw_image(pic, at * transform * *place);
}
return;
}
VelloScenePainter::new(scene).draw_glyphs(font, font_size, hint, normalized_coords, embolden, style, brush, brush_alpha, at * transform, glyph_transform, glyphs);
}
+9 -5
View File
@@ -13,8 +13,12 @@ raea-sys-atlas = { path = "../atlas" }
parry3d = "0.31"
rayon = "1"
serde_json = "1"
# the process's one shared GPU device, and wgpu's ray queries on it (BK3)
raea-gpu-device = { path = "../../gpu/device" }
wgpu = "=30.0.1"
bytemuck = "1"
pollster = "0.4"
# the paths the light is traced along (BK3)
raea-sys-lighttrace = { path = "../lighttrace" }
# a model read on its own second UVs (own.rs): its meshes, and its base colour textures decoded
gltf = { version = "1.4", default-features = false, features = ["utils", "names"] }
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
[dev-dependencies]
# the panorama the atelier's run reads (own/tests.rs)
image = { version = "0.25", default-features = false, features = ["hdr"] }
+3 -2
View File
@@ -5,6 +5,7 @@
//! progress). Next: a clean map (BK4), and the bake in a composition (BK5).
// each texel's ray origin and the texels inside other geometry (BK2)
pub mod own;
pub mod texels;
// the light that bounces, traced on the GPU (BK3)
pub mod trace;
#[cfg(test)]
mod trace_tests;
+169
View File
@@ -0,0 +1,169 @@
//! A model traced on its own second UVs, a map a mesh (docs/bake.feature BK3): what lightbake.py lays out, so raea's
//! light is compared with Cycles' texel for texel. Every mesh of the .glb in world space with its materials (base
//! colour, its texture, less what's metal), and a mesh's texels at a side: those whose centre a triangle covers.
use gltf::mesh::util::ReadIndices;
use parry3d::glamx::{Mat4, Vec2, Vec3};
use std::collections::HashMap;
use std::ops::Range;
use parry3d::shape::TriMesh;
use rayon::prelude::*;
use crate::texels::starts;
use raea_sys_lighttrace::{Image, Surface};
pub struct Mesh {
pub name: String,
/// its triangles in Model::triangles
pub triangles: Range<usize>,
}
/// A .glb's meshes in the world, as World takes them, with each vertex's second UV.
#[derive(Default)]
pub struct Model {
pub positions: Vec<[f32; 3]>,
pub normals: Vec<[f32; 3]>,
pub uvs: Vec<[f32; 2]>,
pub second: Vec<[f32; 2]>,
pub triangles: Vec<[u32; 3]>,
pub surfaces: Vec<Surface>,
pub textures: Vec<Image>,
pub meshes: Vec<Mesh>,
}
/// A texel of a mesh's map whose centre a triangle covers.
pub struct At {
pub x: u32,
pub y: u32,
/// its point off the surface, the sides of its footprint and its open starts (texels::starts)
pub origin: [f32; 3],
pub sides: [[f32; 3]; 2],
pub open: u32,
/// the shading normal there (the vertices', interpolated), on the plane's side
pub normal: [f32; 3],
}
/// The model, its textures no longer a side than `most` (a bounce blurs the rest away).
pub fn read(glb: &[u8], most: u32) -> Result<Model, String> {
let g = gltf::Gltf::from_slice(glb).map_err(|e| e.to_string())?;
let blob = g.blob.clone().ok_or("a model without its binary: only a .glb is read")?;
let mut m = Model::default();
let mut images = HashMap::new();
let mut stack: Vec<(gltf::Node, Mat4)> = match g.default_scene().or(g.scenes().next()) {
Some(s) => s.nodes().map(|n| (n, Mat4::IDENTITY)).collect(),
None => return Err("a model without a scene".into()),
};
while let Some((node, up)) = stack.pop() {
let world = up * Mat4::from_cols_array_2d(&node.transform().matrix());
stack.extend(node.children().map(|c| (c, world)));
let Some(mesh) = node.mesh() else { continue };
let first = m.triangles.len();
for p in mesh.primitives() {
if p.mode() != gltf::mesh::Mode::Triangles {
continue;
}
primitive(&mut m, &p, world, &blob, &mut images, most)?;
}
m.meshes.push(Mesh { name: mesh.name().unwrap_or_default().to_string(), triangles: first..m.triangles.len() });
}
Ok(m)
}
fn primitive(m: &mut Model, p: &gltf::Primitive, world: Mat4, blob: &[u8], images: &mut HashMap<usize, u32>, most: u32) -> Result<(), String> {
let r = p.reader(|_| Some(blob));
let base = m.positions.len() as u32;
let turn = world.inverse().transpose();
m.positions.extend(r.read_positions().ok_or("a mesh without positions")?.map(|v| world.transform_point3(Vec3::from(v)).to_array()));
let n = m.positions.len() - base as usize;
match r.read_normals() {
Some(v) => m.normals.extend(v.map(|v| turn.transform_vector3(Vec3::from(v)).normalize_or_zero().to_array())),
None => m.normals.extend(vec![[0.0; 3]; n]),
}
let uv = |set: u32| r.read_tex_coords(set).map_or(vec![[0.0; 2]; n], |u| u.into_f32().collect());
let (first, second) = (uv(0), uv(1));
m.uvs.extend(first);
m.second.extend(second);
let index: Vec<u32> = match r.read_indices() {
Some(ReadIndices::U8(i)) => i.map(u32::from).collect(),
Some(ReadIndices::U16(i)) => i.map(u32::from).collect(),
Some(ReadIndices::U32(i)) => i.collect(),
None => (0..n as u32).collect(),
};
let pbr = p.material().pbr_metallic_roughness();
let [cr, cg, cb, _] = pbr.base_color_factor();
let texture = match pbr.base_color_texture() {
Some(t) => Some(texture(m, &t.texture().source(), blob, images, most)?),
None => None,
};
let e = p.material().emissive_factor();
let surface = Surface { albedo: [cr, cg, cb], emission: e, metallic: pbr.metallic_factor(), roughness: pbr.roughness_factor(), f0: 0.04, texture };
m.triangles.extend(index.chunks_exact(3).map(|t| [base + t[0], base + t[1], base + t[2]]));
m.surfaces.resize(m.triangles.len(), surface);
Ok(())
}
fn texture(m: &mut Model, image: &gltf::Image, blob: &[u8], images: &mut HashMap<usize, u32>, most: u32) -> Result<u32, String> {
if let Some(k) = images.get(&image.index()) {
return Ok(*k);
}
let gltf::image::Source::View { view, .. } = image.source() else { return Err("a texture outside the .glb".into()) };
let bytes = &blob[view.offset()..view.offset() + view.length()];
let full = image::load_from_memory(bytes).map_err(|e| format!("a texture: {e}"))?;
let small = if full.width().max(full.height()) > most { full.thumbnail(most, most) } else { full }.to_rgba8();
let rgba = small.pixels().map(|p| u32::from_le_bytes(p.0)).collect();
m.textures.push(Image { width: small.width(), height: small.height(), rgba });
let k = m.textures.len() as u32 - 1;
images.insert(image.index(), k);
Ok(k)
}
/// A mesh's texels on its second UVs at `side` by `side`, each once (the first triangle over its centre); `offset` as
/// Texels' own.
pub fn texels(m: &Model, mesh: &Mesh, world: &TriMesh, side: u32, offset: f32, whole: bool) -> Vec<At> {
let mut taken = vec![false; (side * side) as usize];
let mut out = vec![];
for tri in &m.triangles[mesh.triangles.clone()] {
let uv = tri.map(|v| m.second[v as usize].map(|c| c * side as f32));
let [pos, nor] = [&m.positions, &m.normals].map(|list| tri.map(|v| Vec3::from(list[v as usize])));
let cross = |a: [f32; 2], b: [f32; 2], c: [f32; 2]| (Vec2::from(b) - Vec2::from(a)).perp_dot(Vec2::from(c) - Vec2::from(a));
let area = cross(uv[0], uv[1], uv[2]);
let plane = (pos[1] - pos[0]).cross(pos[2] - pos[0]);
if area.abs() < 1e-9 || plane.length_squared() < 1e-24 {
continue;
}
// a texel's sides on this triangle, metres
let (e1, e2) = (Vec2::from(uv[1]) - Vec2::from(uv[0]), Vec2::from(uv[2]) - Vec2::from(uv[0]));
let sides = [((pos[1] - pos[0]) * e2.y - (pos[2] - pos[0]) * e1.y) / area, ((pos[2] - pos[0]) * e1.x - (pos[1] - pos[0]) * e2.x) / area];
let span = |k: usize| {
let (lo, hi) = uv.iter().fold((f32::MAX, f32::MIN), |(l, h), q| (l.min(q[k]), h.max(q[k])));
((lo - 0.5).ceil().max(0.0) as u32, ((hi - 0.5).floor() as i64).clamp(-1, side as i64 - 1))
};
let ((x0, x1), (y0, y1)) = (span(0), span(1));
for y in y0 as i64..=y1 {
for x in x0 as i64..=x1 {
let c = [x as f32 + 0.5, y as f32 + 0.5];
let w = [cross(uv[1], uv[2], c) / area, cross(uv[2], uv[0], c) / area, cross(uv[0], uv[1], c) / area];
let at = (y as u32 * side + x as u32) as usize;
if w.iter().any(|&v| v < 0.0) || taken[at] {
continue;
}
taken[at] = true;
let p = pos[0] * w[0] + pos[1] * w[1] + pos[2] * w[2];
let shade = (nor[0] * w[0] + nor[1] * w[1] + nor[2] * w[2]).normalize_or_zero();
let mut n = plane.normalize();
if n.dot(shade) < 0.0 {
n = -n;
}
out.push((At { x: x as u32, y: y as u32, origin: p.to_array(), sides: sides.map(|s| s.to_array()), open: 0, normal: if shade == Vec3::ZERO { n } else { shade }.to_array() }, n, pos));
}
}
}
out.into_par_iter().enumerate().map(|(k, (a, n, pos))| {
let (origin, open) = starts(world, pos, Vec3::from(a.origin), n, a.sides.map(Vec3::from), offset, k as u32, whole);
At { origin, open, ..a }
}).collect()
}
#[cfg(test)]
mod tests;
+148
View File
@@ -0,0 +1,148 @@
use super::*;
use crate::texels::tests::{cuboid, glb};
use raea_sys_lighttrace::{Settings, Sky, Starts, Sun, World, trace};
#[test]
fn a_model_reads_in_the_world_with_its_materials() {
let m = read(&glb(&[(cuboid([0.0; 3], [1.0; 3]), [0.0, 2.0, 0.0])]), 64).unwrap();
assert_eq!((m.meshes.len(), m.triangles.len(), m.surfaces.len()), (1, 12, 12));
assert!(m.positions.iter().all(|p| (2.0..=3.0).contains(&p[1])), "the node's translation");
// glTF's metallic and roughness are 1 when a material doesn't say; the rest under it has the dielectric's F0
assert_eq!(m.surfaces[0], Surface { albedo: [1.0; 3], metallic: 1.0, roughness: 1.0, f0: 0.04, ..Surface::default() });
}
#[test]
fn texels_lie_where_the_second_uvs_put_them() {
// a 2 m by 1 m wall standing at z = 3, facing +Z, over the left half of its map
let quad = [([0.0f32, 0.0, 3.0], [0.0f32, 1.0f32]), ([2.0, 0.0, 3.0], [0.5, 1.0]), ([2.0, 1.0, 3.0], [0.5, 0.5]), ([0.0, 1.0, 3.0], [0.0, 0.5])];
let m = Model {
positions: quad.iter().map(|q| q.0).collect(),
normals: vec![[0.0, 0.0, 1.0]; 4],
uvs: vec![[0.0; 2]; 4],
second: quad.iter().map(|q| q.1).collect(),
triangles: vec![[0, 1, 2], [0, 2, 3]],
surfaces: vec![Surface::default(); 2],
meshes: vec![Mesh { name: "wall".into(), triangles: 0..2 }],
..Model::default()
};
let world = parry3d::shape::TriMesh::new(m.positions.iter().map(|p| Vec3::from(*p)).collect(), m.triangles.clone()).unwrap();
let t = texels(&m, &m.meshes[0], &world, 16, 1e-4, false);
assert_eq!(t.len(), 8 * 8, "a quarter of 16 x 16, each once");
for a in &t {
let want = [(a.x as f32 + 0.5) / 8.0 * 2.0, 1.0 - (a.y as f32 + 0.5 - 8.0) / 8.0];
assert!((a.origin[0] - want[0]).abs() < 1e-2 && (a.origin[1] - want[1]).abs() < 1e-2 && (a.origin[2] - 3.0001).abs() < 1e-5, "{},{} at {:?}", a.x, a.y, a.origin);
assert_eq!(a.normal, [0.0, 0.0, 1.0]);
assert_eq!(a.sides, [[0.25, 0.0, 0.0], [0.0, -0.125, 0.0]], "a texel's sides");
}
}
fn number(name: &str, d: f32) -> f32 {
std::env::var(name).ok().and_then(|v| v.parse().ok()).unwrap_or(d)
}
/// lightbake.py's smooth: a 3 x 3 mean over the covered texels, `passes` times.
fn smooth(side: usize, map: &mut Vec<Option<[f32; 3]>>, passes: usize) {
for _ in 0..passes {
let from = map.clone();
for (i, out) in map.iter_mut().enumerate().filter(|(_, v)| v.is_some()) {
let (x, y) = ((i % side) as i32, (i / side) as i32);
let near: Vec<[f32; 3]> = (-1..=1).flat_map(|dy| (-1..=1).map(move |dx| (x + dx, y + dy))).filter(|&(a, b)| a >= 0 && b >= 0 && a < side as i32 && b < side as i32).filter_map(|(a, b)| from[b as usize * side + a as usize]).collect();
*out = Some(std::array::from_fn(|k| near.iter().map(|c| c[k]).sum::<f32>() / near.len() as f32));
}
}
}
/// The atelier's run (docs/bake.feature BK3): a model lightbake.py baked, traced on its own maps under the light its
/// .blend held, and each map against Cycles' (compare.rs's map_stops: the mean distance in stops and the signed one,
/// over the texels both cover, Cycles' clipped ones out). RAEA_BAKE_DIR holds set.glb, set.lightmaps.json and
/// lightmaps/, RAEA_BAKE_SKY the panorama; _RUNS ("512x4": samples x bounces, each in turn), _STRENGTH, _ROTATION, _SMOOTH, _SUN ("x,y,z,r,g,b")
/// _ONLY (mesh names), _OFFSET (metres), _WHOLE (a texel's buried part counts, as in Cycles), _LAMBERT (no glossy layers, for a diffuse-only reference), _DUMP (a folder: each map's luminances, raea's and Cycles', and the texel's place, as f32 threes)
/// and _OUT (each run's table, OUT-RUN.json).
#[test]
#[ignore]
fn against_cycles() {
let dir = std::path::PathBuf::from(std::env::var("RAEA_BAKE_DIR").expect("RAEA_BAKE_DIR"));
let t0 = std::time::Instant::now();
let mut m = read(&std::fs::read(dir.join("set.glb")).unwrap(), 512).unwrap();
if std::env::var("RAEA_BAKE_LAMBERT").is_ok() {
m.surfaces.iter_mut().for_each(|s| *s = Surface { albedo: s.albedo.map(|c| c * (1.0 - s.metallic)), metallic: 0.0, f0: 0.0, ..*s });
}
let listed: serde_json::Value = serde_json::from_slice(&std::fs::read(dir.join("set.lightmaps.json")).unwrap()).unwrap();
let far = m.positions.iter().flatten().fold(0.0f32, |a, v| a.max(v.abs()));
let offset = number("RAEA_BAKE_OFFSET", crate::texels::offset(far));
let hdr = image::open(std::env::var("RAEA_BAKE_SKY").expect("RAEA_BAKE_SKY")).unwrap().to_rgb32f();
let sky = Sky { width: hdr.width(), height: hdr.height(), rgb: hdr.pixels().map(|p| p.0).collect(), strength: number("RAEA_BAKE_STRENGTH", 1.0), rotation: number("RAEA_BAKE_ROTATION", 0.0) };
let sun = std::env::var("RAEA_BAKE_SUN").ok().map(|s| {
let v: Vec<f32> = s.split(',').map(|x| x.parse().unwrap()).collect();
Sun { dir: [v[0], v[1], v[2]], irradiance: [v[3], v[4], v[5]], half_angle: 0.00459 }
});
let world = parry3d::shape::TriMesh::new(m.positions.iter().map(|p| Vec3::from(*p)).collect(), m.triangles.clone()).unwrap();
let mut maps = vec![];
for l in listed["meshes"].as_array().unwrap() {
let name = l["mesh"].as_str().unwrap();
if std::env::var("RAEA_BAKE_ONLY").is_ok_and(|only| !only.split(',').any(|o| o == name)) {
continue;
}
let mesh = m.meshes.iter().find(|x| x.name == name).unwrap_or_else(|| panic!("no mesh {name}"));
let side = l["size"].as_u64().unwrap() as u32;
maps.push((name.to_string(), mesh, side, l["lightmap_exposure"].as_f64().unwrap() as f32 / 683.0, texels(&m, mesh, &world, side, offset, std::env::var("RAEA_BAKE_WHOLE").is_ok())));
}
let origin: Vec<[f32; 3]> = maps.iter().flat_map(|x| x.4.iter().map(|a| a.origin)).collect();
let sides: Vec<[[f32; 3]; 2]> = maps.iter().flat_map(|x| x.4.iter().map(|a| a.sides)).collect();
let open: Vec<u32> = maps.iter().flat_map(|x| x.4.iter().map(|a| a.open)).collect();
let normal: Vec<[f32; 3]> = maps.iter().flat_map(|x| x.4.iter().map(|a| a.normal)).collect();
println!("{} meshes, {} triangles, {} texels, {} inside, {} textures; read and laid in {:.1} s", m.meshes.len(), m.triangles.len(), origin.len(), open.iter().filter(|m| **m == 0).count(), m.textures.len(), t0.elapsed().as_secs_f64());
let runs = std::env::var("RAEA_BAKE_RUNS").unwrap_or("512x4".into());
let w = World { positions: &m.positions, triangles: &m.triangles, surfaces: &m.surfaces, uvs: &m.uvs, textures: &m.textures };
for run in runs.split(',') {
let [samples, bounces] = run.split('x').collect::<Vec<_>>().try_into().expect("SAMPLESxBOUNCES");
let s = Settings { samples: samples.parse().unwrap(), bounces: bounces.parse().unwrap(), per_pass: 8, sky: sky.clone(), sun };
let t1 = std::time::Instant::now();
let light = trace(&w, &Starts { origin: &origin, normal: &normal, sides: &sides, open: &open, offset }, &s, &mut |_, _| {}).unwrap();
let seconds = t1.elapsed().as_secs_f64();
println!("{} values that aren't finite", light.iter().flatten().filter(|v| !v.is_finite()).count());
println!("{run}: traced {} samples, {} bounces in {seconds:.1} s", s.samples, s.bounces);
let passes = number("RAEA_BAKE_SMOOTH", 2.0) as usize;
let (mut first, mut rows) = (0, vec![]);
let (mut abs, mut signed, mut n, mut zeros) = (0.0f64, 0.0f64, 0usize, 0usize);
for (name, mesh, side, scale, at) in &maps {
let side = *side as usize;
let mut mine = vec![None; side * side];
for (k, a) in at.iter().enumerate() {
if open[first + k] != 0 {
mine[a.y as usize * side + a.x as usize] = Some(light[first + k]);
}
}
first += at.len();
smooth(side, &mut mine, passes);
let file = listed["meshes"].as_array().unwrap().iter().find(|l| l["mesh"] == name.as_str()).unwrap()["map"].as_str().unwrap().rsplit('/').next().unwrap().to_string();
let theirs = image::open(dir.join("lightmaps").join(file)).unwrap().to_rgb16();
let lum = |c: [f32; 3]| 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
let (mut a, mut b, mut k) = (0.0f64, 0.0f64, 0usize);
let mut pairs: Vec<f32> = vec![];
for (i, v) in mine.iter().enumerate() {
let q = theirs.get_pixel((i % side) as u32, (i / side) as u32).0;
let (Some(v), false) = (v, q.contains(&u16::MAX)) else { continue };
let (x, y) = (lum(*v), lum(q.map(|c| c as f32 / 65535.0 * scale)));
pairs.extend([x, y, i as f32]);
if x <= 0.0 || y <= 0.0 {
zeros += 1;
continue;
}
let st = (x / y).log2() as f64;
(a, b, k) = (a + st.abs(), b + st, k + 1);
}
if let Ok(d) = std::env::var("RAEA_BAKE_DUMP") {
std::fs::write(format!("{d}/{run}-{name}.f32"), pairs.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>()).unwrap();
}
let s0 = m.surfaces[mesh.triangles.start];
(abs, signed, n) = (abs + a, signed + b, n + k);
rows.push(serde_json::json!({ "mesh": name, "side": side, "texels": k, "mean_stops": a / k.max(1) as f64, "bias_stops": b / k.max(1) as f64, "textured": s0.texture.is_some(), "albedo": s0.albedo }));
}
let over = rows.iter().filter(|r| r["texels"].as_u64().unwrap() > 0 && r["mean_stops"].as_f64().unwrap() > 1.0 / 3.0).count();
println!("{n} texels compared ({zeros} left out, one side exactly 0): mean {:.3} stops, bias {:+.3}; {over} of {} meshes over 1/3 stop", abs / n as f64, signed / n as f64, rows.len());
if let Ok(out) = std::env::var("RAEA_BAKE_OUT") {
std::fs::write(format!("{out}-{run}.json"), serde_json::json!({ "samples": s.samples, "bounces": s.bounces, "trace_seconds": seconds, "mean_stops": abs / n as f64, "bias_stops": signed / n as f64, "meshes": rows }).to_string()).unwrap();
}
}
}
+55 -12
View File
@@ -13,6 +13,7 @@ use rayon::prelude::*;
use serde_json::{Value, json};
use raea_sys_atlas::rays::{hemi, sample};
use raea_sys_lighttrace::CENTRE;
pub use raea_sys_atlas::{Layout, Texel};
/// Rays each texel casts for the inside test: cosine-weighted, the atlas's rotated R2 sequence per texel.
@@ -23,9 +24,11 @@ pub struct Texels {
pub layout: Layout,
/// each texel's ray origin: its surface point, four offsets in from its triangle's edges, moved `offset` along its normal
pub origin: Vec<[f32; 3]>,
/// the texels inside other geometry (their rays meet back faces), left for BK4 to fill
pub inside: Vec<bool>,
/// metres off the surface: 1e-5 of the model's size or of its farthest coordinate, at least 10 microns
/// the two sides of each texel's footprint, and which of the points over it are open (0 inside other geometry: their
/// rays meet back faces, left for BK4 to fill), as raea_sys_lighttrace::Starts takes them
pub sides: Vec<[[f32; 3]; 2]>,
pub open: Vec<u32>,
/// metres off the surface: `offset` of the model's size or of its farthest coordinate
pub offset: f32,
/// the model's triangles in world space, for the trace (BK3)
pub mesh: TriMesh,
@@ -37,6 +40,19 @@ pub fn request(texels: f32, max_side: u32) -> Value {
json!({ "env": { "density": texels, "max_side": max_side } })
}
impl Texels {
/// Which texels are inside other geometry, in the layout's order.
pub fn inside(&self) -> Vec<bool> {
self.open.iter().map(|&m| m == 0).collect()
}
}
/// How far off a surface a ray starts in a model of this size, metres: three times what its floats round to
/// (a_surface_never_meets_itself), and well under the gaps things are stacked with (0.2 mm in a 15 m room).
pub fn offset(size: f32) -> f32 {
(1e-6 * size).max(1e-6)
}
/// Every texel of the model's atlas in the world: its origin and whether it's inside other geometry.
pub fn texels(glb: &[u8], req: &Value) -> Result<Texels, String> {
let (layout, mesh) = raea_sys_atlas::laid(glb, req)?;
@@ -44,20 +60,24 @@ pub fn texels(glb: &[u8], req: &Value) -> Result<Texels, String> {
for &v in mesh.vertices() {
(lo, hi, far) = (lo.min(v), hi.max(v), far.max(v.abs().max_element()));
}
let offset = (1e-5 * (hi - lo).length().max(far)).max(1e-5);
let half = 0.5 / layout.density;
let origin: Vec<[f32; 3]> = layout.texels.iter().map(|t| {
let tri = mesh.indices()[t.tri as usize].map(|v| mesh.vertices()[v as usize]);
(off_edges(tri, Vec3::from(t.p), 4.0 * offset, half) + Vec3::from(t.n) * offset).to_array()
let offset = offset((hi - lo).length().max(far));
// a texel of the atlas is a square of its density; its turn on the surface doesn't matter to its footprint
let sides: Vec<[[f32; 3]; 2]> = layout.texels.iter().map(|t| {
let n = Vec3::from(t.n);
let u = n.any_orthonormal_vector() / layout.density;
[u.to_array(), n.cross(u).to_array()]
}).collect();
let inside = layout.texels.par_iter().zip(&origin).enumerate().map(|(i, (t, &o))| inside(&mesh, Vec3::from(o), Vec3::from(t.n), i as u32)).collect();
Ok(Texels { layout, origin, inside, offset, mesh })
let (origin, open) = layout.texels.par_iter().zip(&sides).enumerate().map(|(i, (t, s))| {
let tri = mesh.indices()[t.tri as usize].map(|v| mesh.vertices()[v as usize]);
starts(&mesh, tri, Vec3::from(t.p), Vec3::from(t.n), s.map(Vec3::from), offset, i as u32, false)
}).unzip();
Ok(Texels { layout, origin, sides, open, offset, mesh })
}
/// Whether a texel is inside other geometry: of its rays that meet anything, at least half meet a back face and more
/// meet back faces than front ones. A foot inside a closed floor slab meets back faces every way; one under a floor
/// that is a single plane meets its underside upwards and nothing downwards, and is inside too.
fn inside(mesh: &TriMesh, o: Vec3, n: Vec3, seed: u32) -> bool {
pub(crate) fn inside(mesh: &TriMesh, o: Vec3, n: Vec3, seed: u32) -> bool {
let (mut back, mut front) = (0, 0);
for j in 0..RAYS {
let d = hemi(n, sample(seed, j));
@@ -69,11 +89,34 @@ fn inside(mesh: &TriMesh, o: Vec3, n: Vec3, seed: u32) -> bool {
back * 2 >= RAYS && back > front
}
/// Where a texel's samples start: its point off the surface, and which of the 4 x 4 points of its footprint are open
/// (on its triangle, clear of its edges, not inside other geometry). A texel half buried keeps only its open half:
/// what it's averaged over is what can be seen (`whole` takes the buried part too, as Cycles does: for comparing). A
/// corner and the centre that agree stand for the rest.
pub(crate) fn starts(mesh: &TriMesh, tri: [Vec3; 3], p: Vec3, n: Vec3, [u, v]: [Vec3; 2], offset: f32, seed: u32, whole: bool) -> ([f32; 3], u32) {
let gap = 4.0 * offset;
let centre = off_edges(tri, p, gap, 0.5 * u.length().max(v.length())) + n * offset;
let at = |c: u32| p + u * ((c % 4) as f32 / 4.0 - 0.375) + v * ((c / 4) as f32 / 4.0 - 0.375);
let cells: Vec<u32> = (0..16).filter(|&c| off_edges(tri, at(c), gap, f32::MAX).distance(at(c)) < 0.5 * offset).collect();
if whole && !cells.is_empty() {
return ((p + n * offset).to_array(), cells.iter().fold(0, |m, c| m | 1 << c));
}
let hid = inside(mesh, centre, n, seed);
let buried = |c: u32| inside(mesh, at(c) + n * offset, n, seed ^ (c + 1).wrapping_mul(0x9e37_79b9));
if cells.is_empty() {
return (centre.to_array(), if hid { 0 } else { CENTRE });
}
let corners: Vec<u32> = cells.iter().copied().filter(|c| [0, 3, 12, 15].contains(c)).collect();
let mixed = corners.iter().any(|&c| buried(c) != hid) || (corners.is_empty() && cells.len() < 16);
let open = if !mixed { if hid { 0 } else { cells.iter().fold(0, |m, c| m | 1 << c) } } else { cells.iter().filter(|&&c| !buried(c)).fold(0, |m, c| m | 1 << c) };
if open == 0 { (centre.to_array(), if hid { 0 } else { CENTRE }) } else { ((p + n * offset).to_array(), open) }
}
/// p moved along its triangle until it's `gap` from each edge, or by `most` (half a texel: its own footprint; a needle
/// narrower than the gap would send it to its far end). A chart's
/// edge band takes its texels from the edge itself, and a point on the edge of a floor is in the plane of the wall
/// standing on it: its rays started in that wall and half of them left the room.
fn off_edges([a, b, c]: [Vec3; 3], p: Vec3, gap: f32, most: f32) -> Vec3 {
pub(crate) fn off_edges([a, b, c]: [Vec3; 3], p: Vec3, gap: f32, most: f32) -> Vec3 {
let n = (b - a).cross(c - a);
let area = n.length_squared().max(f32::MIN_POSITIVE);
// barycentric weights, each raised to what stands `gap` from the edge opposite its corner (its height: area / edge)
+4 -4
View File
@@ -100,7 +100,7 @@ fn a_point_on_an_edge_is_moved_off_it_and_never_far() {
fn texels_inside_the_slab_are_marked_and_those_in_the_open_are_not() {
let t = texels(&set(), &request(16.0, 1024)).unwrap();
let (mut sunk, mut open, mut under) = (0, 0, 0);
for (x, &inside) in t.layout.texels.iter().zip(&t.inside) {
for (x, &inside) in t.layout.texels.iter().zip(&t.inside()) {
let [px, py, pz] = x.p;
if (-0.18..-0.02).contains(&py) && px.abs() < 0.26 && pz.abs() < 0.26 {
// the block's sides within the slab's thickness, away from its faces
@@ -123,7 +123,7 @@ fn texels_inside_the_slab_are_marked_and_those_in_the_open_are_not() {
#[test]
fn the_same_model_gives_the_same_texels() {
let (a, b) = (texels(&set(), &request(16.0, 1024)).unwrap(), texels(&set(), &request(16.0, 1024)).unwrap());
assert!(a.layout == b.layout && a.origin == b.origin && a.inside == b.inside);
assert!(a.layout == b.layout && a.origin == b.origin && a.open == b.open);
}
#[test]
@@ -143,11 +143,11 @@ fn measured() {
let layout = raea_sys_atlas::layout(&glb, &request(64.0, 4096)).unwrap();
let t1 = std::time::Instant::now();
let t = texels(&glb, &request(64.0, 4096)).unwrap();
let inside = t.inside.iter().filter(|&&i| i).count();
let inside = t.inside().iter().filter(|&&i| i).count();
if let Ok(out) = std::env::var("RAEA_BAKE_OUT") {
// the atlas: grey where a texel is in the open, red where it's inside, black where there's none (a PPM)
let mut img = vec![0u8; (layout.w * layout.h * 3) as usize];
for (x, &i) in t.layout.texels.iter().zip(&t.inside) {
for (x, &i) in t.layout.texels.iter().zip(&t.inside()) {
let k = 3 * (x.y as usize * layout.w as usize + x.x as usize);
img[k..k + 3].copy_from_slice(if i { &[230, 40, 30] } else { &[150, 150, 150] });
}
-107
View File
@@ -1,107 +0,0 @@
use super::*;
use crate::texels::tests::{cuboid, glb, set};
use crate::texels::{request, texels};
fn world(mesh: &parry3d::shape::TriMesh, surfaces: &[Surface]) -> (Vec<[f32; 3]>, Vec<[u32; 3]>, Vec<Surface>) {
(mesh.vertices().iter().map(|v| v.to_array()).collect(), mesh.indices().to_vec(), surfaces.to_vec())
}
/// The light on t's texels, each triangle's surface given by its centroid.
fn run(t: &crate::texels::Texels, surface: impl Fn([f32; 3]) -> Surface, s: &Settings) -> Vec<[f32; 3]> {
let v = t.mesh.vertices();
let surfaces: Vec<Surface> = t.mesh.indices().iter().map(|i| surface(std::array::from_fn(|k| i.iter().map(|&j| v[j as usize][k]).sum::<f32>() / 3.0))).collect();
let (p, i, s2) = world(&t.mesh, &surfaces);
let normal: Vec<[f32; 3]> = t.layout.texels.iter().map(|x| x.n).collect();
let starts = Starts { origin: &t.origin, normal: &normal, inside: &t.inside, offset: t.offset };
trace(&World { positions: &p, triangles: &i, surfaces: &s2 }, &starts, s, &mut |_, _| {}).unwrap()
}
/// A white set under a white sky: whatever bounces, every texel's light is the sky's (a white furnace). The block sunk
/// in the slab and the box set by its node make real concave corners; paths there bounce until they find the sky.
#[test]
fn a_white_furnace_is_the_sky_at_every_texel() {
let t = texels(&set(), &request(8.0, 1024)).unwrap();
let s = Settings { samples: 64, bounces: 64, per_pass: 16, sky: [1.0; 3] };
let light = run(&t, |_| Surface { albedo: [1.0; 3], emission: [0.0; 3] }, &s);
let open: Vec<[f32; 3]> = light.iter().zip(&t.inside).filter(|(_, i)| !**i).map(|(l, _)| *l).collect();
let off = open.iter().filter(|l| l.iter().any(|c| (c - 1.0).abs() > 0.01)).count();
println!("furnace: {off} of {} off by more than 1%", open.len());
let worst = open.iter().flatten().fold(0.0f32, |m, c| m.max((c - 1.0).abs()));
println!("furnace: worst {worst}, mean {}", open.iter().map(|l| l[0]).sum::<f32>() / open.len() as f32);
assert!(open.len() > 500 && off == 0, "{off} of {} texels more than 1% off the sky, worst {worst}", open.len());
}
/// A black wall 40 m long and 2 m high on a black floor under a white sky: the floor's light at a distance d from its
/// foot is what the sky leaves, 1/2 (1 + d / sqrt(d^2 + h^2)) (an endless wall's form factor), which only cosine-weighted
/// rays give.
#[test]
fn a_walls_shadow_on_the_floor_is_its_form_factor() {
let set = glb(&[(cuboid([0.0, -0.1, -20.0], [6.0, 0.0, 20.0]), [0.0; 3]), (cuboid([-0.2, -0.1, -20.0], [0.0, 2.0, 20.0]), [0.0; 3])]);
let t = texels(&set, &request(4.0, 1024)).unwrap();
let light = run(&t, |_| Surface { albedo: [0.0; 3], emission: [0.0; 3] }, &Settings { samples: 512, ..Settings::default() });
for d in [0.5f32, 1.0, 2.0, 4.0] {
let v: Vec<(f32, f32)> = t.layout.texels.iter().zip(&light).filter(|(x, _)| x.p[1].abs() < 1e-3 && x.n[1] > 0.9 && x.p[2].abs() < 4.0 && (x.p[0] - d).abs() < 0.13).map(|(x, l)| (0.5 * (1.0 + x.p[0] / (x.p[0] * x.p[0] + 4.0).sqrt()), l[0])).collect();
let (want, got) = v.iter().fold((0.0, 0.0), |(a, b), (w, g)| (a + w / v.len() as f32, b + g / v.len() as f32));
println!("wall: d {d} m: {got:.4} for {want:.4} over {} texels", v.len());
assert!(v.len() > 20 && (got - want).abs() < 0.01, "{d} m from the wall the floor gets {got}, not {want}");
}
}
/// A closed box glowing 1 all round with an albedo of a half: every point inside gets 1 + 1/2 + 1/4 ... = 2.
#[test]
fn a_glowing_box_adds_up_its_bounces() {
let inward = cuboid([-1.0; 3], [1.0; 3]).into_iter().map(|[a, b, c]| [a, c, b]).collect();
let t = texels(&glb(&[(inward, [0.0; 3])]), &request(8.0, 1024)).unwrap();
let light = run(&t, |_| Surface { albedo: [0.5; 3], emission: [1.0; 3] }, &Settings { samples: 64, bounces: 64, per_pass: 16, sky: [0.0; 3] });
let mean = light.iter().zip(&t.inside).filter(|(_, i)| !**i).map(|(l, _)| l[0]).sum::<f32>() / t.inside.iter().filter(|i| !**i).count() as f32;
println!("box: {mean:.4} for 2, {} of {} texels marked inside", t.inside.iter().filter(|i| **i).count(), t.inside.len());
assert!((mean - 2.0).abs() < 0.01, "the glowing box's light is {mean}, not 2");
}
/// A white floor beside a red wall: the floor near the wall gets redder than the floor far from it.
#[test]
fn a_red_wall_bleeds_onto_the_floor() {
let floor = cuboid([-1.0, -0.1, -2.0], [1.0, 0.0, 2.0]);
let wall = cuboid([-1.0, 0.0, -2.0], [-0.9, 2.0, 2.0]);
let t = texels(&glb(&[(floor, [0.0; 3]), (wall, [0.0; 3])]), &request(16.0, 1024)).unwrap();
let red = |c: [f32; 3]| Surface { albedo: if c[1] > 0.5 { [0.9, 0.0, 0.0] } else { [0.9; 3] }, emission: [0.0; 3] };
let light = run(&t, red, &Settings { samples: 128, bounces: 4, per_pass: 32, sky: [1.0; 3] });
// floor top texels near the wall (x -0.9..-0.7) and far (x > 0.6)
let mean = |near: bool| {
let v: Vec<f32> = t.layout.texels.iter().zip(&light).zip(&t.inside).filter(|((x, _), i)| !**i && x.p[1].abs() < 1e-3 && x.n[1] > 0.9 && if near { x.p[0] < -0.7 } else { x.p[0] > 0.6 }).map(|((_, l), _)| l[1] / l[0]).collect();
v.iter().sum::<f32>() / v.len() as f32
};
let (near, far) = (mean(true), mean(false));
assert!(near < far * 0.97, "green over red near the red wall {near}, far from it {far}");
}
#[test]
fn the_same_bake_gives_the_same_bytes() {
let t = texels(&set(), &request(8.0, 1024)).unwrap();
let s = Settings { samples: 16, per_pass: 8, ..Settings::default() };
let surf = |c: [f32; 3]| Surface { albedo: [0.5 + 0.1 * c[0].abs().fract(); 3], emission: [0.0; 3] };
let (a, b) = (run(&t, surf, &s), run(&t, surf, &s));
assert!(a.iter().any(|l| l[0] > 0.1), "no light at all");
assert_eq!(a, b);
}
#[test]
fn mismatched_inputs_are_refused() {
let starts = Starts { origin: &[[0.0; 3]], normal: &[], inside: &[], offset: 1e-4 };
assert!(trace(&World { positions: &[], triangles: &[], surfaces: &[] }, &starts, &Settings::default(), &mut |_, _| {}).is_err());
}
/// The measured run (docs/bake.feature BK3): RAEA_BAKE_GLB at 64 texels a metre, every surface 0.7 grey under a white
/// sky, RAEA_BAKE_SAMPLES (default 512) a texel: the trace's time alone.
/// `cargo test -p raea-sys-lightbake trace::tests::measured -- --ignored --nocapture`
#[test]
#[ignore]
fn measured() {
let glb = std::fs::read(std::env::var("RAEA_BAKE_GLB").expect("RAEA_BAKE_GLB: a .glb")).unwrap();
let samples = std::env::var("RAEA_BAKE_SAMPLES").ok().and_then(|v| v.parse().ok()).unwrap_or(512);
let t = texels(&glb, &request(64.0, 4096)).unwrap();
let t0 = std::time::Instant::now();
let light = run(&t, |_| Surface { albedo: [0.7; 3], emission: [0.0; 3] }, &Settings { samples, ..Settings::default() });
let lit = light.iter().zip(&t.inside).filter(|(_, i)| !**i).map(|(l, _)| l[0]).collect::<Vec<_>>();
println!("{} texels, {} triangles, {samples} samples, 4 bounces: {:.2} s, mean light {:.3}", light.len(), t.mesh.indices().len(), t0.elapsed().as_secs_f64(), lit.iter().sum::<f32>() / lit.len() as f32);
}
+212
View File
@@ -0,0 +1,212 @@
use raea_sys_lighttrace::*;
use crate::texels::tests::{cuboid, glb, set};
use crate::texels::{request, starts, texels};
use parry3d::glamx::Vec3;
fn world(mesh: &parry3d::shape::TriMesh, surfaces: &[Surface]) -> (Vec<[f32; 3]>, Vec<[u32; 3]>, Vec<Surface>) {
(mesh.vertices().iter().map(|v| v.to_array()).collect(), mesh.indices().to_vec(), surfaces.to_vec())
}
/// The light on t's texels, each triangle's surface given by its centroid.
fn run(t: &crate::texels::Texels, surface: impl Fn([f32; 3]) -> Surface, s: &Settings) -> Vec<[f32; 3]> {
let v = t.mesh.vertices();
let surfaces: Vec<Surface> = t.mesh.indices().iter().map(|i| surface(std::array::from_fn(|k| i.iter().map(|&j| v[j as usize][k]).sum::<f32>() / 3.0))).collect();
let (p, i, s2) = world(&t.mesh, &surfaces);
let normal: Vec<[f32; 3]> = t.layout.texels.iter().map(|x| x.n).collect();
let starts = Starts { origin: &t.origin, normal: &normal, sides: &t.sides, open: &t.open, offset: t.offset };
trace(&World { positions: &p, triangles: &i, surfaces: &s2, uvs: &[], textures: &[] }, &starts, s, &mut |_, _| {}).unwrap()
}
/// A white set under a white sky: whatever bounces, every texel's light is the sky's (a white furnace). The block sunk
/// in the slab and the box set by its node make real concave corners; paths there bounce until they find the sky.
#[test]
fn a_white_furnace_is_the_sky_at_every_texel() {
let t = texels(&set(), &request(8.0, 1024)).unwrap();
let s = Settings { samples: 64, bounces: 64, per_pass: 16, sky: Sky::even([1.0; 3]), ..Settings::default() };
let light = run(&t, |_| Surface { albedo: [1.0; 3], ..Surface::default() }, &s);
let open: Vec<[f32; 3]> = light.iter().zip(&t.inside()).filter(|(_, i)| !**i).map(|(l, _)| *l).collect();
let off = open.iter().filter(|l| l.iter().any(|c| (c - 1.0).abs() > 0.01)).count();
println!("furnace: {off} of {} off by more than 1%", open.len());
let worst = open.iter().flatten().fold(0.0f32, |m, c| m.max((c - 1.0).abs()));
println!("furnace: worst {worst}, mean {}", open.iter().map(|l| l[0]).sum::<f32>() / open.len() as f32);
assert!(open.len() > 500 && off == 0, "{off} of {} texels more than 1% off the sky, worst {worst}", open.len());
}
/// A black wall 40 m long and 2 m high on a black floor under a white sky: the floor's light at a distance d from its
/// foot is what the sky leaves, 1/2 (1 + d / sqrt(d^2 + h^2)) (an endless wall's form factor), which only cosine-weighted
/// rays give.
#[test]
fn a_walls_shadow_on_the_floor_is_its_form_factor() {
let set = glb(&[(cuboid([0.0, -0.1, -20.0], [6.0, 0.0, 20.0]), [0.0; 3]), (cuboid([-0.2, -0.1, -20.0], [0.0, 2.0, 20.0]), [0.0; 3])]);
let t = texels(&set, &request(4.0, 1024)).unwrap();
let light = run(&t, |_| Surface { albedo: [0.0; 3], ..Surface::default() }, &Settings { samples: 512, ..Settings::default() });
for d in [0.5f32, 1.0, 2.0, 4.0] {
let v: Vec<(f32, f32)> = t.layout.texels.iter().zip(&light).filter(|(x, _)| x.p[1].abs() < 1e-3 && x.n[1] > 0.9 && x.p[2].abs() < 4.0 && (x.p[0] - d).abs() < 0.13).map(|(x, l)| (0.5 * (1.0 + x.p[0] / (x.p[0] * x.p[0] + 4.0).sqrt()), l[0])).collect();
let (want, got) = v.iter().fold((0.0, 0.0), |(a, b), (w, g)| (a + w / v.len() as f32, b + g / v.len() as f32));
println!("wall: d {d} m: {got:.4} for {want:.4} over {} texels", v.len());
assert!(v.len() > 20 && (got - want).abs() < 0.01, "{d} m from the wall the floor gets {got}, not {want}");
}
}
/// A closed box glowing 1 all round with an albedo of a half: every point inside gets 1 + 1/2 + 1/4 ... = 2.
#[test]
fn a_glowing_box_adds_up_its_bounces() {
let inward = cuboid([-1.0; 3], [1.0; 3]).into_iter().map(|[a, b, c]| [a, c, b]).collect();
let t = texels(&glb(&[(inward, [0.0; 3])]), &request(8.0, 1024)).unwrap();
let light = run(&t, |_| Surface { albedo: [0.5; 3], emission: [1.0; 3], ..Surface::default() }, &Settings { samples: 64, bounces: 64, per_pass: 16, sky: Sky::even([0.0; 3]), ..Settings::default() });
let mean = light.iter().zip(&t.inside()).filter(|(_, i)| !**i).map(|(l, _)| l[0]).sum::<f32>() / t.inside().iter().filter(|i| !**i).count() as f32;
println!("box: {mean:.4} for 2, {} of {} texels marked inside", t.inside().iter().filter(|i| **i).count(), t.inside().len());
assert!((mean - 2.0).abs() < 0.01, "the glowing box's light is {mean}, not 2");
}
/// A white floor beside a red wall: the floor near the wall gets redder than the floor far from it.
#[test]
fn a_red_wall_bleeds_onto_the_floor() {
let floor = cuboid([-1.0, -0.1, -2.0], [1.0, 0.0, 2.0]);
let wall = cuboid([-1.0, 0.0, -2.0], [-0.9, 2.0, 2.0]);
let t = texels(&glb(&[(floor, [0.0; 3]), (wall, [0.0; 3])]), &request(16.0, 1024)).unwrap();
let red = |c: [f32; 3]| Surface { albedo: if c[1] > 0.5 { [0.9, 0.0, 0.0] } else { [0.9; 3] }, ..Surface::default() };
let light = run(&t, red, &Settings { samples: 128, bounces: 4, per_pass: 32, sky: Sky::even([1.0; 3]), ..Settings::default() });
// floor top texels near the wall (x -0.9..-0.7) and far (x > 0.6)
let mean = |near: bool| {
let v: Vec<f32> = t.layout.texels.iter().zip(&light).zip(&t.inside()).filter(|((x, _), i)| !**i && x.p[1].abs() < 1e-3 && x.n[1] > 0.9 && if near { x.p[0] < -0.7 } else { x.p[0] > 0.6 }).map(|((_, l), _)| l[1] / l[0]).collect();
v.iter().sum::<f32>() / v.len() as f32
};
let (near, far) = (mean(true), mean(false));
assert!(near < far * 0.97, "green over red near the red wall {near}, far from it {far}");
}
#[test]
fn the_same_bake_gives_the_same_bytes() {
let t = texels(&set(), &request(8.0, 1024)).unwrap();
let s = Settings { samples: 16, per_pass: 8, ..Settings::default() };
let surf = |c: [f32; 3]| Surface { albedo: [0.5 + 0.1 * c[0].abs().fract(); 3], ..Surface::default() };
let (a, b) = (run(&t, surf, &s), run(&t, surf, &s));
assert!(a.iter().any(|l| l[0] > 0.1), "no light at all");
assert_eq!(a, b);
}
#[test]
fn mismatched_inputs_are_refused() {
let starts = Starts { origin: &[[0.0; 3]], normal: &[], sides: &[], open: &[], offset: 1e-4 };
assert!(trace(&World { positions: &[], triangles: &[], surfaces: &[], uvs: &[], textures: &[] }, &starts, &Settings::default(), &mut |_, _| {}).is_err());
}
/// A floor, and something on it: the light on a texel 0.4 m a side whose centre is 0.1 m under its edge at x = 0, by
/// its starts, and which of them are open.
fn half_covered(on_it: &[crate::texels::tests::Tri], samples_at_centre: bool) -> (f32, u32) {
let floor = [[-40.0, 0.0, -40.0], [-40.0, 0.0, 80.0], [80.0, 0.0, -40.0]];
let mesh = parry3d::shape::TriMesh::new(std::iter::once(floor).chain(on_it.iter().copied()).flatten().map(Vec3::from).collect(), (0..on_it.len() as u32 + 1).map(|k| [3 * k, 3 * k + 1, 3 * k + 2]).collect()).unwrap();
let sides = [[0.4, 0.0, 0.0], [0.0, 0.0, 0.4]];
let (origin, open) = starts(&mesh, floor.map(Vec3::from), Vec3::new(0.1, 0.0, 0.0), Vec3::Y, sides.map(Vec3::from), 1e-4, 7, false);
let (p, i, s) = world(&mesh, &vec![Surface::default(); mesh.indices().len()]);
let st = Starts { origin: &[origin], normal: &[[0.0, 1.0, 0.0]], sides: &[sides], open: &[if samples_at_centre { CENTRE } else { open }], offset: 1e-4 };
let l = trace(&World { positions: &p, triangles: &i, surfaces: &s, uvs: &[], textures: &[] }, &st, &Settings { samples: 4096, ..Settings::default() }, &mut |_, _| {}).unwrap();
(l[0][0], open)
}
/// A texel with a sheet 0.2 mm over three quarters of it (a stack's ledge): a quarter of the sky, as Cycles' jittered
/// samples see, where its centre alone sees nothing.
#[test]
fn a_texel_under_a_sheets_edge_sees_the_part_that_is_open() {
let sheet = cuboid([0.0, 0.0002, -10.0], [10.0, 0.0052, 10.0]);
let (centre, _) = half_covered(&sheet, true);
let (over, open) = half_covered(&sheet, false);
println!("ledge: centre {centre:.4}, over the texel {over:.4} for 0.249, open {open:#x}");
assert!(centre < 0.01 && (over - 0.249).abs() < 0.01 && open == 0xffff, "{centre} {over} {open:#x}");
}
/// A texel three quarters inside a block sunk in the floor: only its open quarter counts, not that quarter averaged with
/// the dark inside.
#[test]
fn a_texel_half_buried_is_lit_by_its_open_part() {
let block = cuboid([0.0, -1.0, -10.0], [10.0, 1.0, 10.0]);
let (over, open) = half_covered(&block, false);
println!("block: {over:.4} over its open part, open {open:#x}");
assert!(open == 0x1111 && (0.48..0.58).contains(&over), "{over} {open:#x}");
}
/// A 40 m floor lit by the sun at 45 degrees and nothing else: a point 0.1 m over it looking down gets the sunlit
/// floor's light, albedo x irradiance x cos 45 / pi; a point on the floor gets nothing, its own sun being live.
#[test]
fn the_sun_lights_what_it_bounces_to_and_not_the_texel_itself() {
let p = [[-20.0, 0.0, -20.0], [20.0, 0.0, -20.0], [20.0, 0.0, 20.0], [-20.0, 0.0, 20.0]];
let surfaces = [Surface { albedo: [0.5; 3], ..Surface::default() }; 2];
let world = World { positions: &p, triangles: &[[0, 2, 1], [0, 3, 2]], surfaces: &surfaces, uvs: &[], textures: &[] };
let starts = Starts { origin: &[[0.0, 0.1, 0.0], [8.0, 1e-4, 0.0]], normal: &[[0.0, -1.0, 0.0], [0.0, 1.0, 0.0]], sides: &[[[0.0; 3]; 2]; 2], open: &[CENTRE; 2], offset: 1e-4 };
let sun = Sun { dir: [1.0, 1.0, 0.0], irradiance: [std::f32::consts::PI, 0.0, 0.0], half_angle: 0.0046 };
let s = Settings { samples: 4096, per_pass: 64, bounces: 1, sky: Sky::even([0.0; 3]), sun: Some(sun), ..Settings::default() };
let l = trace(&world, &starts, &s, &mut |_, _| {}).unwrap();
println!("sun: over the floor {:?} for 0.3536, on it {:?} for 0", l[0], l[1]);
assert!((l[0][0] - 0.3536).abs() < 0.005 && l[0][1] == 0.0 && l[1] == [0.0; 3], "{l:?}");
}
/// A sky lit only in its left-to-right middle half (straight ahead, -Z): a wall facing -Z gets the light, one facing +Z
/// none; turned a quarter counter-clockwise from above the light comes from -X.
#[test]
fn the_panorama_faces_ahead_and_turns_counter_clockwise() {
let set = glb(&[(cuboid([-0.5, 0.0, -0.5], [0.5, 1.0, 0.5]), [0.0; 3])]);
let t = texels(&set, &request(8.0, 512)).unwrap();
let sky = |rotation| Sky { width: 64, height: 1, rgb: (0..64).map(|x| if (16..48).contains(&x) { [1.0; 3] } else { [0.0; 3] }).collect(), strength: 1.0, rotation };
let faces = |rotation: f32| {
let light = run(&t, |_| Surface::default(), &Settings { samples: 256, sky: sky(rotation), ..Settings::default() });
[[0.0, 0.0, -1.0], [0.0, 0.0, 1.0], [-1.0, 0.0, 0.0], [1.0, 0.0, 0.0]].map(|n: [f32; 3]| {
let v: Vec<f32> = t.layout.texels.iter().zip(&light).filter(|(x, _)| (0..3).all(|k| (x.n[k] - n[k]).abs() < 0.1)).map(|(_, l)| l[0]).collect();
v.iter().sum::<f32>() / v.len() as f32
})
};
let (ahead, turned) = (faces(0.0), faces(std::f32::consts::FRAC_PI_2));
println!("sky: -Z +Z -X +X {ahead:?}, turned {turned:?}");
assert!(ahead[0] > 0.97 && ahead[1] < 0.03 && (ahead[2] - 0.5).abs() < 0.03, "{ahead:?}");
assert!(turned[2] > 0.97 && turned[3] < 0.03 && (turned[0] - 0.5).abs() < 0.03, "{turned:?}");
}
/// Points looking straight up under an even sky, 134 million rays: one in 2^24 goes exactly up, where the panorama's
/// longitude is atan2(0, 0), which Metal gave as NaN (a whole texel lost on the atelier at 1024 samples).
#[test]
fn a_ray_straight_up_sees_the_sky() {
let p = [[0.0, -5.0, 0.0], [1.0, -5.0, 0.0], [0.0, -5.0, 1.0]];
let world = World { positions: &p, triangles: &[[0, 1, 2]], surfaces: &[Surface::default()], uvs: &[], textures: &[] };
let n = 16384;
let (origin, normal, sides, open) = (vec![[0.0; 3]; n], vec![[0.0, 1.0, 0.0]; n], vec![[[0.0; 3]; 2]; n], vec![CENTRE; n]);
let l = trace(&world, &Starts { origin: &origin, normal: &normal, sides: &sides, open: &open, offset: 1e-4 }, &Settings { samples: 8192, per_pass: 128, ..Settings::default() }, &mut |_, _| {}).unwrap();
assert_eq!(l.iter().flatten().filter(|v| !v.is_finite()).count(), 0, "values that aren't finite");
assert!(l.iter().all(|c| (c[0] - 1.0).abs() < 1e-3), "not the sky: {:?}", l.iter().find(|c| (c[0] - 1.0).abs() >= 1e-3));
}
/// A floor textured red on its left half and green on its right (sRGB 188 is 0.5 linear): the underside of a plate
/// over each half sees that half's colour.
#[test]
fn a_textured_floor_bounces_its_texture() {
let (mut p, mut tri, mut uv) = (vec![], vec![], vec![]);
for (x, z) in [(-20.0f32, -20.0f32), (20.0, -20.0), (20.0, 20.0), (-20.0, 20.0)] {
p.push([x, 0.0, z]);
uv.push([(x + 20.0) / 40.0, (z + 20.0) / 40.0]);
}
tri.extend([[0u32, 2, 1], [0, 3, 2]]);
let image = Image { width: 2, height: 1, rgba: vec![0xff00_00bc, 0xff00_bc00] };
let surfaces = vec![Surface { albedo: [1.0; 3], texture: Some(0), ..Surface::default() }; 2];
let origin: Vec<[f32; 3]> = [-10.0, 10.0].into_iter().map(|x| [x, 0.1, 0.0]).collect();
let starts = Starts { origin: &origin, normal: &[[0.0, -1.0, 0.0]; 2], sides: &[[[0.0; 3]; 2]; 2], open: &[CENTRE; 2], offset: 1e-4 };
let s = Settings { samples: 4096, per_pass: 64, bounces: 2, ..Settings::default() };
let l = trace(&World { positions: &p, triangles: &tri, surfaces: &surfaces, uvs: &uv, textures: &[image] }, &starts, &s, &mut |_, _| {}).unwrap();
println!("textured: {l:?}");
assert!((l[0][0] - 0.5029).abs() < 0.01 && l[0][1] < 0.01 && (l[1][1] - 0.5029).abs() < 0.01 && l[1][0] < 0.01, "{l:?}");
let bad = trace(&World { positions: &p, triangles: &tri, surfaces: &surfaces, uvs: &[], textures: &[] }, &starts, &s, &mut |_, _| {});
assert!(bad.is_err());
}
/// The measured run (docs/bake.feature BK3): RAEA_BAKE_GLB at 64 texels a metre, every surface 0.7 grey under a white
/// sky, RAEA_BAKE_SAMPLES (default 512) a texel: the trace's time alone.
/// `cargo test -p raea-sys-lightbake trace_tests::measured -- --ignored --nocapture`
#[test]
#[ignore]
fn measured() {
let glb = std::fs::read(std::env::var("RAEA_BAKE_GLB").expect("RAEA_BAKE_GLB: a .glb")).unwrap();
let samples = std::env::var("RAEA_BAKE_SAMPLES").ok().and_then(|v| v.parse().ok()).unwrap_or(512);
let t = texels(&glb, &request(64.0, 4096)).unwrap();
let t0 = std::time::Instant::now();
let light = run(&t, |_| Surface { albedo: [0.7; 3], ..Surface::default() }, &Settings { samples, ..Settings::default() });
let lit = light.iter().zip(&t.inside()).filter(|(_, i)| !**i).map(|(l, _)| l[0]).collect::<Vec<_>>();
println!("{} texels, {} triangles, {samples} samples, 4 bounces: {:.2} s, mean light {:.3}", light.len(), t.mesh.indices().len(), t0.elapsed().as_secs_f64(), lit.iter().sum::<f32>() / lit.len() as f32);
}
-93
View File
@@ -1,93 +0,0 @@
// The light that bounces, per texel (docs/bake.feature BK3): paths from the texel's origin through the model's own
// triangles (one BLAS, one TLAS) by wgpu's ray queries. What a texel keeps is the mean light its cosine-weighted rays
// bring back, so the lightmap times a surface's albedo is the light it sends on. At each hit the surface's emission
// is added and the path goes on weighted by its albedo (Lambert, diffuse.wgsl); a miss sees the sky; after the
// second bounce Russian roulette ends paths by their weight, unbiased. Passes add to `accum` (rgb, samples).
struct Params {
sky: vec4<f32>,
count: u32,
pass_index: u32,
per_pass: u32,
bounces: u32,
offset: f32,
// the first texel of this dispatch (a bake's texels go in chunks)
first: u32,
_pad1: f32,
_pad2: f32,
}
struct Surface {
albedo: vec4<f32>,
emission: vec4<f32>,
}
@group(0) @binding(0) var tlas: acceleration_structure;
@group(0) @binding(1) var<storage, read> positions: array<vec4<f32>>;
@group(0) @binding(2) var<storage, read> indices: array<u32>;
@group(0) @binding(3) var<storage, read> surfaces: array<Surface>;
// per texel: origin (w: 1 when inside other geometry) and normal
@group(0) @binding(4) var<storage, read> texels: array<vec4<f32>>;
@group(0) @binding(5) var<storage, read_write> accum: array<vec4<f32>>;
@group(0) @binding(6) var<uniform> params: Params;
// The nearest hit. Its own function: a ray_query declared in a loop is zeroed again each turn, which naga writes for
// Metal as an assignment Metal's intersection_query deletes.
fn nearest(o: vec3<f32>, d: vec3<f32>) -> RayIntersection {
var rq: ray_query;
rayQueryInitialize(&rq, tlas, RayDesc(0u, 0xffu, 0.0, 1.0e30, o, d));
while (rayQueryProceed(&rq)) {}
return rayQueryGetCommittedIntersection(&rq);
}
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let i = params.first + gid.x;
if (i >= params.count) {
return;
}
let at = texels[2u * i];
if (at.w > 0.5) {
return;
}
let n0 = texels[2u * i + 1u].xyz;
var sum = vec3<f32>(0.0);
for (var s = 0u; s < params.per_pass; s = s + 1u) {
var rng = raea_hash(i * 0x9e3779b9u ^ raea_hash(params.pass_index * params.per_pass + s));
var o = at.xyz;
var n = n0;
var weight = vec3<f32>(1.0);
var light = vec3<f32>(0.0);
for (var b = 0u; b < params.bounces; b = b + 1u) {
let d = raea_diffuse_sample(n, vec2<f32>(raea_rand(&rng), raea_rand(&rng)));
let hit = nearest(o, d);
if (hit.kind == RAY_QUERY_INTERSECTION_NONE) {
light = light + weight * params.sky.rgb;
break;
}
let p = hit.primitive_index;
let srf = surfaces[p];
light = light + weight * srf.emission.rgb;
let a = positions[indices[3u * p]].xyz;
let bb = positions[indices[3u * p + 1u]].xyz;
let c = positions[indices[3u * p + 2u]].xyz;
var ng = normalize(cross(bb - a, c - a));
if (dot(ng, d) > 0.0) {
ng = -ng;
}
let w = hit.barycentrics;
o = a * (1.0 - w.x - w.y) + bb * w.x + c * w.y + ng * params.offset;
n = ng;
weight = weight * srf.albedo.rgb;
if (b >= 2u) {
let q = max(weight.r, max(weight.g, weight.b));
if (raea_rand(&rng) >= q) {
break;
}
weight = weight / q;
}
}
sum = sum + light;
}
accum[i] = accum[i] + vec4<f32>(sum, f32(params.per_pass));
}
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "raea-sys-lighttrace"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "Light paths traced on the GPU: what a triangle bounces, the sky, the sun and emission, by wgpu's ray queries (docs/bake.feature BK3)"
[dependencies]
# the process's one shared GPU device, and wgpu's ray queries on it
raea-gpu-device = { path = "../../gpu/device" }
wgpu = "=30.0.1"
bytemuck = "1"
pollster = "0.4"
+120
View File
@@ -0,0 +1,120 @@
//! The GGX the kernel's glossy bounces use (docs/bake.feature BK3), on the CPU: the directional albedo a rough metal or
//! dielectric layer keeps, tabled, so the kernel can give back what a single scatter loses and keep what's under a
//! dielectric's layer. The functions are Cycles' (github.com/blender/cycles, BSD-3-Clause, see NOTICE:
//! kernel/closure/bsdf_microfacet.h, bsdf_util.h, kernel/sample/mapping.h), written here in Rust and in wgsl/glossy.wgsl until
//! tools/cycles-port is on main, and held to its own output below.
use std::f32::consts::PI;
/// Rows and columns of the table: roughness, then the cosine to the viewer.
pub const STEPS: usize = 32;
pub fn lambda(a2: f32, c: f32) -> f32 {
0.5 * ((1.0 + a2 * (1.0 / (c * c) - 1.0).max(0.0)).sqrt() - 1.0)
}
/// Cycles' bsdf_G: the combined masking and shadowing of the two directions.
pub fn g2(a2: f32, ci: f32, co: f32) -> f32 {
1.0 / (1.0 + lambda(a2, ci) + lambda(a2, co))
}
pub fn d(a2: f32, c: f32) -> f32 {
let c2 = (c * c).min(1.0);
a2 / (PI * (1.0 - c2 + a2 * c2).powi(2))
}
/// A microfacet normal from the ones visible from `wi` (Heitz 2018, as Cycles samples it), in the shading frame.
pub fn vndf(wi: [f32; 3], [ax, ay]: [f32; 2], r: [f32; 2]) -> [f32; 3] {
let n = |v: [f32; 3]| {
let l = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
[v[0] / l, v[1] / l, v[2] / l]
};
let w = n([ax * wi[0], ay * wi[1], wi[2]]);
let l2 = w[0] * w[0] + w[1] * w[1];
let t1 = if l2 > 1e-7 { [-w[1] / l2.sqrt(), w[0] / l2.sqrt(), 0.0] } else { [1.0, 0.0, 0.0] };
let t2 = [w[1] * t1[2] - w[2] * t1[1], w[2] * t1[0] - w[0] * t1[2], w[0] * t1[1] - w[1] * t1[0]];
let (a1, b1) = (2.0 * r[0] - 1.0, 2.0 * r[1] - 1.0);
let (rad, phi) = if a1 == 0.0 && b1 == 0.0 { (0.0, 0.0) } else if a1 * a1 > b1 * b1 { (a1, PI / 4.0 * (b1 / a1)) } else { (b1, PI / 2.0 - PI / 4.0 * (a1 / b1)) };
let x = rad * phi.cos();
let s = 0.5 * (1.0 + w[2]);
let y = (1.0 - x * x).max(0.0).sqrt() * (1.0 - s) + rad * phi.sin() * s;
let z = (1.0 - x * x - y * y).max(0.0).sqrt();
let h: [f32; 3] = std::array::from_fn(|k| x * t1[k] + y * t2[k] + z * w[k]);
n([ax * h[0], ay * h[1], h[2].max(0.0)])
}
/// Where a dielectric of IOR 1.5 stands between its F0 (0.04) and 1 (Cycles' fresnel_dielectric_cos).
pub fn dielectric(c: f32) -> f32 {
let g = (1.25 + c * c).sqrt();
let (a, b) = ((g - c) / (g + c), (c * (g + c) - 1.0) / (c * (g - c) + 1.0));
((0.5 * a * a * (1.0 + b * b) - 0.04) / 0.96).clamp(0.0, 1.0)
}
/// The table, a row a roughness (0 to 1) and a column the square root of the cosine to the viewer (0 to 1): a white lobe's albedo (single scatter), the part of
/// it Schlick's (1 - c)^5 weighs, the part `dielectric` weighs, and the row's mean albedo over the cosines.
pub fn table() -> Vec<[f32; 4]> {
const N: u32 = 1024;
let mut out = vec![[0.0f32; 4]; STEPS * STEPS];
for (i, row) in out.chunks_mut(STEPS).enumerate() {
let a = (i as f32 / (STEPS - 1) as f32).powi(2).max(1e-3);
for (j, cell) in row.iter_mut().enumerate() {
let mu = (j as f32 / (STEPS - 1) as f32).powi(2).max(1e-4);
let wo = [(1.0 - mu * mu).sqrt(), 0.0, mu];
for k in 0..N {
let h = vndf(wo, [a, a], [(k as f32 + 0.5) / N as f32, k.reverse_bits() as f32 / 4294967296.0]);
let c = wo[0] * h[0] + wo[1] * h[1] + wo[2] * h[2];
let z = 2.0 * c * h[2] - wo[2];
if z > 0.0 {
let g = g2(a * a, z, mu) * (1.0 + lambda(a * a, mu)) / N as f32;
for (sum, f) in cell.iter_mut().zip([1.0, (1.0 - c).clamp(0.0, 1.0).powi(5), dielectric(c)]) {
*sum += f * g;
}
}
}
}
// the mean of E over the cosines, 2 mu dmu with mu = y^2, a trapezoid between the nodes
let y = |j: usize| j as f32 / (STEPS - 1) as f32;
let at = |j: usize| 4.0 * row[j][0] * y(j).powi(3);
let mean = (1..STEPS).map(|j| (at(j - 1) + at(j)) / 2.0 / (STEPS - 1) as f32).sum::<f32>();
row.iter_mut().for_each(|c| c[3] = mean);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
/// Cases of tools/cycles-port's oracle (Cycles 6ea3d9bcd81a, built as C++): the two alphas, a cosine, wi, the disk's two
/// numbers; then D, G (with wi.z), lambda and the sampled normal.
#[test]
fn the_ggx_is_cycles() {
#[rustfmt::skip]
let cases: [([f32; 2], f32, [f32; 3], [f32; 2], [f32; 3], [f32; 3]); 3] = [
([0.030198643, 0.0263823215], 0.547724247, [0.16266492, -0.762519956, 0.626181662], [0.495889366, 0.548348844], [0.000591959222, 0.999115765, 0.000531673431], [-0.000647504407, 0.00159752904, 0.999998569]),
([0.982707202, 0.182275727], 0.108885549, [-0.725084424, 0.324529201, 0.607398808], [0.56473726, 0.590222061], [0.307646185, 0.187696591, 4.01351929], [-0.52829963, -0.00960596558, 0.849003613]),
([0.342305034, 0.509727001], 0.47010687, [-0.767907083, -0.492557466, 0.409519047], [0.999985695, 0.494606256], [0.0575702898, 0.817566216, 0.0943524837], [0.531567872, -0.846983373, 0.0074105612]),
];
for (a, c, wi, r, want, normal) in cases {
let a2 = a[0] * a[0];
for (got, want) in [d(a2, c), g2(a2, c, wi[2]), lambda(a2, c)].into_iter().zip(want) {
assert!((got - want).abs() <= (2e-5 * want.abs()).max(2e-6), "{got} for {want}");
}
let h = vndf(wi, a, r);
assert!(h.iter().zip(normal).all(|(g, w)| (g - w).abs() < 1e-4), "{h:?} for {normal:?}");
}
// the dielectric at eta 1.5 the kernel fixes, by its own closed forms: F0 at normal incidence and 1 at grazing
assert!(dielectric(1.0).abs() < 1e-5 && (dielectric(0.0) - 1.0).abs() < 1e-5);
}
/// A white lobe keeps all its light when it's smooth, loses some when rough, and its parts stay inside it.
#[test]
fn the_table_is_a_lobes_albedo() {
let t = table();
assert!((t[STEPS - 1][0] - 1.0).abs() < 0.01, "smooth, face on: {}", t[STEPS - 1][0]);
// at alpha 1, seen face on, D is 1/pi and G 2z/(1 + z): the albedo is 1 - ln 2
let rough = t[STEPS * STEPS - 1][0];
assert!((rough - (1.0 - std::f32::consts::LN_2)).abs() < 2e-3, "rough, face on: {rough}");
assert!(t.iter().all(|c| c[0] <= 1.002 && c[1] <= c[0] && c[2] <= c[0] && c[3] > 0.0 && c[3] <= 1.002));
}
}
@@ -4,32 +4,86 @@
//! systems/rt's from a Bevy render world; the kernel's WGSL (wgsl/diffuse.wgsl) is a module rt can include as it is.
//! A device without ray queries is refused with the reason, and the composition renders unbaked.
pub mod glossy;
#[cfg(test)]
mod tests;
use wgpu::util::DeviceExt;
/// What a triangle sends on: the share of light it reflects (diffuse) and the light it gives off, linear RGB.
#[derive(Clone, Copy, Debug, PartialEq)]
/// What a triangle sends on: its base colour (times its texture's, when it has one) and the light it gives off, linear RGB;
/// how much of it is a metal, how rough its glossy layers are, and the F0 of the dielectric layer over the rest (0: none,
/// and with no metal either it's Lambert).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Surface {
pub albedo: [f32; 3],
pub emission: [f32; 3],
pub metallic: f32,
pub roughness: f32,
pub f0: f32,
/// its texture's place in `World::textures`
pub texture: Option<u32>,
}
/// The world a bake traces: triangles in world space, each with its surface.
/// A colour texture: sRGB, 8 bits a channel (red in the low byte), top row first.
pub struct Image {
pub width: u32,
pub height: u32,
pub rgba: Vec<u32>,
}
/// The world a bake traces: triangles in world space, each with its surface; a UV a vertex (or none at all).
pub struct World<'a> {
pub positions: &'a [[f32; 3]],
pub triangles: &'a [[u32; 3]],
pub surfaces: &'a [Surface],
pub uvs: &'a [[f32; 2]],
pub textures: &'a [Image],
}
/// What's traced from: each texel's origin (BK2, already off its surface), its normal, and whether it's inside other
/// geometry (left at zero for BK4 to fill), and the offset each bounce leaves its surface by.
/// The sky: a panorama (its middle straight ahead, -Z) at its strength, turned counter-clockwise from above.
#[derive(Clone, Debug)]
pub struct Sky {
pub width: u32,
pub height: u32,
/// linear RGB, top row first
pub rgb: Vec<[f32; 3]>,
pub strength: f32,
pub rotation: f32,
}
impl Sky {
/// One light from everywhere.
pub fn even(rgb: [f32; 3]) -> Sky {
Sky { width: 1, height: 1, rgb: vec![rgb], strength: 1.0, rotation: 0.0 }
}
}
/// The sun: out at the texel (it stays live), in at every bounce after.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Sun {
/// toward it
pub dir: [f32; 3],
/// its irradiance on a surface facing it, linear RGB, in the sky's units
pub irradiance: [f32; 3],
/// half its disk's angle, radians
pub half_angle: f32,
}
/// A texel that starts only at its point (`Starts::open`).
pub const CENTRE: u32 = 1 << 16;
/// What's traced from: each texel's point (BK2, already off its surface) and normal; the two sides of its footprint,
/// and which of the 4 x 4 points over it are open (a bit each, row by row; `CENTRE` alone for its point only, 0 when it's
/// inside other geometry and left at zero for BK4 to fill); and the offset each bounce leaves its surface by.
pub struct Starts<'a> {
pub origin: &'a [[f32; 3]],
pub normal: &'a [[f32; 3]],
pub inside: &'a [bool],
pub sides: &'a [[[f32; 3]; 2]],
pub open: &'a [u32],
pub offset: f32,
}
#[derive(Clone, Copy, Debug)]
#[derive(Clone, Debug)]
pub struct Settings {
/// samples a texel
pub samples: u32,
@@ -37,13 +91,13 @@ pub struct Settings {
pub bounces: u32,
/// samples a texel in each pass: a pass short enough that the machine stays responsive
pub per_pass: u32,
/// the sky's light, linear RGB (the composition's <Environment> comes in BK3's next step)
pub sky: [f32; 3],
pub sky: Sky,
pub sun: Option<Sun>,
}
impl Default for Settings {
fn default() -> Self {
Self { samples: 512, bounces: 4, per_pass: 16, sky: [1.0; 3] }
Self { samples: 512, bounces: 4, per_pass: 16, sky: Sky::even([1.0; 3]), sun: None }
}
}
@@ -53,8 +107,15 @@ const CHUNK: u32 = 1 << 18;
/// The light reaching each texel (the mean its cosine-weighted rays bring back), in `from`'s order; inside texels 0.
pub fn trace(world: &World, from: &Starts, s: &Settings, progress: &mut dyn FnMut(u32, u32)) -> Result<Vec<[f32; 3]>, String> {
let n = from.origin.len();
if from.normal.len() != n || from.inside.len() != n || world.surfaces.len() != world.triangles.len() {
return Err("trace: the texels' origins, normals and inside marks, and the triangles' surfaces, must match".into());
if from.normal.len() != n || from.open.len() != n || from.sides.len() != n || world.surfaces.len() != world.triangles.len() {
return Err("trace: the texels' origins, normals, sides and open starts, and the triangles' surfaces, must match".into());
}
if s.sky.rgb.is_empty() || s.sky.rgb.len() != (s.sky.width * s.sky.height) as usize {
return Err("trace: the sky's picture doesn't match its size".into());
}
let textured = world.surfaces.iter().any(|s| s.texture.is_some());
if (textured && world.uvs.len() != world.positions.len()) || world.surfaces.iter().any(|s| s.texture.is_some_and(|t| t as usize >= world.textures.len())) {
return Err("trace: a textured surface needs its texture and a UV on every vertex".into());
}
if n == 0 || world.triangles.is_empty() {
return Ok(vec![[0.0; 3]; n]);
@@ -79,9 +140,27 @@ fn dispatch(device: &wgpu::Device, queue: &wgpu::Queue, world: &World, from: &St
let n = from.origin.len();
let tlas = accel(device, queue, world);
let vec4 = |v: [f32; 3], w: f32| [v[0], v[1], v[2], w];
let positions: Vec<[f32; 4]> = world.positions.iter().map(|p| vec4(*p, 1.0)).collect();
let surfaces: Vec<[f32; 4]> = world.surfaces.iter().flat_map(|s| [vec4(s.albedo, 0.0), vec4(s.emission, 0.0)]).collect();
let texels: Vec<[f32; 4]> = (0..n).flat_map(|i| [vec4(from.origin[i], from.inside[i] as u32 as f32), vec4(from.normal[i], 0.0)]).collect();
let mut uvs = world.uvs.to_vec();
uvs.resize(world.positions.len(), [0.0; 2]);
let positions: Vec<[f32; 4]> = world.positions.iter().zip(&uvs).map(|(p, uv)| vec4(*p, uv[0])).collect();
let vs: Vec<f32> = uvs.iter().map(|uv| uv[1]).collect();
let firsts: Vec<u32> = world.textures.iter().scan(0u32, |at, t| Some(std::mem::replace(at, *at + t.rgba.len() as u32))).collect();
let surfaces: Vec<[u32; 16]> = world.surfaces.iter().map(|s| {
let tex = s.texture.map_or([0; 4], |k| [1, firsts[k as usize], world.textures[k as usize].width, world.textures[k as usize].height]);
let mut row = [0u32; 16];
for k in 0..3 {
(row[k], row[4 + k]) = (s.albedo[k].to_bits(), s.emission[k].to_bits());
}
row[8..12].copy_from_slice(&tex);
row[12..15].copy_from_slice(&[s.metallic, s.roughness, s.f0].map(f32::to_bits));
row
}).collect();
let mut images: Vec<u32> = world.textures.iter().flat_map(|t| t.rgba.iter().copied()).collect();
if images.is_empty() {
images.push(0);
}
let sky: Vec<[f32; 4]> = s.sky.rgb.iter().map(|c| vec4(c.map(|x| x * s.sky.strength), 0.0)).chain(glossy::table()).collect();
let texels: Vec<[f32; 4]> = (0..n).flat_map(|i| [vec4(from.origin[i], f32::from_bits(from.open[i])), vec4(from.normal[i], 0.0), vec4(from.sides[i][0], 0.0), vec4(from.sides[i][1], 0.0)]).collect();
let storage = |label: &str, bytes: &[u8], usage: wgpu::BufferUsages| device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents: bytes, usage: wgpu::BufferUsages::STORAGE | usage });
let index: Vec<u32> = world.triangles.iter().flatten().copied().collect();
let bufs = [
@@ -91,24 +170,34 @@ fn dispatch(device: &wgpu::Device, queue: &wgpu::Queue, world: &World, from: &St
storage("lightbake texels", bytemuck::cast_slice(&texels), wgpu::BufferUsages::empty()),
storage("lightbake accum", &vec![0u8; n * 16], wgpu::BufferUsages::COPY_SRC),
];
let params = device.create_buffer(&wgpu::BufferDescriptor { label: Some("lightbake params"), size: 48, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
let src = format!("enable wgpu_ray_query;\n{}\n{}", include_str!("wgsl/diffuse.wgsl"), include_str!("wgsl/trace.wgsl"));
let more = [
storage("lightbake vs", bytemuck::cast_slice(&vs), wgpu::BufferUsages::empty()),
storage("lightbake textures", bytemuck::cast_slice(&images), wgpu::BufferUsages::empty()),
storage("lightbake sky", bytemuck::cast_slice(&sky), wgpu::BufferUsages::empty()),
];
let params = device.create_buffer(&wgpu::BufferDescriptor { label: Some("lightbake params"), size: 80, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
let src = format!("enable wgpu_ray_query;\n{}\n{}\n{}", include_str!("wgsl/diffuse.wgsl"), include_str!("wgsl/glossy.wgsl"), include_str!("wgsl/trace.wgsl"));
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("lightbake trace"), source: wgpu::ShaderSource::Wgsl(src.into()) });
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("lightbake trace"), layout: None, module: &module, entry_point: Some("main"), compilation_options: Default::default(), cache: None });
let mut entries = vec![wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::AccelerationStructure(&tlas) }];
entries.extend(bufs.iter().enumerate().map(|(k, b)| wgpu::BindGroupEntry { binding: k as u32 + 1, resource: b.as_entire_binding() }));
entries.push(wgpu::BindGroupEntry { binding: 6, resource: params.as_entire_binding() });
let all = bufs.iter().chain(std::iter::once(&params)).chain(&more);
entries.extend(all.enumerate().map(|(k, b)| wgpu::BindGroupEntry { binding: k as u32 + 1, resource: b.as_entire_binding() }));
let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("lightbake trace"), layout: &pipeline.get_bind_group_layout(0), entries: &entries });
let passes = s.samples.div_ceil(s.per_pass.max(1));
for pass in 0..passes {
let per = s.per_pass.max(1).min(s.samples - pass * s.per_pass.max(1));
for first in (0..n as u32).step_by(CHUNK as usize) {
let mut p = [0u32; 12];
for (k, v) in s.sky.iter().enumerate() {
p[k] = v.to_bits();
let mut p = [0u32; 20];
if let Some(sun) = &s.sun {
let l = sun.dir.iter().map(|x| x * x).sum::<f32>().sqrt();
for k in 0..3 {
(p[k], p[4 + k]) = ((sun.dir[k] / l).to_bits(), sun.irradiance[k].to_bits());
}
p[3] = sun.half_angle.cos().to_bits();
}
let end = (first + CHUNK).min(n as u32);
(p[4], p[5], p[6], p[7], p[8], p[9]) = (end, pass, per, s.bounces, from.offset.to_bits(), first);
(p[8], p[9], p[10], p[11], p[12], p[13]) = (end, pass * s.per_pass.max(1), per, s.bounces, from.offset.to_bits(), first);
(p[14], p[15], p[16]) = (s.sky.width, s.sky.height, s.sky.rotation.to_bits());
queue.write_buffer(&params, 0, bytemuck::cast_slice(&p));
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("lightbake pass") });
{
@@ -124,6 +213,11 @@ fn dispatch(device: &wgpu::Device, queue: &wgpu::Queue, world: &World, from: &St
}
let acc = read(device, queue, &bufs[4], n * 16)?;
let acc: &[[f32; 4]] = bytemuck::cast_slice(&acc);
// a pass the GPU dropped, or light that isn't a number, is an error here: never kept as a dark or a broken map
let wrong = acc.iter().zip(from.open).filter(|(a, open)| a[3] != if **open == 0 { 0.0 } else { s.samples as f32 } || !a.iter().all(|c| c.is_finite())).count();
if wrong > 0 {
return Err(format!("the light bake's trace came back wrong on {wrong} of {n} texels (not {} samples each, or light that isn't finite)", s.samples));
}
Ok(acc.iter().map(|a| if a[3] > 0.0 { [a[0] / a[3], a[1] / a[3], a[2] / a[3]] } else { [0.0; 3] }).collect())
}
@@ -162,6 +256,3 @@ fn read(device: &wgpu::Device, queue: &wgpu::Queue, buf: &wgpu::Buffer, size: us
let bytes = back.slice(..).get_mapped_range().map_err(|e| format!("the light bake's readback: {e}"))?.to_vec();
Ok(bytes)
}
#[cfg(test)]
mod tests;
+151
View File
@@ -0,0 +1,151 @@
use crate::glossy::{STEPS, d, dielectric, g2, table};
use crate::*;
// (a floor of 20 km puts its rays' starts within its own rounding at this offset, and they meet it)
const FLOOR: f32 = 400.0;
fn surface(base: f32, metallic: f32, roughness: f32, f0: f32) -> Surface {
Surface { albedo: [base; 3], metallic, roughness, f0, ..Surface::default() }
}
/// The light on a point half a metre over a wide floor, facing it, with a panel glowing 1 over it or not.
fn over_a_floor(floor: Surface, panel: bool, s: &Settings) -> f32 {
let mut p = vec![[-FLOOR, 0.0, -FLOOR], [-FLOOR, 0.0, 3.0 * FLOOR], [3.0 * FLOOR, 0.0, -FLOOR]];
let mut t = vec![[0, 1, 2]];
let mut surfaces = vec![floor];
if panel {
p.extend(PANEL);
t.extend([[3, 4, 5], [3, 5, 6]]);
surfaces.extend([Surface { emission: [1.0; 3], ..Surface::default() }; 2]);
}
let st = Starts { origin: &[[0.0, 0.5, 0.0]; 64], normal: &[[0.0, -1.0, 0.0]; 64], sides: &[[[0.0; 3]; 2]; 64], open: &[CENTRE; 64], offset: 1e-4 };
let l = trace(&World { positions: &p, triangles: &t, surfaces: &surfaces, uvs: &[], textures: &[] }, &st, s, &mut |_, _| {}).unwrap();
l.iter().map(|l| l[0]).sum::<f32>() / 64.0
}
const PANEL: [[f32; 3]; 4] = [[2.0, 4.0, -2.0], [6.0, 4.0, -2.0], [6.0, 4.0, 2.0], [2.0, 4.0, 2.0]];
const KINDS: [(&str, f32, f32, f32, f32); 5] = [("rough metal", 0.8, 1.0, 0.9, 0.0), ("smooth metal", 0.8, 1.0, 0.1, 0.0), ("plastic", 0.5, 0.0, 0.3, 0.04), ("half metal", 0.6, 0.5, 0.6, 0.04), ("chalk", 0.5, 0.0, 1.0, 0.0)];
/// What the kernel should send from wi to wo (its z the normal), the cosine included, after a turn of density `likely`.
fn sent(t: &[[f32; 4]], (_, base, metallic, rough, f0): (&str, f32, f32, f32, f32), likely: f32, wo: [f32; 3], wi: [f32; 3]) -> f32 {
let mu = wo[2];
if wi[2] <= 0.0 || mu <= 0.0 {
return 0.0;
}
if metallic == 0.0 && f0 == 0.0 {
return base * wi[2] / std::f32::consts::PI;
}
let a = (rough * rough).max(0.5 * (1.0 - likely).max(0.0).sqrt());
let at = [mu.sqrt(), a.sqrt()].map(|x| x.min(1.0) * (STEPS - 1) as f32);
let [j, i] = at.map(|x| (x as usize).min(STEPS - 2));
let (f, g) = (at[0] - j as f32, at[1] - i as f32);
let cell = |k: usize| (t[i * STEPS + j][k] * (1.0 - f) + t[i * STEPS + j + 1][k] * f) * (1.0 - g) + (t[(i + 1) * STEPS + j][k] * (1.0 - f) + t[(i + 1) * STEPS + j + 1][k] * f) * g;
let mix = |a: f32, b: f32, s: f32| a + (b - a) * s;
let kept = |fss: f32| 1.0 + fss * cell(3) / (1.0 - fss * (1.0 - cell(3))) * (1.0 - cell(0)) / cell(0);
let h: [f32; 3] = std::array::from_fn(|k| wo[k] + wi[k]);
let l = h.iter().map(|x| x * x).sum::<f32>().sqrt();
let c = (0..3).map(|k| wo[k] * h[k] / l).sum::<f32>();
let coat = if f0 > 0.0 { (1.0 - metallic) * kept(mix(f0, 1.0, (0.0894977 - 0.04) / 0.96)) } else { 0.0 };
let diffuse = base * (1.0 - metallic - coat * (f0 * cell(0) + (1.0 - f0) * cell(2))).max(0.0);
let fresnel = metallic * kept(mix(base, 1.0, 1.0 / 21.0)) * mix(base, 1.0, (1.0 - c).clamp(0.0, 1.0).powi(5)) + coat * mix(f0, 1.0, dielectric(c));
diffuse * wi[2] / std::f32::consts::PI + fresnel * d(a * a, h[2] / l) * g2(a * a, mu, wi[2]) / (4.0 * mu)
}
/// The mean over the point's own rays of `at` (the ray from the floor up to the point, its cosine over pi, where it hit).
fn over_rays(at: impl Fn([f32; 3], f32, [f32; 3], u32) -> f32) -> f32 {
const N: u32 = 1 << 20;
let total: f64 = (0..N).map(|k| {
let (u, v) = ((k as f32 + 0.5) / N as f32, k.reverse_bits() as f32 / 4294967296.0);
let (r, phi, z) = (u.sqrt(), std::f32::consts::TAU * v, (1.0 - u).sqrt().max(1e-3));
let wo = [r * phi.cos(), r * phi.sin(), z];
at(wo, z / std::f32::consts::PI, [-wo[0] * 0.5 / z, -wo[1] * 0.5 / z, 0.0], k) as f64
}).sum();
(total / N as f64) as f32
}
/// Whatever the surface, white ones send on all they get: a point over one sees the sky's 1.
#[test]
fn white_glossy_surfaces_send_on_all_their_light() {
let s = Settings { samples: 4096, per_pass: 64, bounces: 4, ..Settings::default() };
let mut off = 0;
for (name, metallic, f0) in [("metal", 1.0, 0.0), ("dielectric", 0.0, 0.04), ("half", 0.5, 0.04)] {
for rough in [0.1, 0.5, 0.75, 1.0] {
let l = over_a_floor(surface(1.0, metallic, rough, f0), false, &s);
println!("{name} of roughness {rough}: {l:.4} for 1");
off += ((l - 1.0).abs() >= 0.01) as u32;
}
}
assert_eq!(off, 0, "white surfaces off by 1% or more");
}
/// The sun off a floor, against the same light summed on the CPU with the functions held to Cycles' (glossy.rs).
#[test]
fn the_suns_glint_is_the_lobes_own() {
let t = table();
let toward = [0.6f32, 0.8, 0.0];
let sun = Sun { dir: toward, irradiance: [1.0; 3], half_angle: 1e-3 };
let s = Settings { samples: 16384, per_pass: 64, bounces: 1, sky: Sky::even([0.0; 3]), sun: Some(sun) };
for kind in KINDS {
let got = over_a_floor(surface(kind.1, kind.2, kind.3, kind.4), false, &s);
// the floor's frame here: x, z of the world, then up
let want = over_rays(|wo, likely, _, _| sent(&t, kind, likely, wo, [toward[0], toward[2], toward[1]]));
println!("sun, {}: {got:.5} for {want:.5}", kind.0);
assert!((got / want - 1.0).abs() < 0.01, "{}: {got} for {want}", kind.0);
}
}
/// A glowing panel found by the paths' own turns, against the same light summed over the panel.
#[test]
fn a_panels_reflection_is_found_by_its_turns() {
let t = table();
let s = Settings { samples: 16384, per_pass: 64, bounces: 2, sky: Sky::even([0.0; 3]), sun: None };
let mut off = 0;
for kind in KINDS {
let got = over_a_floor(surface(kind.1, kind.2, kind.3, kind.4), true, &s);
let want = over_rays(|wo, likely, p, k| {
let [u, v] = [0.754_877_666_246_693, 0.569_840_290_998_053].map(|g: f64| (k as f64 * g).fract() as f32);
let to = [PANEL[0][0] + 4.0 * u - p[0], PANEL[0][2] + 4.0 * v - p[1], PANEL[0][1]];
let r2 = to.iter().map(|x| x * x).sum::<f32>();
let wi = to.map(|x| x / r2.sqrt());
sent(&t, kind, likely, wo, wi) * wi[2] * 16.0 / r2
});
println!("panel, {}: {got:.5} for {want:.5}", kind.0);
off += ((got / want - 1.0).abs() >= 0.015) as u32;
}
assert_eq!(off, 0, "kinds off by 1.5% or more");
}
/// The share of rays that meet the plane they leave, off a tilted triangle `far` m from the origin, at an offset of `rel`
/// of that: from the texels themselves, and from where a bounce lands (a point over it, the plane half grey).
fn meets_itself(far: f32, rel: f32) -> [f32; 2] {
let [u, v] = [[0.64f32, 0.48, 0.6], [-0.6, 0.8, 0.0]];
let n = [-0.48f32, -0.36, 0.8];
let at = |a: f32, b: f32, h: f32| -> [f32; 3] { std::array::from_fn(|k| [0.6, 0.64, 0.48][k] * far + (u[k] * a + v[k] * b + n[k] * h) * far) };
let p = [at(-0.4, -0.4, 0.0), at(1.0, -0.4, 0.0), at(-0.4, 1.0, 0.0)];
let hash = |k: u32| (k.wrapping_mul(0x9e37_79b9) >> 8) as f32 / 16777216.0;
let origin: Vec<[f32; 3]> = (0..4096).map(|k| at(0.3 * hash(k) - 0.2, 0.3 * hash(k + 7919) - 0.2, rel)).collect();
let over: Vec<[f32; 3]> = (0..4096).map(|k| at(0.1 * hash(k) - 0.1, 0.1 * hash(k + 7919) - 0.1, 1e-3)).collect();
let run = |from: &[[f32; 3]], normal: [f32; 3], albedo: f32, bounces: u32| {
let m = from.len();
let st = Starts { origin: from, normal: &vec![normal; m], sides: &vec![[[0.0; 3]; 2]; m], open: &vec![CENTRE; m], offset: rel * far };
let l = trace(&World { positions: &p, triangles: &[[0, 1, 2]], surfaces: &[Surface { albedo: [albedo; 3], ..Surface::default() }], uvs: &[], textures: &[] }, &st, &Settings { samples: 256, bounces, ..Settings::default() }, &mut |_, _| {}).unwrap();
l.iter().map(|l| l[0]).sum::<f32>() / m as f32
};
let direct = 1.0 - run(&origin, n, 0.0, 1);
// half grey once: 0.5 of the sky; every further meeting halves it
let bounced = 1.0 - run(&over, n.map(|c| -c), 0.5, 3) / 0.5;
[direct, bounced]
}
#[test]
fn a_surface_never_meets_itself() {
let mut off = 0;
for far in [1.0, 15.0, 300.0, 5000.0] {
for rel in [1e-5, 1e-6, 3e-7, 1e-7] {
let [direct, bounced] = meets_itself(far, rel);
println!("{far} m, offset {rel:e} of it: {direct:.5} of the texels' rays, {bounced:.5} of the bounces'");
off += (rel >= 1e-6 && (direct.abs() > 1e-3 || bounced.abs() > 5e-3)) as u32;
}
}
assert_eq!(off, 0);
}
+120
View File
@@ -0,0 +1,120 @@
// The glossy layers of a surface (docs/bake.feature BK3), after Cycles' Principled: a metal (GGX, F82 with a white edge
// tint, which is Schlick) and a dielectric layer of IOR 1.5 over Lambert. The GGX, its sampling and the Fresnels are
// Cycles' (github.com/blender/cycles 6ea3d9bcd81a, kernel/closure/bsdf_microfacet.h, bsdf_util.h and
// kernel/sample/mapping.h, BSD-3-Clause: see NOTICE), written here until tools/cycles-port is on main. What a single
// scatter loses is given back from glossy.rs's table. It needs raea_layers_at(i), that table's cells, STEPS by STEPS:
// by roughness and the cosine's square root: the albedo of a white lobe
// (E), its Schlick part, its dielectric part, and E's mean over the cosines.
const RAEA_STEPS: i32 = 32;
fn raea_ggx_lambda(a2: f32, c: f32) -> f32 {
return 0.5 * (sqrt(1.0 + a2 * max(1.0 / (c * c) - 1.0, 0.0)) - 1.0);
}
fn raea_ggx_d(a2: f32, c: f32) -> f32 {
let c2 = min(c * c, 1.0);
let q = 1.0 - c2 + a2 * c2;
return a2 / (3.141592654 * q * q);
}
// A microfacet normal from the ones visible from w (Heitz 2018), in the shading frame (z the normal).
fn raea_ggx_sample(w: vec3<f32>, a: f32, r: vec2<f32>) -> vec3<f32> {
let v = normalize(vec3<f32>(a * w.x, a * w.y, w.z));
let l2 = v.x * v.x + v.y * v.y;
var t1 = vec3<f32>(1.0, 0.0, 0.0);
if (l2 > 1e-7) {
t1 = vec3<f32>(-v.y, v.x, 0.0) * inverseSqrt(l2);
}
let p = 2.0 * r - 1.0;
var rad = 0.0;
var phi = 0.0;
if (p.x * p.x > p.y * p.y) {
rad = p.x;
phi = 0.785398163 * (p.y / p.x);
} else if (p.y != 0.0) {
rad = p.y;
phi = 1.570796327 - 0.785398163 * (p.x / p.y);
}
let x = rad * cos(phi);
let y = mix(sqrt(max(1.0 - x * x, 0.0)), rad * sin(phi), 0.5 * (1.0 + v.z));
let h = x * t1 + y * cross(v, t1) + sqrt(max(1.0 - x * x - y * y, 0.0)) * v;
return normalize(vec3<f32>(a * h.x, a * h.y, max(0.0, h.z)));
}
// Where a dielectric of IOR 1.5 stands between its F0 and 1 at this cosine (Cycles' generalized Schlick, exponent < 0).
fn raea_dielectric(cosine: f32) -> f32 {
let c = abs(cosine);
let g = sqrt(1.25 + c * c);
let a = (g - c) / (g + c);
let b = (c * (g + c) - 1.0) / (c * (g - c) + 1.0);
return clamp((0.5 * a * a * (1.0 + b * b) - 0.04) / 0.96, 0.0, 1.0);
}
fn raea_layer(rough: f32, mu: f32) -> vec4<f32> {
let at = clamp(vec2<f32>(sqrt(mu), rough), vec2<f32>(0.0), vec2<f32>(1.0)) * f32(RAEA_STEPS - 1);
let i = min(vec2<i32>(at), vec2<i32>(RAEA_STEPS - 2));
let f = at - vec2<f32>(i);
let k = i.y * RAEA_STEPS + i.x;
return mix(mix(raea_layers_at(k), raea_layers_at(k + 1), f.x), mix(raea_layers_at(k + RAEA_STEPS), raea_layers_at(k + RAEA_STEPS + 1), f.x), f.y);
}
// A surface seen from one direction: its lobes' weights, and how often the glossy ones are sampled.
struct Lobes {
diffuse: vec3<f32>,
metal: vec3<f32>,
base: vec3<f32>,
f0: f32,
coat: f32,
a: f32,
p: f32,
}
// What the compensation multiplies a single scatter by (1 + Cycles' Fms times what's missing of the lobe).
fn raea_kept(fss: vec3<f32>, t: vec4<f32>) -> vec3<f32> {
return 1.0 + fss * t.w / (1.0 - fss * (1.0 - t.w)) * (1.0 - t.x) / t.x;
}
// `gloss`: metallic, roughness, the dielectric's F0 (0: no such layer). `a_least`: the least alpha (filter glossy).
fn raea_lobes(base: vec3<f32>, gloss: vec3<f32>, a_least: f32, mu: f32) -> Lobes {
var l: Lobes;
l.base = base;
l.diffuse = base * (1.0 - gloss.x);
if (gloss.x <= 0.0 && gloss.z <= 0.0) {
return l;
}
l.a = max(max(gloss.y * gloss.y, a_least), 0.002);
l.f0 = gloss.z;
let t = raea_layer(sqrt(l.a), mu);
l.metal = gloss.x * raea_kept(mix(base, vec3<f32>(1.0), 1.0 / 21.0), t);
var seen = l.metal * (base * t.x + (1.0 - base) * t.y);
if (gloss.z > 0.0) {
// 0.05156: Cycles' average dielectric Fresnel at 1.5 (fresnel_dielectric_Fss) between F0 and 1
l.coat = (1.0 - gloss.x) * raea_kept(vec3<f32>(mix(gloss.z, 1.0, 0.05156)), t).x;
let c = l.coat * (gloss.z * t.x + (1.0 - gloss.z) * t.z);
l.diffuse = base * max(1.0 - gloss.x - c, 0.0);
seen = seen + c;
}
let g = dot(seen, vec3<f32>(1.0));
l.p = g / max(g + dot(l.diffuse, vec3<f32>(1.0)), 1e-6);
return l;
}
// The light sent from wi to wo, cosine included, and (w) the density with which raea_lobes_sample picks wi.
fn raea_lobes_eval(l: Lobes, wo: vec3<f32>, wi: vec3<f32>) -> vec4<f32> {
if (wi.z <= 0.0) {
return vec4<f32>(0.0);
}
let d = wi.z / 3.141592654;
if (l.p <= 0.0) {
return vec4<f32>(l.diffuse * d, d);
}
let h = normalize(wo + wi);
let c = dot(wo, h);
let a2 = l.a * l.a;
let lo = raea_ggx_lambda(a2, wo.z);
let one = raea_ggx_d(a2, h.z) / (4.0 * wo.z);
let s5 = pow(clamp(1.0 - c, 0.0, 1.0), 5.0);
let f = l.metal * mix(l.base, vec3<f32>(1.0), s5) + l.coat * mix(l.f0, 1.0, raea_dielectric(c));
return vec4<f32>(l.diffuse * d + f * (one / (1.0 + lo + raea_ggx_lambda(a2, wi.z))), l.p * one / (1.0 + lo) + (1.0 - l.p) * d);
}
+216
View File
@@ -0,0 +1,216 @@
// The light that bounces, per texel (docs/bake.feature BK3): paths from the texel's origin through the model's own
// triangles (one BLAS, one TLAS) by wgpu's ray queries. What a texel keeps is the mean light its cosine-weighted rays
// bring back, so the lightmap times a surface's albedo is the light it sends on. At each hit the surface's emission
// is added and the path goes on by its BSDF (Lambert, diffuse.wgsl, under the glossy layers of glossy.wgsl); a miss sees
// the sky; after the second bounce Russian roulette ends paths by their weight, unbiased. As Cycles does by default
// (filter glossy 1), a lobe is no sharper than its path's least likely turn: a caustic is blurred, not a firefly. Passes add to `accum` (rgb, samples).
struct Params {
// toward the sun (w: the cosine of its half angle) and its irradiance facing it, all zero when there's none
sun_dir: vec4<f32>,
sun: vec4<f32>,
count: u32,
// the first sample of this pass (the random numbers are a sample's own)
base: u32,
per_pass: u32,
bounces: u32,
offset: f32,
// the first texel of this dispatch (a bake's texels go in chunks)
first: u32,
sky_w: u32,
sky_h: u32,
rotation: f32,
_pad0: f32,
_pad1: f32,
_pad2: f32,
}
// tex: 1 when textured, then the texture's first word, width and height; gloss: metallic, roughness, the dielectric's F0
struct Surface {
albedo: vec4<f32>,
emission: vec4<f32>,
tex: vec4<u32>,
gloss: vec4<f32>,
}
@group(0) @binding(0) var tlas: acceleration_structure;
// each vertex's place, and its u in w
@group(0) @binding(1) var<storage, read> positions: array<vec4<f32>>;
@group(0) @binding(2) var<storage, read> indices: array<u32>;
@group(0) @binding(3) var<storage, read> surfaces: array<Surface>;
// per texel: its point off the surface (w: which starts are open, see `start`), the hemisphere's normal, and its
// footprint's two sides
@group(0) @binding(4) var<storage, read> texels: array<vec4<f32>>;
@group(0) @binding(5) var<storage, read_write> accum: array<vec4<f32>>;
@group(0) @binding(6) var<uniform> params: Params;
// each vertex's v
@group(0) @binding(7) var<storage, read> vs: array<f32>;
// the textures one after another, sRGB, 8 bits a channel
@group(0) @binding(8) var<storage, read> images: array<u32>;
// the panorama, top row first, its light already at its strength; then glossy.rs's table
@group(0) @binding(9) var<storage, read> sky: array<vec4<f32>>;
fn raea_layers_at(k: i32) -> vec4<f32> {
return sky[params.sky_w * params.sky_h + u32(k)];
}
// The nearest hit. Its own function: a ray_query declared in a loop is zeroed again each turn, which naga writes for
// Metal as an assignment Metal's intersection_query deletes.
fn nearest(o: vec3<f32>, d: vec3<f32>) -> RayIntersection {
var rq: ray_query;
rayQueryInitialize(&rq, tlas, RayDesc(0u, 0xffu, 0.0, 1.0e30, o, d));
while (rayQueryProceed(&rq)) {}
return rayQueryGetCommittedIntersection(&rq);
}
fn blocked(o: vec3<f32>, d: vec3<f32>) -> bool {
var rq: ray_query;
rayQueryInitialize(&rq, tlas, RayDesc(RAY_FLAG_TERMINATE_ON_FIRST_HIT, 0xffu, 0.0, 1.0e30, o, d));
while (rayQueryProceed(&rq)) {}
return rayQueryGetCommittedIntersection(&rq).kind != RAY_QUERY_INTERSECTION_NONE;
}
// The panorama as raea draws it (systems/environment): its middle straight ahead (-Z), its right half to +X, turned
// counter-clockwise from above by `rotation`; bilinear, wrapping round.
fn sky_at(d: vec3<f32>) -> vec3<f32> {
let size = vec2<f32>(f32(params.sky_w), f32(params.sky_h));
// straight up or down has no longitude, and atan2(0, 0) may be NaN: any will do
var lon = 0.0;
if (d.x != 0.0 || d.z != 0.0) {
lon = atan2(d.x, -d.z);
}
let u = fract(0.5 + (lon + params.rotation) / 6.283185307);
let v = acos(clamp(d.y, -1.0, 1.0)) / 3.141592654;
let at = vec2<f32>(u, v) * size - 0.5;
let f = fract(at);
let i = vec2<i32>(floor(at));
let w = i32(params.sky_w);
let x0 = u32((i.x + w) % w);
let x1 = u32((i.x + 1 + w) % w);
let y0 = u32(clamp(i.y, 0, i32(params.sky_h) - 1)) * params.sky_w;
let y1 = u32(clamp(i.y + 1, 0, i32(params.sky_h) - 1)) * params.sky_w;
return mix(mix(sky[y0 + x0].rgb, sky[y0 + x1].rgb, f.x), mix(sky[y1 + x0].rgb, sky[y1 + x1].rgb, f.x), f.y);
}
// A texture's colour at uv, linear, its nearest texel, repeating.
fn image_at(tex: vec4<u32>, uv: vec2<f32>) -> vec3<f32> {
let q = fract(uv);
let x = min(u32(q.x * f32(tex.z)), tex.z - 1u);
let y = min(u32(q.y * f32(tex.w)), tex.w - 1u);
let c = unpack4x8unorm(images[tex.y + y * tex.z + x]).rgb;
return select(pow((c + 0.055) / 1.055, vec3<f32>(2.4)), c / 12.92, c <= vec3<f32>(0.04045));
}
// Where a sample starts: one of the texel's 4 x 4 points, the open ones in turn (Cycles jitters its samples over the
// texel too: a ledge narrower than a texel is half of it, not all or nothing). Bit 16 alone is the centre.
fn start(i: u32, at: vec3<f32>, open: u32, turn: u32) -> vec3<f32> {
var left = open & 0xffffu;
if (left == 0u) {
return at;
}
for (var k = turn % countOneBits(left); k > 0u; k = k - 1u) {
left = left & (left - 1u);
}
let c = firstTrailingBit(left);
let q = (vec2<f32>(f32(c % 4u), f32(c / 4u)) + 0.5) / 4.0 - 0.5;
return at + texels[4u * i + 2u].xyz * q.x + texels[4u * i + 3u].xyz * q.y;
}
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let i = params.first + gid.x;
if (i >= params.count) {
return;
}
let at = texels[4u * i];
let open = bitcast<u32>(at.w);
if (open == 0u) {
return;
}
let n0 = texels[4u * i + 1u].xyz;
var sum = vec3<f32>(0.0);
for (var s = 0u; s < params.per_pass; s = s + 1u) {
var rng = raea_hash(i * 0x9e3779b9u ^ raea_hash(params.base + s));
var o = start(i, at.xyz, open, params.base + s + raea_hash(i));
var n = n0;
var weight = vec3<f32>(1.0);
var light = vec3<f32>(0.0);
var d = raea_diffuse_sample(n, vec2<f32>(raea_rand(&rng), raea_rand(&rng)));
var likely = dot(n, d) / 3.141592654;
for (var b = 0u; b < params.bounces; b = b + 1u) {
let hit = nearest(o, d);
if (hit.kind == RAY_QUERY_INTERSECTION_NONE) {
light = light + weight * sky_at(d);
break;
}
let p = hit.primitive_index;
let srf = surfaces[p];
light = light + weight * srf.emission.rgb;
let a = positions[indices[3u * p]].xyz;
let bb = positions[indices[3u * p + 1u]].xyz;
let c = positions[indices[3u * p + 2u]].xyz;
var ng = normalize(cross(bb - a, c - a));
if (dot(ng, d) > 0.0) {
ng = -ng;
}
let w = hit.barycentrics;
o = a * (1.0 - w.x - w.y) + bb * w.x + c * w.y + ng * params.offset;
n = ng;
var albedo = srf.albedo.rgb;
if (srf.tex.x == 1u) {
let i0 = indices[3u * p];
let i1 = indices[3u * p + 1u];
let i2 = indices[3u * p + 2u];
let k = 1.0 - w.x - w.y;
albedo = albedo * image_at(srf.tex, vec2<f32>(positions[i0].w * k + positions[i1].w * w.x + positions[i2].w * w.y, vs[i0] * k + vs[i1] * w.x + vs[i2] * w.y));
}
let x = normalize(cross(n, select(vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(1.0, 0.0, 0.0), abs(n.x) < 0.9)));
let frame = mat3x3<f32>(x, cross(n, x), n);
var wo = -d * frame;
wo.z = max(wo.z, 1e-4);
let lobes = raea_lobes(albedo, srf.gloss.xyz, 0.5 * sqrt(max(0.0, 1.0 - likely)), wo.z);
// the sun at the hit (never at the texel: its direct light stays live), from a point of its disk
let toward = params.sun_dir.xyz;
let facing = dot(n, toward);
if (params.sun_dir.w > 0.0 && facing > 0.0) {
let z = 1.0 - raea_rand(&rng) * (1.0 - params.sun_dir.w);
let phi = 6.283185307 * raea_rand(&rng);
let r = sqrt(max(0.0, 1.0 - z * z));
let sa = select(vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(1.0, 0.0, 0.0), abs(toward.x) < 0.9);
let st = normalize(cross(toward, sa));
let sd = normalize(st * (r * cos(phi)) + cross(toward, st) * (r * sin(phi)) + toward * z);
if (!blocked(o, sd)) {
light = light + weight * params.sun.rgb * raea_lobes_eval(lobes, wo, sd * frame).rgb;
}
}
let u = vec2<f32>(raea_rand(&rng), raea_rand(&rng));
if (lobes.p <= 0.0) {
d = raea_diffuse_sample(n, u);
weight = weight * lobes.diffuse;
likely = min(likely, dot(n, d) / 3.141592654);
} else {
if (raea_rand(&rng) < lobes.p) {
d = reflect(-wo, raea_ggx_sample(wo, lobes.a, u));
} else {
d = raea_diffuse_sample(vec3<f32>(0.0, 0.0, 1.0), u);
}
let f = raea_lobes_eval(lobes, wo, d);
if (f.w <= 0.0) {
break;
}
weight = weight * f.rgb / f.w;
likely = min(likely, f.w);
d = normalize(frame * d);
}
if (b >= 2u) {
let q = min(max(weight.r, max(weight.g, weight.b)), 1.0);
if (raea_rand(&rng) >= q) {
break;
}
weight = weight / q;
}
}
sum = sum + light;
}
accum[i] = accum[i] + vec4<f32>(sum, f32(params.per_pass));
}
+155
View File
@@ -0,0 +1,155 @@
// The colour a procedural surface draws (lib.rs), as a module with no bindings, imports, stages or derivatives, so a
// fragment shader and a compute kernel can both take it (docs/bake.feature BK3): what a pixel knows from its screen
// derivatives comes in as an argument. NOT YET USED: procmat.wesl still has its own copy, and takes this one (the copy
// deleted) in the commit that compiles it.
struct Proc {
a: vec4<f32>,
b: vec4<f32>,
gap_color: vec4<f32>,
dust_color: vec4<f32>,
dirt_color: vec4<f32>,
// kind, scale, rough_a, rough_b
k: vec4<f32>,
// bump, seed, tile_x, tile_y
t: vec4<f32>,
// gap, dust, dirt, edges
w: vec4<f32>,
}
fn proc_hash(p: vec3<f32>) -> f32 {
let q = fract(p * 0.3183099 + vec3(0.1, 0.2, 0.3));
let r = q * 17.0;
return fract(r.x * r.y * r.z * (r.x + r.y + r.z));
}
fn proc_vnoise(p: vec3<f32>) -> f32 {
let i = floor(p);
let f = fract(p);
let u = f * f * (3.0 - 2.0 * f);
let a = mix(mix(proc_hash(i), proc_hash(i + vec3(1.0, 0.0, 0.0)), u.x), mix(proc_hash(i + vec3(0.0, 1.0, 0.0)), proc_hash(i + vec3(1.0, 1.0, 0.0)), u.x), u.y);
let b = mix(mix(proc_hash(i + vec3(0.0, 0.0, 1.0)), proc_hash(i + vec3(1.0, 0.0, 1.0)), u.x), mix(proc_hash(i + vec3(0.0, 1.0, 1.0)), proc_hash(i + vec3(1.0, 1.0, 1.0)), u.x), u.y);
return mix(a, b, u.z);
}
fn proc_fbm(p: vec3<f32>) -> f32 {
var s = 0.0;
var w = 0.5;
var q = p;
for (var k = 0; k < 5; k++) {
s += w * proc_vnoise(q);
q = q * 2.03 + vec3(1.7, 9.2, 3.1);
w *= 0.5;
}
return s / 0.96875;
}
// the face's own plane: the two axes across the dominant normal (a wall's x-y, a floor's x-z)
fn proc_plane(p: vec3<f32>, n: vec3<f32>) -> vec2<f32> {
let a = abs(n);
if (a.y >= a.x && a.y >= a.z) { return p.xz; }
if (a.x >= a.z) { return vec2(p.z, p.y); }
return p.xy;
}
// (mix between a and b, gap mask, height 0..1); duv: how much of the face's plane (proc_plane) a pixel or a texel covers
fn proc_pattern(pm: Proc, p: vec3<f32>, n: vec3<f32>, duv: vec2<f32>) -> vec3<f32> {
let kind = i32(pm.k.x + 0.5);
let q = p / max(pm.k.y, 1e-4) + vec3(pm.t.y * 17.3);
let uv = proc_plane(p, n);
// wood: rings round the local y axis, wandering, and fine grain along it
if (kind == 1) {
let r = length(q.xz + vec2(proc_fbm(q * 0.4), proc_fbm(q * 0.4 + 7.0)) * 0.6) * 4.0;
let ring = smoothstep(0.0, 0.6, fract(r)) * (1.0 - smoothstep(0.75, 1.0, fract(r)));
let grain = proc_vnoise(vec3(q.x * 30.0, q.y * 1.5, q.z * 30.0));
let m = clamp(ring * 0.75 + grain * 0.35, 0.0, 1.0);
return vec3(m, 0.0, 0.3 * ring + 0.2 * grain);
}
// marble: sharp veins through soft clouding
if (kind == 2) {
let v = pow(1.0 - abs(sin(q.x * 2.0 + q.y * 0.7 + proc_fbm(q * 0.8) * 7.0)), 10.0);
let cloud = proc_fbm(q * 0.5) * 0.3;
return vec3(clamp(v + cloud, 0.0, 1.0), 0.0, 0.05 * v);
}
// stone / concrete: mottled, pitted, speckled
if (kind == 3) {
let m = proc_fbm(q);
let pits = smoothstep(0.78, 0.84, proc_vnoise(q * 9.0));
let speck = step(0.93, proc_hash(floor(q * 30.0)));
return vec3(clamp(m * 0.8 + speck * 0.4, 0.0, 1.0), pits, m * 0.6 - pits * 0.5);
}
// brick (running bond) and tiles: cells on the face's plane with gaps between, each cell its own shade
if (kind == 4 || kind == 5) {
let size = vec2(max(pm.t.z, 1e-3), max(pm.t.w, 1e-3));
var c = uv / size;
let row = floor(c.y);
if (kind == 4) { c.x += 0.5 * (row - 2.0 * floor(row / 2.0)); }
let id = floor(c);
let f = fract(c);
let g = vec2(pm.w.x) / size;
let edge = min(min(f.x, 1.0 - f.x) / max(g.x, 1e-4), min(f.y, 1.0 - f.y) / max(g.y, 1e-4));
let gap = 1.0 - smoothstep(0.5, 1.0, edge);
let shade = proc_hash(vec3(id, pm.t.y)) * 0.7 + proc_fbm(q * 2.0) * 0.3;
let bevel = smoothstep(0.5, 2.0, edge);
return vec3(shade, gap, bevel * (0.8 + 0.2 * proc_fbm(q * 3.0)));
}
// fabric: a plain weave
if (kind == 6) {
let f = uv / max(pm.k.y, 1e-4) * 6.2831;
let warp = 0.5 + 0.5 * sin(f.x) * sign(sin(f.y * 0.5));
let weft = 0.5 + 0.5 * sin(f.y) * sign(sin(f.x * 0.5 + 1.57));
// threads finer than a pixel fade to the weave's mean shade, so a distant sofa doesn't shimmer in moire
let far = smoothstep(0.8, 2.5, length(duv) / max(pm.k.y, 1e-4) * 6.2831);
let m = mix(max(warp, weft), 0.72, far);
return vec3(clamp(m * 0.6 + proc_fbm(q * 0.3) * 0.4, 0.0, 1.0), 0.0, m * (1.0 - far));
}
// brushed metal: long fine streaks along the face
if (kind == 7) {
let sy = uv.y / max(pm.k.y, 1e-4) * 60.0;
let s = mix(proc_vnoise(vec3(uv.x / max(pm.k.y, 1e-4) * 0.4, sy, pm.t.y)), 0.5, smoothstep(0.5, 1.5, duv.y / max(pm.k.y, 1e-4) * 60.0));
return vec3(s * 0.6 + proc_fbm(q * 0.2) * 0.4, 0.0, s * 0.15);
}
// plaster: soft trowel marks and fine bumps
if (kind == 8) {
let m = proc_fbm(q * 0.6);
let fine = proc_vnoise(q * 18.0);
return vec3(m, 0.0, m * 0.5 + fine * 0.2);
}
// noise: two colours by fractal noise
let m = proc_fbm(q);
return vec3(m, 0.0, m * 0.5);
}
// Where a surface is drawn: its point and normal in the mesh's own space and the world's, and how fast its normal turns
// (1 / metres: the raster's fwidth of the normal over the position's; a ray hit's, over its triangle's edges).
struct ProcAt {
p: vec3<f32>,
wp: vec3<f32>,
wn: vec3<f32>,
curve: f32,
}
// (colour, roughness) of the pattern with its use over it: dust on what faces up; dirt in the gaps, the hollows,
// undersides and along the floor line; edges worn lighter and smoother where hands and feet go
fn proc_drawn(pm: Proc, pat: vec3<f32>, at: ProcAt) -> vec4<f32> {
let t = pat.x;
let gap = pat.y;
var c = mix(pm.a.rgb, pm.b.rgb, t);
var rough = mix(pm.k.z, pm.k.w, t);
c = mix(c, pm.gap_color.rgb, gap);
rough = mix(rough, 0.95, gap);
let wq = at.p / max(pm.k.y, 1e-4) * 0.7 + vec3(pm.t.y * 3.1);
let up = smoothstep(0.55, 0.95, at.wn.y);
let dust = clamp(up * pm.w.y * (0.55 + 0.45 * proc_fbm(wq * 2.0 + 30.0)), 0.0, 0.9);
c = mix(c, pm.dust_color.rgb, dust);
rough = mix(rough, 0.95, dust);
let floor_line = 1.0 - smoothstep(0.0, 0.25, at.wp.y);
let under = clamp(-at.wn.y, 0.0, 1.0);
let dirt = clamp((gap * 0.8 + under * 0.5 + floor_line * 0.7 + smoothstep(0.6, 0.9, proc_fbm(wq * 0.8 + 50.0)) * 0.4) * pm.w.z, 0.0, 0.85) * (0.6 + 0.4 * proc_fbm(wq * 3.0 + 70.0));
c = mix(c, pm.dirt_color.rgb, dirt);
rough = mix(rough, 0.9, dirt);
let edge = smoothstep(25.0, 90.0, at.curve) * pm.w.w * (0.5 + 0.5 * proc_fbm(wq * 4.0 + 90.0));
c = mix(c, min(c * 1.35 + vec3(0.04), vec3(1.0)), edge);
rough = mix(rough, rough * 0.6, edge);
return vec4(c, rough);
}
+47
View File
@@ -68,6 +68,29 @@ pub fn tag_row_view(t: Res<TagRowTarget>, images: Res<Assets<Image>>, view_box:
}
}
/// A camera with a sub view culls by that view. Bevy's update_frusta takes the projection's whole view at the target's
/// shape, so with a box wider than the frame (1080 x 389 in a 1080 x 600 frame, the same field of view up and down) a
/// mesh inside the box's view and outside the frame's was culled and never drawn: a curved shelf's side cards, where
/// the same cards turned the other way reached into the frame's view and drew (#261). After Bevy's own frusta, before
/// visibility is checked; a camera whose sub view went gets Bevy's frustum back.
pub fn sub_view_frusta(mut ours: Local<bevy::platform::collections::HashSet<Entity>>, mut q: Query<(Entity, &Camera, &GlobalTransform, &Projection, &mut bevy::camera::primitives::Frustum)>) {
for (e, c, at, p, mut f) in &mut q {
let next = match c.sub_camera_view.as_ref() {
Some(v) => {
ours.insert(e);
let clip_from_world = p.get_clip_from_view_for_sub(v) * at.affine().inverse();
bevy::camera::primitives::Frustum(bevy::shape::ViewFrustum::from_clip_from_world_custom_far(&clip_from_world, &at.translation(), &at.back(), p.far()))
}
None if ours.remove(&e) => p.compute_frustum(at),
None => continue,
};
// written only when it moves, so the frustum reads as changed when it is
if (0..6).any(|i| next.half_spaces[i].normal() != f.half_spaces[i].normal() || next.half_spaces[i].d() != f.half_spaces[i].d()) {
*f = next;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -126,6 +149,30 @@ mod tests {
assert!(app.world().get::<Camera>(cam).unwrap().sub_camera_view.is_none());
}
#[test]
fn a_wide_box_culls_by_its_own_view() {
use bevy::camera::primitives::{Frustum, Sphere};
// #261's shapes on this 600 x 600 target: fov 30 up and down, the frame 1.8 wide to 1 high and a box 600 x 216
// (1080 x 389's shape); a point 1.7 to the side, 3 ahead, is outside the frame's view (half of it is 1.45
// wide there) and inside the box's (2.23)
let (mut app, cam, _) = app();
app.add_systems(Update, sub_view_frusta.after(tag_row_view));
let p = PerspectiveProjection { fov: 30f32.to_radians(), aspect_ratio: 1080.0 / 600.0, ..default() };
let whole = Projection::Perspective(p.clone()).compute_frustum(&GlobalTransform::IDENTITY);
app.world_mut().entity_mut(cam).insert((Projection::Perspective(p), GlobalTransform::IDENTITY, whole));
let card = Sphere { center: bevy::math::Vec3A::new(1.7, 0.0, -3.0), radius: 0.05 };
let seen = |app: &App| app.world().get::<Frustum>(cam).unwrap().intersects_sphere(&card, true);
app.update();
assert!(!seen(&app), "outside the frame's view");
app.world_mut().resource_mut::<ViewBox>().0 = Some([0, 100, 600, 216]);
app.update();
assert!(seen(&app), "inside the box's view");
// the box goes: Bevy's frustum again
app.world_mut().resource_mut::<ViewBox>().0 = None;
app.update();
assert!(!seen(&app));
}
#[test]
fn a_cameras_own_viewport_is_left_as_it_is() {
let (mut app, _, h) = app();
+3
View File
@@ -222,6 +222,7 @@ raea-app-scene = "apps" # raea scene lint|explain|light|stage
raea-app-voice = "apps" # raea voice: speech to speech on this computer, as lines of JSON
raea-app-ask = "apps"
raea-app-lightbake = "apps" # raea bake light (docs/bake.feature)
raea-sys-lighttrace = "systems" # light paths on the GPU by wgpu ray queries: the kernel the bake, rt and the path tracer share (docs/bake.feature BK3)
raea-sys-lightbake = "systems" # light baked over raea/wear's atlas on raea's ray tracer (docs/bake.feature)
raea-app-double = "apps"
raea-app-solid = "apps"
@@ -336,3 +337,5 @@ raea-sys-damage = true
raea-sys-glb = true
# the atlas raea's bakes share: charts, packing, each texel's point (the cause maps and the light bake lie over it)
raea-sys-atlas = true
# the paths a bake traces its light along (the kernel and its Settings), which systems/rt and the path tracer may build on too
raea-sys-lighttrace = true