Skip to content

programmatic video rendering framework that is actually fast

feat(3D): add 3D scenes with the building blocks of three.js (#233)

Dmitriy Kovalenko6c20994ee76a
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
index cb7c1b96..a1574f8a 100644
--- a/.github/workflows/main.yml
+++ b/.github/workflows/main.yml
@@ -265,7 +265,7 @@ jobs:
env:
RUSTFLAGS: --cfg fframes_docsrs
RUSTDOCFLAGS: --cfg docsrs -D warnings
- run: cargo doc --no-deps -p fframes-media -p fframes --features fframes/cli,fframes/compile-time-svgtree,fframes/exif
+ run: cargo doc --no-deps -p fframes-media -p fframes --features fframes/cli,fframes/compile-time-svgtree,fframes/exif,fframes/3d
release:
# A push to main publishes a nightly, a v* tag publishes that version (scripts/release-version.sh)
diff --git a/AGENTS.md b/AGENTS.md
index 5597b641..cc441a67 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -233,6 +233,7 @@ cargo test -- --nocapture
/fframes-editor # Web editor UI (ReScript + React), published as @fframes/editor
/fframes-editor-controller # WASM bridge between a Video impl and the editor
/fframes-test-utils # Snapshot helpers for svgr! trees
+/fframes-three-d # 3D: three.js style scene graph, glTF, CPU rasterizer or wgpu (GPU texture shared with Skia)
/svgr-macro # The svgr! procedural macro (SVG DSL + static-subtree hashing)
/media-dir-macro # include_media_dir! (embeds a media folder into the binary)
/webvtt-parser # Subtitle format parser
@@ -522,6 +523,109 @@ fframes::svgr!(<image href={layer.href()} x="0" y="0" width="1920" height="1080"
draws nothing in their place, and the editor shows a placeholder.
- Requires the `compile-time-svgtree` feature (the default `renderer` feature of the examples).
+### 7d. 3D scenes (`fframes::three_d`)
+
+`fframes = { features = ["3d"] }` adds `fframes::three_d` (the `fframes_three_d` crate): a
+three.js style scene graph with its own renderer. It has 4x MSAA, metal/roughness PBR with
+clearcoat, a studio or HDR panorama environment, soft sun shadows, planar reflections,
+transparency, additive glows, particles, fog, depth of field, motion blur, bloom and ACES.
+It returns an image for `<image href>`. glTF and STL models load too. The crate docs
+(`fframes-three-d/src/lib.rs`) map three.js classes to their fframes_three_d names.
+
+Two renderers draw the same picture:
+
+- The CPU rasterizer runs everywhere, also in the editor (at half size there).
+- With `fframes = { features = ["3d", "wgpu"] }` the renderer uses wgpu (Vulkan, Metal, DX12).
+ A frame differs from the CPU frame by less than one 8-bit step on average. Without a GPU
+ it falls back to the CPU. `Renderer::cpu()` forces the CPU.
+- With `fframes_skia_renderer = { features = ["vulkan", "wgpu"] }` as well, the 3D stays on
+ the GPU: Skia draws the wgpu texture in place and converts the frame for the encoder.
+ Nothing is read back. Other backends (the CPU backend, Metal, the editor) get pixels.
+
+Without these features nothing of wgpu compiles.
+
+```rust
+use fframes::three_d::*;
+
+// once, in the constructor: geometry is shared by `Arc`, keep the ids you animate
+let mut scene = Scene::new().environment(Environment::studio()).background(Background::Transparent);
+let body = scene.add(Node::mesh(Geometry::rounded_box(1.0, 1.0, 1.0, 0.08, 4), Material::metal(0xd4d8e0, 0.25)).at(0.0, 0.5, 0.0));
+let arm = scene.add_to(body, Node::mesh(Geometry::cylinder(0.1, 0.1, 0.8, 24), Material::standard(0xff5500).clearcoat(1.0)).at(0.6, 0.2, 0.0));
+scene.add(Node::mesh(Geometry::floor(30.0, 30.0), Material::shadow_catcher(0.6)).shadows(false, true));
+scene.add(Node::light(Light::sun(Rgb::WHITE, 3.0, vec3(3.0, 6.0, 4.0))));
+let renderer = Renderer::new(1920, 1080).bloom(Bloom::default());
+
+// render_frame: clone (cheap), pose, render
+let mut s = scene.clone();
+s[arm].rotation = euler(0.0, 0.0, t * 2.0);
+s[body].material_mut().unwrap().emissive_intensity = glow;
+let camera = Camera::perspective(35.0).orbit(vec3(0.0, 0.6, 0.0), 6.0, 30.0 + t * 20.0, 15.0);
+let image = renderer.render(&s, &camera);
+// motion blur for fast shots: renderer.render_motion_blur(3, |o| build(t + o / 120.0))
+svgr!(<image href={image.href()} x="0" y="0" width="1920" height="1080" />)
+```
+
+- Y is up, the camera looks down -Z, angles are radians (`deg()`, `euler_deg()`), units are
+ meters. Hex and `&str` colors are sRGB like three.js. Multiply an `Rgb` above 1 for HDR
+ glow (`Rgb::hex(0x22e8ff) * 6.0`).
+- Geometry: `cuboid`, `rounded_box`, `sphere`, `cylinder`, `cone`, `capsule`, `torus`, `plane`,
+ `floor`, `ring`, `lathe`, `extrude` (concave shapes, bevels), `tube`, `icosahedron`, `text`,
+ with `translate`, `rotate_*`, `scale`, `merge`, `with_color`, `flat`, `smooth`.
+- Materials: `standard`, `metal`, `unlit`, `glow` (additive), `shadow_catcher`, `normals`,
+ with `emissive`, `clearcoat`, `opacity`, `additive`, `map`, `normal_map`, `ao_map`.
+- Pin SVG to 3D: `camera.project(scene.local_to_world(id, local), 1920.0, 1080.0)` gives the
+ pixel. `camera.pixel_size(..)` sizes a bracket. HUD labels then stay on the object.
+- glTF: `let model = Model::from_gltf(bytes)?; let inst = model.add_to(&mut s, None);
+ inst.play(&mut s, model.animation("Dance").unwrap(), t);`
+- STL (geometry only): `Geometry::from_stl(bytes)?.smooth(40.0)` and a `Material`. Most
+ files are millimeters with Z up: `.scale(0.001, 0.001, 0.001).rotate_x(-FRAC_PI_2)`.
+- Depth of field: `camera.focus_on(point, blur_px)` or `.focus(distance, blur_px)`.
+- Reflections (three.js `Reflector`): `scene.reflector = Some(Reflector::floor())` names the
+ plane. `.reflection(0.8)` on a material on that plane shows the scene mirrored in it, blurred
+ by the roughness. One plane per scene, rendered at half resolution by default.
+- Highlights do not sparkle: a normal that turns inside a pixel widens the specular lobe.
+- Cost of a 1080p frame: 60 to 150 ms on 28 CPU threads, 5 to 20 ms on an Intel iGPU. The
+ GPU caches meshes and textures by their `Arc`, so build geometry once. Only the sun
+ (`Light::sun`) casts shadows. Set `.shadows(false, ..)` on floors and far scenery to keep
+ the shadow map tight. `fframes-three-d/tests/gpu.rs` compares both renderers.
+- `examples/arm` is a short film that uses most of the crate. Its `src/effects.rs` builds
+ camera shake, a light beam in hazy air, spark streaks and a printed grid from these blocks.
+
+### 7e. Your own wgpu passes (`fframes::wgpu_layer`)
+
+With `fframes = { features = ["wgpu"] }` and the Skia Vulkan backend's `wgpu` feature,
+anything rendered with wgpu goes into a frame the way fframes_three_d does:
+
+```rust
+use fframes::wgpu;
+
+let Some(gpu) = fframes::shared_gpu() else { return cpu_fallback() }; // CPU backend, editor
+let texture = gpu.device().create_texture(&wgpu::TextureDescriptor {
+ format: fframes::WGPU_LAYER_FORMAT, // Rgba8Unorm, premultiplied sRGB
+ usage: fframes::WGPU_LAYER_USAGE | wgpu::TextureUsages::RENDER_ATTACHMENT,
+ ..
+});
+let mut encoder = gpu.device().create_command_encoder(&Default::default());
+// passes rendering into `texture`
+fframes::finish_wgpu_layer(&mut encoder, &texture); // leaves it sampled, Skia adds no barrier
+gpu.submit([encoder.finish()]); // under the backend's queue lock
+let layer = fframes::wgpu_layer(&gpu, &texture);
+svgr!(<image href={layer.href()} x="0" y="0" width="1920" height="1080" />)
+```
+
+- Render into the texture again only after the returned image is dropped. The backend has
+ submitted the frame that samples it by then. Keep a pool (see `LayerTarget` in
+ `fframes-three-d/src/gpu/mod.rs`) and drop its textures with the device: the GPU can still
+ sample a texture after its image is dropped, and wgpu waits only for its own submissions.
+- The texture is 2D with one layer and one sample. Other textures draw nothing.
+- Keep per-device state in `gpu.state(|gpu| ..)`. It is dropped with the device. The
+ shared Vulkan device belongs to wgpu and goes with the last wgpu object, so wgpu objects
+ may outlive the backend context (`SkiaVulkanCtx`); they hold the GPU memory until then.
+- Every Skia context then submits to the wgpu queue. The queue orders a layer before the
+ frame that samples it. Submit only with `gpu.submit`, which holds the backend's queue lock.
+- The tiny-skia CPU backend draws no layers. Do not keep a shared `SkiaVulkanCtx` alive
+ while it renders.
+
### 7c. Audio mix
`fn audio` places files on the timeline. Tuples still work; `AudioTrack` adds mix settings:
diff --git a/Cargo.lock b/Cargo.lock
index 97c13ad6..5ce5802c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -52,6 +52,12 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4aa90d7ce82d4be67b64039a3d588d38dbcc6736577de4a847025ce5b0c468d1"
+[[package]]
+name = "allocator-api2"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
+
[[package]]
name = "alsa"
version = "0.11.0"
@@ -99,6 +105,15 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04"
+[[package]]
+name = "android_system_properties"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "anes"
version = "0.1.6"
@@ -187,6 +202,15 @@ dependencies = [
"syn 2.0.100",
]
+[[package]]
+name = "arm-example"
+version = "1.2.0"
+dependencies = [
+ "fframes",
+ "fframes_native_player",
+ "fframes_skia_renderer",
+]
+
[[package]]
name = "arrayref"
version = "0.3.9"
@@ -325,11 +349,26 @@ dependencies = [
"proc-macro2",
"quote",
"regex",
- "rustc-hash",
+ "rustc-hash 2.1.1",
"shlex 1.3.0",
"syn 2.0.100",
]
+[[package]]
+name = "bit-set"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d"
+dependencies = [
+ "bit-vec",
+]
+
+[[package]]
+name = "bit-vec"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
+
[[package]]
name = "bit_field"
version = "0.10.2"
@@ -416,6 +455,12 @@ dependencies = [
"syn 3.0.6",
]
+[[package]]
+name = "byteorder"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
+
[[package]]
name = "byteorder-lite"
version = "0.1.0"
@@ -589,6 +634,15 @@ version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f46ad14479a25103f283c0f10005961cf086d8dc42205bb44c46ac563475dca6"
+[[package]]
+name = "codespan-reporting"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"
+dependencies = [
+ "unicode-width",
+]
+
[[package]]
name = "color"
version = "0.3.3"
@@ -952,6 +1006,15 @@ dependencies = [
"libloading",
]
+[[package]]
+name = "document-features"
+version = "0.2.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"
+dependencies = [
+ "litrs",
+]
+
[[package]]
name = "downcast-rs"
version = "1.2.1"
@@ -1125,6 +1188,7 @@ dependencies = [
"criterion",
"fframes-media",
"fframes-media-dir-macro",
+ "fframes_three_d",
"futures",
"image",
"indicatif",
@@ -1190,11 +1254,13 @@ dependencies = [
"itoa",
"kamadak-exif",
"libc",
+ "log",
"quote",
"ttf-parser",
"usvgr",
"wasm-bindgen",
"webvtt-parser",
+ "wgpu",
]
[[package]]
@@ -1239,6 +1305,7 @@ dependencies = [
"svgr",
"thingbuf",
"uuid",
+ "wgpu",
]
[[package]]
@@ -1249,6 +1316,24 @@ dependencies = [
"futures",
]
+[[package]]
+name = "fframes_three_d"
+version = "1.2.0"
+dependencies = [
+ "base64 0.22.1",
+ "bytemuck",
+ "fframes-media",
+ "glam",
+ "gltf",
+ "image",
+ "png 0.17.16",
+ "pollster",
+ "rayon",
+ "ttf-parser",
+ "usvgr",
+ "wgpu",
+]
+
[[package]]
name = "filetime"
version = "0.2.25"
@@ -1473,12 +1558,68 @@ dependencies = [
"weezl",
]
+[[package]]
+name = "glam"
+version = "0.30.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9"
+
[[package]]
name = "glob"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2"
+[[package]]
+name = "gltf"
+version = "1.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3ce1918195723ce6ac74e80542c5a96a40c2b26162c1957a5cd70799b8cacf7"
+dependencies = [
+ "byteorder",
+ "gltf-json",
+ "lazy_static",
+ "serde_json",
+]
+
+[[package]]
+name = "gltf-derive"
+version = "1.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "14070e711538afba5d6c807edb74bcb84e5dbb9211a3bf5dea0dfab5b24f4c51"
+dependencies = [
+ "inflections",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.100",
+]
+
+[[package]]
+name = "gltf-json"
+version = "1.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6176f9d60a7eab0a877e8e96548605dedbde9190a7ae1e80bbcc1c9af03ab14"
+dependencies = [
+ "gltf-derive",
+ "serde",
+ "serde_derive",
+ "serde_json",
+]
+
+[[package]]
+name = "gpu-allocator"
+version = "0.28.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795"
+dependencies = [
+ "ash",
+ "hashbrown 0.16.1",
+ "log",
+ "presser",
+ "thiserror 2.0.21",
+ "windows",
+]
+
[[package]]
name = "half"
version = "2.6.0"
@@ -1487,6 +1628,18 @@ checksum = "459196ed295495a68f7d7fe1d84f6c4b7ff0e21fe3017b2f283c6fac3ad803c9"
dependencies = [
"cfg-if",
"crunchy",
+ "num-traits",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
+dependencies = [
+ "allocator-api2",
+ "equivalent",
+ "foldhash",
]
[[package]]
@@ -1575,7 +1728,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
- "hashbrown",
+ "hashbrown 0.17.1",
]
[[package]]
@@ -1591,6 +1744,12 @@ dependencies = [
"web-time",
]
+[[package]]
+name = "inflections"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a257582fdcde896fd96463bf2d40eefea0580021c0712a0e2b028b60b47a837a"
+
[[package]]
name = "interpolate_name"
version = "0.2.4"
@@ -1728,11 +1887,12 @@ checksum = "f5d4a7da358eff58addd2877a45865158f0d78c911d43a5784ceb7bbf52833b0"
[[package]]
name = "js-sys"
-version = "0.3.77"
+version = "0.3.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f"
+checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5"
dependencies = [
- "once_cell",
+ "cfg-if",
+ "futures-util",
"wasm-bindgen",
]
@@ -1857,6 +2017,12 @@ version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12"
+[[package]]
+name = "litrs"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70"
+
[[package]]
name = "lock_api"
version = "0.4.12"
@@ -1869,9 +2035,9 @@ dependencies = [
[[package]]
name = "log"
-version = "0.4.27"
+version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94"
+checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
[[package]]
name = "loop9"
@@ -1916,7 +2082,7 @@ version = "0.18.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5"
dependencies = [
- "hashbrown",
+ "hashbrown 0.17.1",
]
[[package]]
@@ -2055,6 +2221,44 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16cf681a23b4d0a43fc35024c176437f9dcd818db34e0f42ab456a0ee5ad497b"
+[[package]]
+name = "naga"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130"
+dependencies = [
+ "arrayvec",
+ "bit-set",
+ "bitflags 2.13.2",
+ "cfg-if",
+ "cfg_aliases",
+ "codespan-reporting",
+ "half",
+ "hashbrown 0.17.1",
+ "indexmap",
+ "libm",
+ "log",
+ "naga-types",
+ "num-traits",
+ "once_cell",
+ "rustc-hash 1.1.0",
+ "spirv",
+ "thiserror 2.0.21",
+ "unicode-ident",
+]
+
+[[package]]
+name = "naga-types"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49"
+dependencies = [
+ "hashbrown 0.17.1",
+ "indexmap",
+ "rustc-hash 1.1.0",
+ "thiserror 2.0.21",
+]
+
[[package]]
name = "ndk"
version = "0.9.0"
@@ -2221,6 +2425,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
+ "libm",
]
[[package]]
@@ -2514,6 +2719,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"
dependencies = [
"bitflags 2.13.2",
+ "block2 0.6.2",
"objc2 0.6.4",
"objc2-foundation 0.3.2",
]
@@ -2540,6 +2746,7 @@ dependencies = [
"bitflags 2.13.2",
"objc2 0.6.4",
"objc2-core-foundation",
+ "objc2-core-graphics",
"objc2-foundation 0.3.2",
"objc2-metal 0.3.2",
]
@@ -2621,6 +2828,15 @@ dependencies = [
"libredox",
]
+[[package]]
+name = "ordered-float"
+version = "5.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8c7c9e0d9b23589f26070720bac724174bfec1083e82f7854cdd0267518343c0"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "owned_ttf_parser"
version = "0.25.1"
@@ -2829,6 +3045,12 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "pollster"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bc6355899e1c9462875b6757c79f3caa011a1fdae12bbb1a2e72dd1f234f8336"
+
[[package]]
name = "polycool"
version = "0.4.0"
@@ -2844,6 +3066,15 @@ version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
+[[package]]
+name = "portable-atomic-util"
+version = "0.2.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715"
+dependencies = [
+ "portable-atomic",
+]
+
[[package]]
name = "ppv-lite86"
version = "0.2.21"
@@ -2853,6 +3084,12 @@ dependencies = [
"zerocopy 0.8.24",
]
+[[package]]
+name = "presser"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"
+
[[package]]
name = "prettyplease"
version = "0.2.32"
@@ -2998,6 +3235,12 @@ dependencies = [
"getrandom 0.3.2",
]
+[[package]]
+name = "range-alloc"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08"
+
[[package]]
name = "rangemap"
version = "1.5.1"
@@ -3165,6 +3408,12 @@ dependencies = [
"tiktok-example",
]
+[[package]]
+name = "renderdoc-sys"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"
+
[[package]]
name = "rgb"
version = "0.8.50"
@@ -3186,6 +3435,12 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a157657054ffe556d8858504af8a672a054a6e0bd9e8ee531059100c0fa11bb2"
+[[package]]
+name = "rustc-hash"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
+
[[package]]
name = "rustc-hash"
version = "2.1.1"
@@ -3629,6 +3884,15 @@ dependencies = [
"x11rb",
]
+[[package]]
+name = "spirv"
+version = "0.4.0+sdk-1.4.341.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f"
+dependencies = [
+ "bitflags 2.13.2",
+]
+
[[package]]
name = "static_assertions"
version = "1.1.0"
@@ -3952,6 +4216,15 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
+[[package]]
+name = "tokio"
+version = "1.53.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e"
+dependencies = [
+ "pin-project-lite",
+]
+
[[package]]
name = "toml"
version = "0.8.20"
@@ -4252,9 +4525,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen"
-version = "0.2.100"
+version = "0.2.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5"
+checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409"
dependencies = [
"cfg-if",
"once_cell",
@@ -4262,40 +4535,25 @@ dependencies = [
"serde",
"serde_json",
"wasm-bindgen-macro",
-]
-
-[[package]]
-name = "wasm-bindgen-backend"
-version = "0.2.100"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2f0a0651a5c2bc21487bde11ee802ccaf4c51935d0d3d42a6101f98161700bc6"
-dependencies = [
- "bumpalo",
- "log",
- "proc-macro2",
- "quote",
- "syn 2.0.100",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-futures"
-version = "0.4.50"
+version = "0.4.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "555d470ec0bc3bb57890405e5d4322cc9ea83cebb085523ced7be4144dac1e61"
+checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e"
dependencies = [
- "cfg-if",
"js-sys",
- "once_cell",
+ "tokio",
"wasm-bindgen",
- "web-sys",
]
[[package]]
name = "wasm-bindgen-macro"
-version = "0.2.100"
+version = "0.2.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7fe63fc6d09ed3792bd0897b314f53de8e16568c2b3f7982f468c0bf9bd0b407"
+checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
@@ -4303,22 +4561,22 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro-support"
-version = "0.2.100"
+version = "0.2.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de"
+checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7"
dependencies = [
+ "bumpalo",
"proc-macro2",
"quote",
- "syn 2.0.100",
- "wasm-bindgen-backend",
+ "syn 3.0.6",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
-version = "0.2.100"
+version = "0.2.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1a05d73b933a847d6cccdda8f838a22ff101ad9bf93e33684f39c1f5f0eece3d"
+checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6"
dependencies = [
"unicode-ident",
]
@@ -4434,9 +4692,9 @@ dependencies = [
[[package]]
name = "web-sys"
-version = "0.3.77"
+version = "0.3.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "33b6dd2ef9186f1f2072e409e99cd22a975331a6b3591b12c764e0e55c60d5d2"
+checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4"
dependencies = [
"js-sys",
"wasm-bindgen",
@@ -4466,6 +4724,159 @@ version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53a85b86a771b1c87058196170769dd264f66c0782acf1ae6cc51bfd64b39082"
+[[package]]
+name = "wgpu"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "527ccdf43dd5b2e8676eed9984ce00e2bbb0a1b85b70c1969dcb6cd2eb55ab9e"
+dependencies = [
+ "arrayvec",
+ "bitflags 2.13.2",
+ "bytemuck",
+ "cfg-if",
+ "cfg_aliases",
+ "document-features",
+ "hashbrown 0.17.1",
+ "js-sys",
+ "log",
+ "parking_lot",
+ "portable-atomic",
+ "profiling",
+ "raw-window-handle",
+ "smallvec",
+ "static_assertions",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+ "wgpu-core",
+ "wgpu-hal",
+ "wgpu-types",
+]
+
+[[package]]
+name = "wgpu-core"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14"
+dependencies = [
+ "arrayvec",
+ "bit-set",
+ "bit-vec",
+ "bitflags 2.13.2",
+ "bytemuck",
+ "cfg_aliases",
+ "document-features",
+ "hashbrown 0.17.1",
+ "indexmap",
+ "log",
+ "naga",
+ "naga-types",
+ "once_cell",
+ "parking_lot",
+ "portable-atomic",
+ "profiling",
+ "raw-window-handle",
+ "rustc-hash 1.1.0",
+ "smallvec",
+ "thiserror 2.0.21",
+ "wgpu-core-deps-apple",
+ "wgpu-core-deps-windows-linux-android",
+ "wgpu-hal",
+ "wgpu-naga-bridge",
+ "wgpu-types",
+]
+
+[[package]]
+name = "wgpu-core-deps-apple"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "061f3d319a40d39d00b1ecc2c33b89fe21d4e6fe01859df3500a3a8ecccd6b68"
+dependencies = [
+ "wgpu-hal",
+]
+
+[[package]]
+name = "wgpu-core-deps-windows-linux-android"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7586165fd5f6d881cb9ce4bb71f40d6caab2c0f1837e3fc1d9788a197fb6004f"
+dependencies = [
+ "wgpu-hal",
+]
+
+[[package]]
+name = "wgpu-hal"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6b7fb58561a792bc237628ba0792e332de418fefe145f13b5ed8201e6d52f58"
+dependencies = [
+ "android_system_properties",
+ "arrayvec",
+ "ash",
+ "bit-set",
+ "bitflags 2.13.2",
+ "block2 0.6.2",
+ "bytemuck",
+ "cfg-if",
+ "cfg_aliases",
+ "gpu-allocator",
+ "hashbrown 0.17.1",
+ "libc",
+ "libloading",
+ "log",
+ "naga",
+ "naga-types",
+ "objc2 0.6.4",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+ "objc2-foundation 0.3.2",
+ "objc2-metal 0.3.2",
+ "objc2-quartz-core 0.3.2",
+ "once_cell",
+ "ordered-float",
+ "parking_lot",
+ "portable-atomic",
+ "portable-atomic-util",
+ "profiling",
+ "range-alloc",
+ "raw-window-handle",
+ "raw-window-metal",
+ "renderdoc-sys",
+ "smallvec",
+ "static_assertions",
+ "thiserror 2.0.21",
+ "wgpu-naga-bridge",
+ "wgpu-types",
+ "windows",
+ "windows-core",
+]
+
+[[package]]
+name = "wgpu-naga-bridge"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2f62e73117bb7a62bfd9c5a5841438a823f6566c6442a808ee269d2d055c081"
+dependencies = [
+ "naga",
+ "wgpu-types",
+]
+
+[[package]]
+name = "wgpu-types"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "99dad6f1fbdbbdb4c278a6508b059d44688f5cebddf78d005a46a31340269286"
+dependencies = [
+ "bitflags 2.13.2",
+ "bytemuck",
+ "js-sys",
+ "log",
+ "naga-types",
+ "raw-window-handle",
+ "static_assertions",
+ "web-sys",
+]
+
[[package]]
name = "winapi"
version = "0.3.9"
diff --git a/Cargo.toml b/Cargo.toml
index f90058fe..a49cbde3 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -10,6 +10,7 @@ members = [
"fframes-media",
"fframes-skia-renderer",
"fframes-native-player",
+ "fframes-three-d",
"media-dir-macro",
"render-bench",
"render-bench/vs-remotion",
@@ -43,6 +44,7 @@ members = [
"examples/shaders/editor/editor-bridge",
"examples/neon-triangle",
"examples/neon-triangle/editor/editor-bridge",
+ "examples/arm",
# maybe clean this up?
# "fframes-lyon-renderer",
@@ -109,7 +111,6 @@ wasm-bindgen = "0.2.100"
kamadak-exif = "0.6.1"
# fframes internal deps
-fframes_renderer = { path = "fframes-renderer", version = "1.0.0-beta.6.rc-3.2" }
fframes-media = { path = "fframes-media", version = "1.2.0" }
svgr-macro = { path = "svgr-macro", version = "1.2.0" }
fframes-media-dir-macro = { path = "media-dir-macro", version = "1.2.0" }
@@ -118,3 +119,4 @@ webvtt-parser = { path = "webvtt-parser", version = "1.2.0" }
fframes_skia_renderer = { path = "fframes-skia-renderer", version = "1.2.0" }
# Members pick metal or vulkan: both at once match no prebuilt Skia and build it from source.
fframes_native_player = { path = "fframes-native-player", version = "1.2.0", default-features = false }
+fframes_three_d = { path = "fframes-three-d", version = "1.2.0" }
diff --git a/examples/arm/.gitignore b/examples/arm/.gitignore
new file mode 100644
index 00000000..9baf8f74
--- /dev/null
+++ b/examples/arm/.gitignore
@@ -0,0 +1,3 @@
+out.mp4
+frames/
+dynamic_media/
diff --git a/examples/arm/Cargo.toml b/examples/arm/Cargo.toml
new file mode 100644
index 00000000..6d8086f0
--- /dev/null
+++ b/examples/arm/Cargo.toml
@@ -0,0 +1,50 @@
+[package]
+name = "arm-example"
+version = "1.2.0"
+edition = "2024"
+publish = false
+
+[dependencies]
+# `3d`: `fframes::three_d`; `wgpu`: the 3D renders on the GPU
+fframes = { workspace = true, features = ["3d", "wgpu"] }
+
+# Skia on Metal on macOS, on Vulkan everywhere else.
+# `preview`: real-time GPU window
+[target.'cfg(target_os = "macos")'.dependencies]
+fframes_skia_renderer = { workspace = true, features = ["metal"] }
+fframes_native_player = { workspace = true, features = ["metal", "audio"] }
+
+[target.'cfg(not(any(target_os = "macos", target_arch = "wasm32")))'.dependencies]
+# `wgpu`: the 3D renders on the Vulkan device of Skia and stays on the GPU
+fframes_skia_renderer = { workspace = true, features = ["vulkan", "wgpu"] }
+fframes_native_player = { workspace = true, features = ["vulkan", "audio"] }
+
+[target.'cfg(not(windows))'.dependencies]
+fframes = { workspace = true, features = ["h264", "libav-agree-gpl"] }
+
+# Keep FFmpeg source fallbacks portable across CI runner CPUs (see README).
+[target.'cfg(not(any(target_arch = "wasm32", windows)))'.dependencies]
+fframes = { workspace = true, features = ["build-portable"] }
+
+[features]
+default = ["renderer"]
+renderer = ["fframes/compile-time-svgtree", "fframes/cli"]
+
+[lib]
+crate-type = ["cdylib", "rlib"]
+name = "arm_example"
+path = "src/lib.rs"
+doctest = false
+
+[[bin]]
+name = "arm"
+path = "src/main.rs"
+required-features = ["renderer"]
+
+[[bin]]
+name = "arm-soundtrack"
+path = "src/bin/soundtrack.rs"
+
+[lints]
+workspace = true
+
diff --git a/examples/arm/README.md b/examples/arm/README.md
new file mode 100644
index 00000000..8e5ff297
--- /dev/null
+++ b/examples/arm/README.md
@@ -0,0 +1,56 @@
+# FFRAMES, ASSEMBLED
+
+A 37-second short film about a lab robot with a camera eye. The robot wakes up in the dark
+lab, and its eye light searches the floor. The lab lights flicker on. The robot sees the
+camera, then spells `fframes` with letter pieces from a rack. It gets faster and too
+confident. In a spin it throws the "a" across the floor, and sparks fly. The music stops like
+a tape, and crickets fill the silence. The robot looks at the letter, then into the camera. It
+sighs, moves over carefully and picks up the letter from the floor. It puts the letter in its
+place, pats it, completes the word and bows.
+
+| file | what |
+| --- | --- |
+| `src/arm.rs` | the six axis arm and its analytic inverse kinematics for any tool pose. The arm has finned motors, bolt circles, a gas spring, a corrugated hose, a drag chain, three wrist motors, a forearm that rolls, a gripper and a camera eye with a lid, a spot light and a beam |
+| `src/lab.rs` | the polished concrete floor (procedural color, normal and occlusion-roughness maps, reflects the scene), hazard stripes, stencils, a printed grid, the rack, shelves of bins, monitors, the walls and the lights |
+| `src/effects.rs` | what the film builds itself from the building blocks: camera shake, a light beam in hazy air, sparks with streaks, a printed grid |
+| `src/story.rs` | the performance: keys with character easing (anticipation, overshoot), idle motion, the timelines of the letters, the rigid tumble of the dropped letter, the sounds and the console lines |
+| `src/bin/soundtrack.rs` | the score (music box, marimba, pizzicato, glockenspiel, drums, pads, crickets, tape stop) and every effect, timed from the story. The servo sound follows the speed of each joint |
+
+```sh
+cargo run --release -p arm-example --bin arm-soundtrack # writes dynamic_media/*.wav
+cargo run --release -p arm-example --bin arm -- render # 3D and Skia on the GPU -> out.mp4
+cargo run --release -p arm-example --bin arm -- --cpu render # everything on the CPU
+cargo run --release -p arm-example --bin arm -- --readback render # the 3D read back to the CPU, to compare
+```
+
+## What it uses
+
+| `fframes::three_d` | where |
+| --- | --- |
+| scene graph, groups, `Scene::local_to_world` | the joints of the arm, the gas spring between two joints |
+| `rounded_box`, `cylinder`, `torus`, `sphere_partial`, `lathe`, `extrude`, `tube`, `ring`, `circle`, `text`, `merge` | the arm, the letters, the stencils |
+| `Material::standard`, `metal`, `clearcoat`, `emissive`, `glow` | white paint, chrome, lacquered letters, status lights, the beam |
+| `map`, `normal_map`, `ao_map`, `metal_rough_map`, `emissive_map`, `Texture::from_fn` | the concrete, the hazard stripes, the grid, the monitors |
+| `Light::sun` with `Shadow`, `directional`, `hemisphere`, `spot`, `point` | the ceiling, the fill, the eye light, the glow of the base ring |
+| `Environment::Studio`, `Fog::Exp2`, `Background::Color` | the lab at each light level |
+| `Reflector::floor` | the polished concrete |
+| `Node::instanced` with a color per copy | the bins on the shelves |
+| `Node::particles` | the dust in the beam, the sparks |
+| `Camera::focus_on`, `Renderer::render_motion_blur` | depth of field in every shot, motion blur in the spin and the throw |
+| `Bloom`, `ToneMapping::Neutral`, `exposure` | the glow of the lights and the sparks |
+| `Camera::project`, `Camera::pixel_size` | the SVG marker on the thrown letter |
+
+The 3D comes from `fframes = { features = ["3d", "wgpu"] }` and renders on the GPU
+(`Renderer::gpu()`). On Linux and Windows it uses the same Vulkan device as Skia (the `wgpu`
+feature of `fframes_skia_renderer`): the 3D of each frame is a GPU texture, Skia draws the
+console overlay on it and converts it to YUV for the encoder, and nothing is read back between
+these steps. On macOS Skia renders with Metal, and the 3D comes back as pixels.
+
+The polished concrete reflects the scene (`Scene::reflector`). The reflection renders mirrored
+at half resolution, and the roughness map of the floor blurs it. Specular antialiasing stops
+the sparkle on the chrome.
+
+The full film renders in about 42 seconds on an Intel UHD 770 iGPU: about 19 ms for each 1080p
+frame with depth of field, reflections and 4x MSAA. On average the 3D is within 0.4/255 of the
+CPU rasterizer. `--readback` reads the 3D back from the GPU and uploads it to Skia again, for
+comparison. With `--cpu` the film takes about six minutes on a 28-thread machine.
diff --git a/examples/arm/media/IBMPlexMono-Regular.ttf b/examples/arm/media/IBMPlexMono-Regular.ttf
new file mode 100644
index 00000000..0c9770d5
Binary files /dev/null and b/examples/arm/media/IBMPlexMono-Regular.ttf differ
diff --git a/examples/arm/media/IBMPlexMono-SemiBold.ttf b/examples/arm/media/IBMPlexMono-SemiBold.ttf
new file mode 100644
index 00000000..8f8998a1
Binary files /dev/null and b/examples/arm/media/IBMPlexMono-SemiBold.ttf differ
diff --git a/examples/arm/media/Inter_18pt-ExtraBold.ttf b/examples/arm/media/Inter_18pt-ExtraBold.ttf
new file mode 100644
index 00000000..e71c601c
Binary files /dev/null and b/examples/arm/media/Inter_18pt-ExtraBold.ttf differ
diff --git a/examples/arm/src/arm.rs b/examples/arm/src/arm.rs
new file mode 100644
index 00000000..18196855
--- /dev/null
+++ b/examples/arm/src/arm.rs
@@ -0,0 +1,1199 @@
+//! A six axis industrial arm with a camera eye on its gripper, and its inverse kinematics.
+//! The three wrist axes meet in one point, so the inverse kinematics has an analytic solution.
+
+use std::f32::consts::{FRAC_PI_2, PI, TAU};
+
+use fframes::three_d::*;
+
+/// Height of the J1 turret above the floor.
+pub const BASE_H: f32 = 0.45;
+/// Height of J2 above J1.
+pub const J2_UP: f32 = 0.42;
+/// Distance of J2 in front of the J1 axis.
+pub const A1: f32 = 0.16;
+/// Length of the upper arm, from J2 to J3.
+pub const L2: f32 = 1.05;
+/// Height of the forearm axis above J3.
+pub const A3: f32 = 0.12;
+/// Length of the forearm, from J3 to J5.
+pub const L3: f32 = 1.0;
+/// Distance of the J4 roll joint from J3 along the forearm.
+pub const J4_AT: f32 = 0.62;
+/// Distance from J5 to J6 along the tool.
+pub const J6_OFFSET: f32 = 0.15;
+/// Distance from J6 to the point between the finger tips.
+pub const GRIP: f32 = 0.24;
+/// Distance from J5 to the grip point.
+pub const TIP: f32 = J6_OFFSET + GRIP;
+/// Half the finger gap of the open gripper.
+pub const OPEN: f32 = 0.12;
+/// Position of the eye lens in the J6 frame.
+const EYE: Vec3 = Vec3::new(0.0, 0.068, 0.1);
+
+/// Joint angles in radians: turret (J1), shoulder (J2), elbow (J3), forearm roll (J4),
+/// wrist (J5) and flange roll (J6).
+#[derive(Debug, Clone, Copy, PartialEq, Default)]
+pub struct Joints {
+ pub q: [f32; 6],
+}
+
+impl Joints {
+ pub fn lerp(&self, other: &Joints, t: f32) -> Joints {
+ Joints {
+ q: std::array::from_fn(|i| self.q[i] + (other.q[i] - self.q[i]) * t),
+ }
+ }
+
+ pub fn add(&self, offsets: [f32; 6]) -> Joints {
+ Joints {
+ q: std::array::from_fn(|i| self.q[i] + offsets[i]),
+ }
+ }
+}
+
+/// Local transforms of the six joint nodes.
+fn chain(q: &Joints) -> [Mat4; 6] {
+ [
+ Mat4::from_translation(vec3(0.0, BASE_H, 0.0)) * Mat4::from_rotation_y(q.q[0]),
+ Mat4::from_translation(vec3(0.0, J2_UP, A1)) * Mat4::from_rotation_x(q.q[1]),
+ Mat4::from_translation(vec3(0.0, L2, 0.0)) * Mat4::from_rotation_x(q.q[2]),
+ Mat4::from_translation(vec3(0.0, A3, J4_AT)) * Mat4::from_rotation_z(q.q[3]),
+ Mat4::from_translation(vec3(0.0, 0.0, L3 - J4_AT)) * Mat4::from_rotation_x(q.q[4]),
+ Mat4::from_translation(vec3(0.0, 0.0, J6_OFFSET)) * Mat4::from_rotation_z(q.q[5]),
+ ]
+}
+
+/// World transform of the J6 flange.
+pub fn flange(q: &Joints) -> Mat4 {
+ chain(q).iter().fold(Mat4::IDENTITY, |m, j| m * *j)
+}
+
+/// World transform of the grip point. The tool axis is +Z and the fingers close along +X.
+pub fn tip(q: &Joints) -> Mat4 {
+ flange(q) * Mat4::from_translation(vec3(0.0, 0.0, GRIP))
+}
+
+/// World position of the eye lens.
+pub fn eye(q: &Joints) -> Vec3 {
+ flange(q).transform_point3(EYE)
+}
+
+/// The angle `a + k * TAU` closest to `near`.
+fn unwrap(a: f32, near: f32) -> f32 {
+ a + ((near - a) / TAU).round() * TAU
+}
+
+/// Returns the joint angles that put the grip point at `position` with the tool frame
+/// `rotation`. The tool axis is local +Z and the finger axis is local +X. Of the two wrist
+/// solutions, it uses the one nearest to `hint`. It unwraps J1, J4 and J6 to the turn of `hint`.
+pub fn solve(position: Vec3, rotation: Quat, hint: &Joints) -> Joints {
+ let axis = rotation * Vec3::Z;
+ let wrist = position - axis * TIP;
+ let q1 = unwrap(wrist.x.atan2(wrist.z), hint.q[0]);
+ let r = (wrist.x * wrist.x + wrist.z * wrist.z).sqrt() - A1;
+ let h = wrist.y - (BASE_H + J2_UP);
+ let l3 = (L3 * L3 + A3 * A3).sqrt();
+ let phi = A3.atan2(L3);
+ let d = (r * r + h * h).sqrt().clamp(0.05, L2 + l3 - 1e-3);
+ let gamma = h.atan2(r);
+ let psi = ((L2 * L2 + d * d - l3 * l3) / (2.0 * L2 * d))
+ .clamp(-1.0, 1.0)
+ .acos();
+ // Elbow up.
+ let theta2 = gamma + psi;
+ let elbow = Vec2::new(L2 * theta2.cos(), L2 * theta2.sin());
+ let theta3 = (h - elbow.y).atan2(r - elbow.x) - phi;
+ let q2 = FRAC_PI_2 - theta2;
+ let q3 = -theta3 - q2;
+
+ // The wrist rotation is M = Rz(q4) Rx(q5) Rz(q6).
+ let r3 = Quat::from_rotation_y(q1) * Quat::from_rotation_x(q2 + q3);
+ let m = r3.inverse() * rotation;
+ let z = m * Vec3::Z;
+ let b = z.z.clamp(-1.0, 1.0).acos();
+ let candidates: Vec<(f32, f32)> = if b.sin().abs() < 1e-4 {
+ vec![(hint.q[3], if z.z > 0.0 { 0.0 } else { PI })]
+ } else {
+ let a = z.x.atan2(-z.y);
+ vec![(a, b), (a + PI, -b)]
+ };
+ let mut best: Option<(f32, Joints)> = None;
+ for (a, b) in candidates {
+ let a = unwrap(a, hint.q[3]);
+ let n = (Quat::from_rotation_z(a) * Quat::from_rotation_x(b)).inverse() * m;
+ let x = n * Vec3::X;
+ let c = unwrap(x.y.atan2(x.x), hint.q[5]);
+ let joints = Joints {
+ q: [q1, q2, q3, a, b, c],
+ };
+ let cost =
+ (a - hint.q[3]).abs() + 0.5 * (c - hint.q[5]).abs() + 0.3 * (b - hint.q[4]).abs();
+ if best.as_ref().is_none_or(|(best_cost, _)| cost < *best_cost) {
+ best = Some((cost, joints));
+ }
+ }
+ best.map(|(_, j)| j).expect("a wrist solution")
+}
+
+/// The tool points straight down and the fingers close along the horizontal `fingers`.
+pub fn tool_down(fingers: Vec3) -> Quat {
+ frame(fingers, Vec3::NEG_Y)
+}
+
+/// A rotation with +Z along `z` and +X along `x`, made orthogonal to `z`.
+pub fn frame(x: Vec3, z: Vec3) -> Quat {
+ let z = z.normalize();
+ let y = z.cross(x).normalize();
+ let x = y.cross(z);
+ Quat::from_mat3(&Mat3::from_cols(x, y, z))
+}
+
+/// The tool and the eye point along `look` with level fingers, turned by `roll` radians.
+pub fn looking(look: Vec3, roll: f32) -> Quat {
+ let z = look.normalize();
+ let side = Vec3::Y.cross(z).normalize_or(Vec3::X);
+ Quat::from_axis_angle(z, roll) * frame(side, z)
+}
+
+/// The scene nodes that [`Arm::apply`] poses.
+pub struct Arm {
+ joints: [NodeId; 6],
+ fingers: [NodeId; 2],
+ spring_body: NodeId,
+ spring_rod: NodeId,
+ status: NodeId,
+ ring: NodeId,
+ iris: NodeId,
+ lid: NodeId,
+ /// The spot light of the eye and its beam in the air.
+ eye_light: NodeId,
+ beam: NodeId,
+ /// The light of the base ring on the floor.
+ ring_light: NodeId,
+}
+
+/// The color of the eye light.
+const EYE_LIGHT: u32 = 0xffd6a8;
+
+/// The lights and the eye of the robot.
+#[derive(Debug, Clone, Copy)]
+pub struct Expression {
+ /// Glow of the base ring.
+ pub ring: f32,
+ /// Glow of the gripper status light.
+ pub status: f32,
+ /// Glow of the iris.
+ pub eye: f32,
+ /// Eye lid: 1 is open, 0 is closed.
+ pub lid: f32,
+ /// How much the beam of the eye shows in the air: 1 in the dark lab, 0 when it is lit.
+ pub beam: f32,
+}
+
+/// The materials of the arm.
+pub struct Palette {
+ pub white: Material,
+ pub graphite: Material,
+ pub chrome: Material,
+ pub rubber: Material,
+ pub dark: Material,
+ pub yellow: Material,
+ pub glass: Material,
+}
+
+impl Palette {
+ pub fn new() -> Self {
+ Self {
+ white: Material::standard(0xeeeeea).roughness(0.36).clearcoat(0.7),
+ graphite: Material::metal(0x2c2d31, 0.38),
+ chrome: Material::metal(0xe0e3e7, 0.1),
+ rubber: Material::standard(0x151517).roughness(0.85),
+ dark: Material::metal(0x18191b, 0.55),
+ yellow: Material::standard(0xf2bd00).roughness(0.45),
+ glass: Material::standard(0x05070a)
+ .roughness(0.03)
+ .clearcoat(1.0)
+ .env_intensity(1.6),
+ }
+ }
+}
+
+impl Default for Palette {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// The convex hull of circles as a polygon. It gives cast parts with round ends.
+pub fn hull(circles: &[(Vec2, f32)]) -> Vec<Vec2> {
+ let mut points = Vec::new();
+ for &(c, r) in circles {
+ for i in 0..48 {
+ let a = i as f32 / 48.0 * TAU;
+ points.push(c + Vec2::new(a.cos(), a.sin()) * r);
+ }
+ }
+ points.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y)));
+ let cross = |o: Vec2, a: Vec2, b: Vec2| (a - o).perp_dot(b - o);
+ let mut lower: Vec<Vec2> = Vec::new();
+ for &p in &points {
+ while lower.len() >= 2 && cross(lower[lower.len() - 2], lower[lower.len() - 1], p) <= 0.0 {
+ lower.pop();
+ }
+ lower.push(p);
+ }
+ let mut upper: Vec<Vec2> = Vec::new();
+ for &p in points.iter().rev() {
+ while upper.len() >= 2 && cross(upper[upper.len() - 2], upper[upper.len() - 1], p) <= 0.0 {
+ upper.pop();
+ }
+ upper.push(p);
+ }
+ lower.pop();
+ upper.pop();
+ lower.extend(upper);
+ lower
+}
+
+/// A plate in the side plane of the arm. `shape` is in (z, y), `thickness` is along X and the
+/// center is at `x`.
+fn side_plate(shape: &[Vec2], thickness: f32, bevel: f32, x: f32) -> Geometry {
+ let flipped: Vec<Vec2> = shape.iter().map(|p| Vec2::new(-p.x, p.y)).collect();
+ Geometry::extrude(&flipped, thickness, bevel)
+ .rotate_y(deg(90.0))
+ .translate(x, 0.0, 0.0)
+}
+
+/// A cylinder along X.
+fn axle(radius: f32, length: f32, x: f32, y: f32, z: f32) -> Geometry {
+ Geometry::cylinder(radius, radius, length, 48)
+ .rotate_z(deg(90.0))
+ .translate(x, y, z)
+}
+
+/// A cylinder along the unit vector `axis`, centered at `center`.
+fn rod(radius: f32, length: f32, center: Vec3, axis: Vec3, segments: u32) -> Geometry {
+ Geometry::cylinder(radius, radius, length, segments)
+ .rotate(Quat::from_rotation_arc(Vec3::Y, axis))
+ .translate(center.x, center.y, center.z)
+}
+
+/// Hex bolt heads with washers on a circle. The plane of the circle faces `normal`.
+fn bolt_circle(count: u32, radius: f32, bolt: f32, center: Vec3, normal: Vec3) -> Geometry {
+ let head = Geometry::merge([
+ Geometry::cylinder(bolt * 1.35, bolt * 1.35, bolt * 0.25, 16).translate(
+ 0.0,
+ bolt * 0.12,
+ 0.0,
+ ),
+ Geometry::cylinder(bolt, bolt, bolt * 0.8, 6).translate(0.0, bolt * 0.62, 0.0),
+ ]);
+ let to_normal = Quat::from_rotation_arc(Vec3::Y, normal);
+ Geometry::merge((0..count).map(|i| {
+ let a = i as f32 / count as f32 * TAU;
+ head.clone()
+ .translate(a.cos() * radius, 0.0, a.sin() * radius)
+ .rotate(to_normal)
+ .translate(center.x, center.y, center.z)
+ }))
+}
+
+/// Cooling fins: thin rings from `from` to `to`.
+fn fins(count: u32, radius: f32, from: Vec3, to: Vec3) -> Geometry {
+ let axis = (to - from).normalize_or(Vec3::Y);
+ let ring = Geometry::torus(radius, 0.008, 6, 40).rotate_x(deg(90.0));
+ let to_axis = Quat::from_rotation_arc(Vec3::Y, axis);
+ Geometry::merge((0..count).map(|i| {
+ let p = from.lerp(to, (i as f32 + 0.5) / count as f32);
+ ring.clone().rotate(to_axis).translate(p.x, p.y, p.z)
+ }))
+}
+
+/// A corrugated hose: a tube with rings along `path`.
+fn conduit(path: &[Vec3], radius: f32) -> (Geometry, Geometry) {
+ let tube = Geometry::tube(path, radius, 14);
+ let mut rings = Vec::new();
+ let mut along = 0.0f32;
+ for w in path.windows(2) {
+ let (a, b) = (w[0], w[1]);
+ let len = a.distance(b);
+ let dir = (b - a).normalize_or(Vec3::Y);
+ let mut s = (0.035 - along).max(0.0);
+ while s < len {
+ let p = a + dir * s;
+ rings.push(
+ Geometry::torus(radius * 1.02, radius * 0.18, 6, 18)
+ .rotate_x(deg(90.0))
+ .rotate(Quat::from_rotation_arc(Vec3::Y, dir))
+ .translate(p.x, p.y, p.z),
+ );
+ s += 0.035;
+ }
+ along = s - len;
+ }
+ (tube, Geometry::merge(rings))
+}
+
+/// A warning label at `at` that faces `normal` (X or Z). It is a yellow triangle with a black
+/// border and an exclamation mark.
+fn warning(scene: &mut Scene, parent: NodeId, p: &Palette, at: Vec3, normal: Vec3, size: f32) {
+ let tri = Geometry::polygon(size, 3);
+ let to_normal = Quat::from_rotation_arc(Vec3::Z, normal);
+ let place = |g: Geometry, out: f32| {
+ g.rotate(to_normal).translate(
+ at.x + normal.x * out,
+ at.y + normal.y * out,
+ at.z + normal.z * out,
+ )
+ };
+ scene.add_to(
+ parent,
+ Node::mesh(
+ place(Geometry::extrude(&tri, 0.003, 0.0), 0.0),
+ p.dark.clone(),
+ ),
+ );
+ scene.add_to(
+ parent,
+ Node::mesh(
+ place(
+ Geometry::extrude(&Geometry::polygon(size * 0.78, 3), 0.003, 0.0).translate(
+ 0.0,
+ -size * 0.04,
+ 0.0,
+ ),
+ 0.002,
+ ),
+ p.yellow.clone(),
+ ),
+ );
+ let mark = Geometry::merge([
+ Geometry::rounded_box(size * 0.12, size * 0.42, 0.003, size * 0.03, 1).translate(
+ 0.0,
+ size * 0.02,
+ 0.0,
+ ),
+ Geometry::cylinder(size * 0.07, size * 0.07, 0.003, 12)
+ .rotate_x(deg(90.0))
+ .translate(0.0, -size * 0.32, 0.0),
+ ]);
+ scene.add_to(parent, Node::mesh(place(mark, 0.004), p.dark.clone()));
+}
+
+/// Raised lettering, turned by `rotation` and centered on `at`. It adds nothing when the
+/// font cannot make the text.
+#[allow(clippy::too_many_arguments)]
+fn lettering(
+ scene: &mut Scene,
+ parent: NodeId,
+ material: &Material,
+ font: &[u8],
+ text: &str,
+ size: f32,
+ at: Vec3,
+ rotation: Quat,
+) {
+ if let Ok(g) = Geometry::text(font, text, size, 0.006, 0.0012) {
+ let c = g.bounds().center();
+ scene.add_to(
+ parent,
+ Node::mesh(
+ g.translate(-c.x, -c.y, 0.0)
+ .rotate(rotation)
+ .translate(at.x, at.y, at.z),
+ material.clone(),
+ ),
+ );
+ }
+}
+
+/// A motor along `axis` from `at`: body, fins, end cap with bolts and a connector.
+fn motor(
+ scene: &mut Scene,
+ parent: NodeId,
+ p: &Palette,
+ at: Vec3,
+ axis: Vec3,
+ radius: f32,
+ length: f32,
+) {
+ let to_axis = Quat::from_rotation_arc(Vec3::Y, axis);
+ let center = at + axis * (length * 0.5);
+ scene.add_to(
+ parent,
+ Node::mesh(
+ Geometry::cylinder(radius, radius, length, 48)
+ .rotate(to_axis)
+ .translate(center.x, center.y, center.z),
+ p.white.clone(),
+ ),
+ );
+ scene.add_to(
+ parent,
+ Node::mesh(
+ fins(
+ 7,
+ radius + 0.004,
+ at + axis * (length * 0.15),
+ at + axis * (length * 0.75),
+ ),
+ p.graphite.clone(),
+ ),
+ );
+ let cap_at = at + axis * (length + 0.015);
+ scene.add_to(
+ parent,
+ Node::mesh(
+ Geometry::cylinder(radius * 0.92, radius * 0.92, 0.03, 48)
+ .rotate(to_axis)
+ .translate(cap_at.x, cap_at.y, cap_at.z),
+ p.graphite.clone(),
+ ),
+ );
+ scene.add_to(
+ parent,
+ Node::mesh(
+ bolt_circle(6, radius * 0.7, 0.008, at + axis * (length + 0.03), axis),
+ p.chrome.clone(),
+ ),
+ );
+ let side = if axis.y.abs() > 0.5 { Vec3::Z } else { Vec3::Y };
+ let plug_at = at + axis * (length * 0.85) + side * radius;
+ scene.add_to(
+ parent,
+ Node::mesh(
+ Geometry::rounded_box(0.05, 0.05, 0.05, 0.012, 2)
+ .translate(plug_at.x, plug_at.y, plug_at.z),
+ p.dark.clone(),
+ ),
+ );
+ let nut = at + axis * (length * 0.85) + side * (radius + 0.035);
+ scene.add_to(
+ parent,
+ Node::mesh(rod(0.016, 0.03, nut, side, 6), p.chrome.clone()),
+ );
+}
+
+impl Arm {
+ pub fn build(scene: &mut Scene, p: &Palette, font: &[u8]) -> Arm {
+ // ---- The base, bolted to the floor.
+ let base = scene.add(Node::group().named("base"));
+ scene.add_to(
+ base,
+ Node::mesh(
+ Geometry::rounded_box(1.0, 0.05, 1.0, 0.02, 3).translate(0.0, 0.025, 0.0),
+ p.graphite.clone(),
+ ),
+ );
+ let anchors = Geometry::merge(
+ [
+ (-1.0f32, -1.0f32),
+ (1.0, -1.0),
+ (-1.0, 1.0),
+ (1.0, 1.0),
+ (0.0, -1.0),
+ (0.0, 1.0),
+ (-1.0, 0.0),
+ (1.0, 0.0),
+ ]
+ .iter()
+ .map(|(x, z)| bolt_circle(1, 0.0, 0.026, vec3(x * 0.43, 0.05, z * 0.43), Vec3::Y)),
+ );
+ scene.add_to(base, Node::mesh(anchors, p.chrome.clone()));
+ let column = [
+ vec2(0.0, 0.05),
+ vec2(0.36, 0.05),
+ vec2(0.36, 0.09),
+ vec2(0.31, 0.13),
+ vec2(0.3, 0.37),
+ vec2(0.335, 0.405),
+ vec2(0.335, 0.45),
+ vec2(0.0, 0.45),
+ ];
+ scene.add_to(
+ base,
+ Node::mesh(Geometry::lathe(&column, 96), p.white.clone()),
+ );
+ let ribs = Geometry::merge((0..28).map(|i| {
+ let a = i as f32 / 28.0 * TAU;
+ Geometry::rounded_box(0.014, 0.2, 0.045, 0.005, 1)
+ .translate(0.0, 0.25, 0.3)
+ .rotate_y(a)
+ }));
+ scene.add_to(base, Node::mesh(ribs, p.graphite.clone()));
+ let ring = scene.add_to(
+ base,
+ Node::mesh(
+ Geometry::torus(0.336, 0.008, 8, 128)
+ .rotate_x(deg(90.0))
+ .translate(0.0, 0.385, 0.0),
+ Material::standard(0x111111).emissive(0xff4a00, 0.0),
+ ),
+ );
+ // The ring tints the floor around the base. Point lights cast no shadows, so the
+ // light passes through the column.
+ let ring_light = scene.add_to(
+ base,
+ Node::light(Light::point(0xff4a00, 0.0, 1.6)).at(0.0, 0.385, 0.0),
+ );
+ // The cable goes through a drag chain into a box on the floor.
+ scene.add_to(
+ base,
+ Node::mesh(
+ Geometry::rounded_box(0.18, 0.14, 0.1, 0.02, 2).translate(0.0, 0.2, -0.32),
+ p.dark.clone(),
+ ),
+ );
+ let chain_path: Vec<Vec3> = (0..=40)
+ .map(|i| {
+ let t = i as f32 / 40.0;
+ let a = t * PI;
+ vec3(
+ -0.9 * t,
+ 0.06 + 0.16 * a.sin() * (1.0 - t * 0.5),
+ -0.45 - 0.55 * t,
+ )
+ })
+ .collect();
+ let links = Geometry::merge(
+ chain_path
+ .windows(2)
+ .enumerate()
+ .filter(|(i, _)| i % 2 == 0)
+ .map(|(_, w)| {
+ let dir = (w[1] - w[0]).normalize_or(Vec3::X);
+ let mid = (w[0] + w[1]) * 0.5;
+ Geometry::rounded_box(0.09, 0.05, 0.06, 0.01, 1)
+ .rotate(Quat::from_rotation_arc(Vec3::Z, dir))
+ .translate(mid.x, mid.y, mid.z)
+ }),
+ );
+ scene.add_to(base, Node::mesh(links, p.dark.clone()));
+ scene.add_to(
+ base,
+ Node::mesh(
+ Geometry::rounded_box(0.32, 0.16, 0.24, 0.03, 2).translate(-0.98, 0.08, -1.02),
+ p.graphite.clone(),
+ ),
+ );
+ scene.add_to(
+ base,
+ Node::mesh(
+ Geometry::rounded_box(0.2, 0.004, 0.12, 0.002, 1).translate(-0.98, 0.162, -1.02),
+ p.yellow.clone(),
+ ),
+ );
+
+ // ---- J1: the turret.
+ let j1 = scene.add_to(base, Node::group());
+ scene.add_to(
+ j1,
+ Node::mesh(
+ Geometry::cylinder(0.34, 0.345, 0.07, 96).translate(0.0, 0.035, 0.0),
+ p.graphite.clone(),
+ ),
+ );
+ scene.add_to(
+ j1,
+ Node::mesh(
+ bolt_circle(16, 0.3, 0.011, vec3(0.0, 0.07, 0.0), Vec3::Y),
+ p.chrome.clone(),
+ ),
+ );
+ let cheek = hull(&[
+ (vec2(A1, J2_UP), 0.235),
+ (vec2(-0.08, 0.13), 0.22),
+ (vec2(0.18, 0.1), 0.2),
+ ]);
+ let inner = hull(&[(vec2(A1, J2_UP), 0.17), (vec2(-0.04, 0.16), 0.15)]);
+ for x in [-0.25f32, 0.25] {
+ scene.add_to(
+ j1,
+ Node::mesh(side_plate(&cheek, 0.09, 0.025, x), p.white.clone()),
+ );
+ scene.add_to(
+ j1,
+ Node::mesh(
+ side_plate(&inner, 0.02, 0.006, x * 1.24),
+ p.graphite.clone(),
+ ),
+ );
+ }
+ scene.add_to(
+ j1,
+ Node::mesh(
+ Geometry::rounded_box(0.42, 0.18, 0.44, 0.05, 3).translate(0.0, 0.13, 0.02),
+ p.white.clone(),
+ ),
+ );
+ let vents = Geometry::merge((0..6).map(|i| {
+ Geometry::rounded_box(0.22, 0.012, 0.01, 0.004, 1).translate(
+ 0.0,
+ 0.08 + i as f32 * 0.022,
+ 0.245,
+ )
+ }));
+ scene.add_to(j1, Node::mesh(vents, p.dark.clone()));
+ motor(scene, j1, p, vec3(0.0, 0.1, -0.33), Vec3::Y, 0.1, 0.3);
+ motor(
+ scene,
+ j1,
+ p,
+ vec3(-0.33, J2_UP, A1),
+ Vec3::NEG_X,
+ 0.125,
+ 0.22,
+ );
+ scene.add_to(
+ j1,
+ Node::mesh(axle(0.2, 0.42, 0.0, J2_UP, A1), p.graphite.clone()),
+ );
+ for x in [-0.302f32, 0.302] {
+ scene.add_to(
+ j1,
+ Node::mesh(axle(0.12, 0.02, x, J2_UP, A1), p.chrome.clone()),
+ );
+ scene.add_to(
+ j1,
+ Node::mesh(
+ bolt_circle(
+ 10,
+ 0.155,
+ 0.01,
+ vec3(x * 1.03, J2_UP, A1),
+ Vec3::X * x.signum(),
+ ),
+ p.chrome.clone(),
+ ),
+ );
+ }
+ warning(scene, j1, p, vec3(0.30, 0.17, -0.02), Vec3::X, 0.045);
+ lettering(
+ scene,
+ j1,
+ &p.dark,
+ font,
+ "07",
+ 0.11,
+ vec3(-0.30, 0.18, -0.03),
+ Quat::from_rotation_y(-FRAC_PI_2),
+ );
+
+ // ---- J2: the upper arm.
+ let j2 = scene.add_to(j1, Node::group());
+ let beam = hull(&[(vec2(0.0, 0.0), 0.19), (vec2(0.0, L2), 0.15)]);
+ scene.add_to(
+ j2,
+ Node::mesh(side_plate(&beam, 0.3, 0.035, 0.0), p.white.clone()),
+ );
+ let panel = hull(&[(vec2(0.0, 0.25), 0.1), (vec2(0.0, L2 - 0.25), 0.08)]);
+ for x in [-0.155f32, 0.155] {
+ scene.add_to(
+ j2,
+ Node::mesh(side_plate(&panel, 0.016, 0.005, x), p.graphite.clone()),
+ );
+ let side = if x > 0.0 { FRAC_PI_2 } else { -FRAC_PI_2 };
+ lettering(
+ scene,
+ j2,
+ &p.chrome,
+ font,
+ "FFRAMES",
+ 0.06,
+ vec3(x * 1.06, L2 * 0.52, 0.0),
+ Quat::from_rotation_y(side) * Quat::from_rotation_z(FRAC_PI_2),
+ );
+ }
+ scene.add_to(
+ j2,
+ Node::mesh(
+ Geometry::rounded_box(0.004, L2 * 0.5, 0.012, 0.002, 1).translate(
+ 0.165,
+ L2 * 0.5,
+ 0.11,
+ ),
+ Material::standard(0x111111).emissive(0xff4a00, 1.6),
+ ),
+ );
+ let cable: Vec<Vec3> = (0..=16)
+ .map(|i| {
+ let t = i as f32 / 16.0;
+ vec3(0.09, 0.08 + t * (L2 - 0.16), -0.2 - 0.05 * (t * PI).sin())
+ })
+ .collect();
+ let (hose, rings) = conduit(&cable, 0.024);
+ scene.add_to(j2, Node::mesh(hose, p.rubber.clone()));
+ scene.add_to(j2, Node::mesh(rings, p.rubber.clone()));
+ let cable2: Vec<Vec3> = cable.iter().map(|c| *c + vec3(-0.07, 0.0, 0.005)).collect();
+ scene.add_to(
+ j2,
+ Node::mesh(Geometry::tube(&cable2, 0.014, 12), p.dark.clone()),
+ );
+ let clamps = Geometry::merge((1..4).map(|i| {
+ Geometry::rounded_box(0.16, 0.03, 0.07, 0.01, 2).translate(
+ 0.055,
+ 0.08 + i as f32 * 0.25,
+ -0.2 - 0.05 * (i as f32 * 0.25 / 0.9 * PI).sin(),
+ )
+ }));
+ scene.add_to(j2, Node::mesh(clamps, p.chrome.clone()));
+ for y in [0.35f32, 0.75] {
+ scene.add_to(
+ j2,
+ Node::mesh(
+ Geometry::torus(0.022, 0.006, 8, 20).translate(0.0, y, 0.17),
+ p.chrome.clone(),
+ ),
+ );
+ }
+ scene.add_to(
+ j2,
+ Node::mesh(axle(0.16, 0.36, 0.0, L2, 0.0), p.graphite.clone()),
+ );
+ for x in [-0.19f32, 0.19] {
+ scene.add_to(
+ j2,
+ Node::mesh(axle(0.09, 0.02, x, L2, 0.0), p.chrome.clone()),
+ );
+ scene.add_to(
+ j2,
+ Node::mesh(
+ bolt_circle(
+ 8,
+ 0.12,
+ 0.009,
+ vec3(x * 1.06, L2, 0.0),
+ Vec3::X * x.signum(),
+ ),
+ p.chrome.clone(),
+ ),
+ );
+ }
+ motor(scene, j2, p, vec3(0.18, L2, 0.0), Vec3::X, 0.1, 0.16);
+
+ // ---- J3: the forearm, with the three wrist motors at the back.
+ let j3 = scene.add_to(j2, Node::group());
+ scene.add_to(
+ j3,
+ Node::mesh(
+ Geometry::rounded_box(0.3, 0.3, 0.34, 0.07, 4).translate(0.0, A3, -0.18),
+ p.white.clone(),
+ ),
+ );
+ let grille = Geometry::merge((0..5).map(|i| {
+ Geometry::rounded_box(0.012, 0.16, 0.01, 0.004, 1).translate(
+ 0.152,
+ A3,
+ -0.26 + i as f32 * 0.03,
+ )
+ }));
+ scene.add_to(j3, Node::mesh(grille.clone(), p.dark.clone()));
+ scene.add_to(j3, Node::mesh(grille.scale(-1.0, 1.0, 1.0), p.dark.clone()));
+ for (x, y) in [(-0.07f32, 0.07f32), (0.07, 0.07), (0.0, -0.07)] {
+ motor(
+ scene,
+ j3,
+ p,
+ vec3(x, A3 + y, -0.35),
+ Vec3::NEG_Z,
+ 0.05,
+ 0.12,
+ );
+ }
+ scene.add_to(
+ j3,
+ Node::mesh(
+ Geometry::cylinder(0.105, 0.13, 0.5, 64)
+ .rotate_x(deg(90.0))
+ .translate(0.0, A3, 0.27),
+ p.white.clone(),
+ ),
+ );
+ scene.add_to(
+ j3,
+ Node::mesh(
+ Geometry::torus(0.11, 0.012, 10, 64)
+ .translate(0.0, A3, 0.535)
+ .rotate_x(0.0),
+ p.graphite.clone(),
+ ),
+ );
+ let leds = Geometry::merge((0..3).map(|i| {
+ Geometry::sphere(0.007, 12, 6).translate(0.0, A3 + 0.12, 0.2 + i as f32 * 0.03)
+ }));
+ scene.add_to(
+ j3,
+ Node::mesh(leds, Material::standard(0x111111).emissive(0x7dffb0, 3.0)),
+ );
+ warning(scene, j3, p, vec3(0.118, A3 + 0.02, 0.35), Vec3::X, 0.035);
+
+ // ---- J4: the front of the forearm rolls.
+ let j4 = scene.add_to(j3, Node::group());
+ scene.add_to(
+ j4,
+ Node::mesh(
+ Geometry::torus(0.1, 0.01, 10, 64)
+ .translate(0.0, 0.0, -0.06)
+ .rotate_x(0.0),
+ p.graphite.clone(),
+ ),
+ );
+ scene.add_to(
+ j4,
+ Node::mesh(
+ Geometry::cylinder(0.095, 0.1, 0.24, 64)
+ .rotate_x(deg(90.0))
+ .translate(0.0, 0.0, 0.06),
+ p.white.clone(),
+ ),
+ );
+ scene.add_to(
+ j4,
+ Node::mesh(
+ Geometry::torus(0.092, 0.008, 8, 64)
+ .rotate_x(deg(90.0))
+ .translate(0.0, 0.0, 0.19),
+ p.graphite.clone(),
+ ),
+ );
+ scene.add_to(
+ j4,
+ Node::mesh(
+ bolt_circle(8, 0.075, 0.006, vec3(0.0, 0.0, 0.18), Vec3::Z),
+ p.chrome.clone(),
+ ),
+ );
+ let fork = hull(&[(vec2(0.2, 0.0), 0.06), (vec2(L3 - J4_AT, 0.0), 0.075)]);
+ for x in [-0.085f32, 0.085] {
+ scene.add_to(
+ j4,
+ Node::mesh(side_plate(&fork, 0.03, 0.008, x), p.graphite.clone()),
+ );
+ }
+
+ // ---- J5: the wrist.
+ let j5 = scene.add_to(j4, Node::group());
+ scene.add_to(
+ j5,
+ Node::mesh(axle(0.065, 0.14, 0.0, 0.0, 0.0), p.white.clone()),
+ );
+ for x in [-0.104f32, 0.104] {
+ scene.add_to(
+ j5,
+ Node::mesh(axle(0.045, 0.012, x, 0.0, 0.0), p.chrome.clone()),
+ );
+ scene.add_to(
+ j5,
+ Node::mesh(
+ bolt_circle(
+ 5,
+ 0.032,
+ 0.005,
+ vec3(x * 1.08, 0.0, 0.0),
+ Vec3::X * x.signum(),
+ ),
+ p.dark.clone(),
+ ),
+ );
+ }
+ scene.add_to(
+ j5,
+ Node::mesh(
+ Geometry::cylinder(0.055, 0.06, 0.13, 48)
+ .rotate_x(deg(90.0))
+ .translate(0.0, 0.0, 0.08),
+ p.white.clone(),
+ ),
+ );
+
+ // ---- J6: the flange, the tool changer, the gripper and the eye.
+ let j6 = scene.add_to(j5, Node::group());
+ scene.add_to(
+ j6,
+ Node::mesh(
+ Geometry::cylinder(0.068, 0.068, 0.022, 48)
+ .rotate_x(deg(90.0))
+ .translate(0.0, 0.0, 0.011),
+ p.chrome.clone(),
+ ),
+ );
+ scene.add_to(
+ j6,
+ Node::mesh(
+ bolt_circle(6, 0.05, 0.007, vec3(0.0, 0.0, 0.022), Vec3::Z),
+ p.dark.clone(),
+ ),
+ );
+ scene.add_to(
+ j6,
+ Node::mesh(
+ Geometry::cylinder(0.058, 0.058, 0.03, 48)
+ .rotate_x(deg(90.0))
+ .translate(0.0, 0.0, 0.04),
+ p.graphite.clone(),
+ ),
+ );
+ scene.add_to(
+ j6,
+ Node::mesh(
+ Geometry::torus(0.058, 0.004, 6, 48)
+ .rotate_x(deg(90.0))
+ .translate(0.0, 0.0, 0.056),
+ p.chrome.clone(),
+ ),
+ );
+ scene.add_to(
+ j6,
+ Node::mesh(
+ Geometry::rounded_box(0.26, 0.085, 0.08, 0.02, 3).translate(0.0, 0.0, 0.104),
+ p.graphite.clone(),
+ ),
+ );
+ for y in [0.035f32, -0.035] {
+ scene.add_to(
+ j6,
+ Node::mesh(
+ Geometry::rounded_box(0.24, 0.016, 0.014, 0.005, 1).translate(0.0, y, 0.15),
+ p.chrome.clone(),
+ ),
+ );
+ }
+ let screws = Geometry::merge(
+ [-0.1f32, -0.05, 0.05, 0.1]
+ .iter()
+ .map(|x| rod(0.006, 0.006, vec3(*x, -0.044, 0.104), Vec3::NEG_Y, 6)),
+ );
+ scene.add_to(j6, Node::mesh(screws, p.chrome.clone()));
+ for x in [-0.07f32, 0.07] {
+ scene.add_to(
+ j6,
+ Node::mesh(
+ rod(0.011, 0.03, vec3(x, -0.05, 0.08), Vec3::NEG_Y, 12),
+ p.chrome.clone(),
+ ),
+ );
+ let hose = Geometry::tube(
+ &[
+ vec3(x, -0.06, 0.08),
+ vec3(x * 0.8, -0.1, 0.03),
+ vec3(x * 0.4, -0.1, -0.05),
+ vec3(0.0, -0.08, -0.12),
+ ],
+ 0.007,
+ 8,
+ );
+ scene.add_to(j6, Node::mesh(hose, p.rubber.clone()));
+ }
+ let status = scene.add_to(
+ j6,
+ Node::mesh(
+ Geometry::sphere(0.008, 16, 8).translate(0.11, -0.043, 0.09),
+ Material::standard(0x111111).emissive(0xff4a00, 0.0),
+ ),
+ );
+ // The eye is a camera module on top of the gripper. It looks along the tool axis.
+ let cam = Geometry::rounded_box(0.11, 0.06, 0.09, 0.018, 3).translate(
+ EYE.x,
+ EYE.y - 0.002,
+ EYE.z - 0.04,
+ );
+ scene.add_to(j6, Node::mesh(cam, p.white.clone()));
+ scene.add_to(
+ j6,
+ Node::mesh(
+ Geometry::cylinder(0.026, 0.03, 0.03, 40)
+ .rotate_x(deg(90.0))
+ .translate(EYE.x, EYE.y, EYE.z + 0.015),
+ p.graphite.clone(),
+ ),
+ );
+ scene.add_to(
+ j6,
+ Node::mesh(
+ Geometry::torus(0.024, 0.004, 8, 40).translate(EYE.x, EYE.y, EYE.z + 0.03),
+ p.chrome.clone(),
+ ),
+ );
+ scene.add_to(
+ j6,
+ Node::mesh(
+ Geometry::sphere_partial(0.021, 32, 12, 0.0, deg(60.0))
+ .rotate_x(deg(90.0))
+ .translate(EYE.x, EYE.y, EYE.z + 0.02),
+ p.glass.clone(),
+ ),
+ );
+ let iris = scene.add_to(
+ j6,
+ Node::mesh(
+ Geometry::circle(0.008, 24),
+ Material::standard(0x111111).emissive(0xffb070, 0.0),
+ )
+ .at(EYE.x, EYE.y, EYE.z + 0.0325),
+ );
+ let lid = scene.add_to(
+ j6,
+ Node::mesh(
+ Geometry::rounded_box(0.056, 0.03, 0.006, 0.003, 1),
+ p.graphite.clone(),
+ )
+ .at(EYE.x, EYE.y + 0.03, EYE.z + 0.036),
+ );
+ // The eye lights what it looks at, along the tool axis (+Z). In the dark lab its
+ // beam shows in the air: a glow cone, see `effects::beam`.
+ let lens = vec3(EYE.x, EYE.y, EYE.z + 0.034);
+ let eye_light = scene.add_to(
+ j6,
+ Node::light(Light::spot(EYE_LIGHT, 0.0, deg(17.0), 0.55).pointing(Vec3::Z))
+ .with_position(lens),
+ );
+ let beam = scene.add_to(
+ j6,
+ Node::mesh(
+ crate::effects::beam(2.6, 0.8),
+ Material::glow(EYE_LIGHT, 0.0),
+ )
+ .with_position(lens)
+ .shadows(false, false),
+ );
+ let fingers = [-1.0f32, 1.0].map(|x| {
+ let finger = scene.add_to(j6, Node::group());
+ scene.add_to(
+ finger,
+ Node::mesh(
+ Geometry::rounded_box(0.03, 0.06, 0.07, 0.008, 2).translate(
+ x * 0.015,
+ 0.0,
+ 0.155,
+ ),
+ p.graphite.clone(),
+ ),
+ );
+ scene.add_to(
+ finger,
+ Node::mesh(
+ Geometry::rounded_box(0.024, 0.055, 0.12, 0.007, 2).translate(
+ x * 0.012,
+ 0.0,
+ 0.215,
+ ),
+ p.white.clone(),
+ ),
+ );
+ scene.add_to(
+ finger,
+ Node::mesh(
+ Geometry::rounded_box(0.008, 0.05, 0.06, 0.003, 1).translate(
+ -x * 0.003,
+ 0.0,
+ 0.245,
+ ),
+ p.rubber.clone(),
+ ),
+ );
+ let bolts = Geometry::merge(
+ [0.14f32, 0.17]
+ .iter()
+ .map(|z| rod(0.005, 0.004, vec3(x * 0.031, 0.0, *z), Vec3::X * x, 6)),
+ );
+ scene.add_to(finger, Node::mesh(bolts, p.chrome.clone()));
+ finger
+ });
+
+ // A gas spring between the turret and the upper arm balances the arm.
+ let spring_body = scene.add(Node::group());
+ scene.add_to(
+ spring_body,
+ Node::mesh(
+ Geometry::cylinder(0.045, 0.045, 0.42, 32).translate(0.0, 0.21, 0.0),
+ p.graphite.clone(),
+ ),
+ );
+ scene.add_to(
+ spring_body,
+ Node::mesh(
+ Geometry::torus(0.046, 0.005, 6, 32).translate(0.0, 0.4, 0.0),
+ p.chrome.clone(),
+ ),
+ );
+ scene.add_to(
+ spring_body,
+ Node::mesh(Geometry::sphere(0.05, 24, 12), p.chrome.clone()),
+ );
+ let spring_rod = scene.add(Node::group());
+ scene.add_to(
+ spring_rod,
+ Node::mesh(
+ Geometry::cylinder(0.018, 0.018, 0.45, 16).translate(0.0, 0.225, 0.0),
+ p.chrome.clone(),
+ ),
+ );
+ scene.add_to(
+ spring_rod,
+ Node::mesh(Geometry::sphere(0.035, 24, 12), p.chrome.clone()),
+ );
+
+ Arm {
+ joints: [j1, j2, j3, j4, j5, j6],
+ fingers,
+ spring_body,
+ spring_rod,
+ status,
+ ring,
+ iris,
+ lid,
+ eye_light,
+ beam,
+ ring_light,
+ }
+ }
+
+ /// Poses the arm. `gap` is half the distance between the finger pads.
+ pub fn apply(&self, scene: &mut Scene, q: &Joints, gap: f32, face: &Expression) {
+ for (node, local) in self.joints.iter().zip(chain(q)) {
+ let (_, rotation, translation) = local.to_scale_rotation_translation();
+ let n = &mut scene[*node];
+ n.position = translation;
+ n.rotation = rotation;
+ }
+ let gap = gap.clamp(0.0, OPEN);
+ scene[self.fingers[0]].position = vec3(-gap, 0.0, 0.0);
+ scene[self.fingers[1]].position = vec3(gap, 0.0, 0.0);
+
+ let a = scene.local_to_world(self.joints[0], vec3(0.0, 0.16, -0.27));
+ let b = scene.local_to_world(self.joints[1], vec3(0.0, 0.42, -0.19));
+ let dir = (b - a).normalize_or(Vec3::Y);
+ scene[self.spring_body].position = a;
+ scene[self.spring_body].rotation = Quat::from_rotation_arc(Vec3::Y, dir);
+ scene[self.spring_rod].position = b;
+ scene[self.spring_rod].rotation = Quat::from_rotation_arc(Vec3::Y, -dir);
+
+ let glow = |scene: &mut Scene, node: NodeId, value: f32| {
+ if let Some(m) = scene[node].material_mut() {
+ m.emissive_intensity = value;
+ }
+ };
+ glow(scene, self.ring, face.ring);
+ glow(scene, self.status, face.status);
+ glow(scene, self.iris, face.eye);
+ let lid = face.lid.clamp(0.0, 1.0);
+ scene[self.iris].scale = vec3(1.0, lid.max(0.05), 1.0);
+ scene[self.lid].position = vec3(EYE.x, EYE.y + 0.012 + 0.018 * lid, EYE.z + 0.036);
+ scene[self.lid].scale = vec3(1.0, 1.0 - 0.7 * lid, 1.0);
+
+ // The lights follow the glow: the eye light is off while the lid is closed.
+ let eye = face.eye * lid;
+ let set_light = |scene: &mut Scene, node: NodeId, value: f32| {
+ if let Some(light) = scene[node].light_mut() {
+ *light.intensity_mut() = value;
+ }
+ };
+ set_light(scene, self.eye_light, eye * 0.55);
+ set_light(scene, self.ring_light, face.ring * 0.08);
+ let beam = eye * face.beam;
+ scene[self.beam].visible = beam > 0.0;
+ if let Some(m) = scene[self.beam].material_mut() {
+ m.color = Rgb::hex(EYE_LIGHT) * beam * 0.05;
+ }
+ }
+}
diff --git a/examples/arm/src/bin/soundtrack.rs b/examples/arm/src/bin/soundtrack.rs
new file mode 100644
index 00000000..2bba437e
--- /dev/null
+++ b/examples/arm/src/bin/soundtrack.rs
@@ -0,0 +1,1024 @@
+//! Synthesizes the sound of FFRAMES, ASSEMBLED into `dynamic_media/`. The music follows the
+//! story beats, and the servo sound follows the joint speeds of the animation.
+//!
+//! `cargo run --release -p arm-example --bin arm-soundtrack`
+
+use std::f32::consts::{PI, TAU};
+use std::path::Path;
+
+use arm_example::Show;
+use arm_example::effects::hash;
+use fframes::three_d::math::smoothstep;
+
+/// Samples per second.
+const RATE: f32 = 48_000.0;
+
+// ------------------------------------------------------------------ Building blocks
+
+/// White noise from a fixed seed (xorshift).
+struct Noise(u32);
+
+impl Noise {
+ fn next(&mut self) -> f32 {
+ self.0 ^= self.0 << 13;
+ self.0 ^= self.0 >> 17;
+ self.0 ^= self.0 << 5;
+ (self.0 as f32 / u32::MAX as f32) * 2.0 - 1.0
+ }
+}
+
+/// An RBJ biquad filter. Call `set` for each sample to sweep the filter.
+#[derive(Default, Clone)]
+struct Biquad {
+ b0: f32,
+ b1: f32,
+ b2: f32,
+ a1: f32,
+ a2: f32,
+ x1: f32,
+ x2: f32,
+ y1: f32,
+ y2: f32,
+}
+
+/// Low pass, high pass or band pass.
+#[derive(Clone, Copy)]
+enum Kind {
+ Low,
+ High,
+ Band,
+}
+
+impl Biquad {
+ fn new(kind: Kind, freq: f32, q: f32) -> Self {
+ let mut f = Self::default();
+ f.set(kind, freq, q);
+ f
+ }
+
+ fn set(&mut self, kind: Kind, freq: f32, q: f32) {
+ let w = TAU * freq.clamp(10.0, RATE * 0.45) / RATE;
+ let (sin, cos) = w.sin_cos();
+ let alpha = sin / (2.0 * q);
+ let a0 = 1.0 + alpha;
+ let (b0, b1, b2) = match kind {
+ Kind::Low => ((1.0 - cos) / 2.0, 1.0 - cos, (1.0 - cos) / 2.0),
+ Kind::High => (
+ f32::midpoint(1.0, cos),
+ -(1.0 + cos),
+ f32::midpoint(1.0, cos),
+ ),
+ Kind::Band => (alpha, 0.0, -alpha),
+ };
+ self.b0 = b0 / a0;
+ self.b1 = b1 / a0;
+ self.b2 = b2 / a0;
+ self.a1 = -2.0 * cos / a0;
+ self.a2 = (1.0 - alpha) / a0;
+ }
+
+ fn run(&mut self, x: f32) -> f32 {
+ let y = self.b0 * x + self.b1 * self.x1 + self.b2 * self.x2
+ - self.a1 * self.y1
+ - self.a2 * self.y2;
+ self.x2 = self.x1;
+ self.x1 = x;
+ self.y2 = self.y1;
+ self.y1 = y;
+ y
+ }
+}
+
+/// A band limited sawtooth (polyBLEP).
+#[derive(Default, Clone)]
+struct Saw {
+ phase: f32,
+}
+
+impl Saw {
+ fn next(&mut self, freq: f32) -> f32 {
+ let dt = (freq / RATE).min(0.5);
+ let mut y = 2.0 * self.phase - 1.0;
+ y -= blep(self.phase, dt);
+ self.phase += dt;
+ if self.phase >= 1.0 {
+ self.phase -= 1.0;
+ }
+ y
+ }
+}
+
+/// The polyBLEP correction near the jump of the sawtooth.
+fn blep(t: f32, dt: f32) -> f32 {
+ if t < dt {
+ let t = t / dt;
+ t + t - t * t - 1.0
+ } else if t > 1.0 - dt {
+ let t = (t - 1.0) / dt;
+ t * t + t + t + 1.0
+ } else {
+ 0.0
+ }
+}
+
+/// A sine oscillator.
+#[derive(Default, Clone)]
+struct Sine {
+ phase: f32,
+}
+
+impl Sine {
+ fn next(&mut self, freq: f32) -> f32 {
+ let y = (self.phase * TAU).sin();
+ self.phase = (self.phase + freq / RATE).fract();
+ y
+ }
+}
+
+/// The frequency of a MIDI note in Hz.
+fn note(midi: f32) -> f32 {
+ 440.0 * 2f32.powf((midi - 69.0) / 12.0)
+}
+
+/// Exponential decay from `t = 0`, silence before.
+fn decay(t: f32, rate: f32) -> f32 {
+ if t < 0.0 { 0.0 } else { (-t * rate).exp() }
+}
+
+/// A linear attack of `attack` seconds, then exponential decay.
+fn attack_decay(t: f32, attack: f32, rate: f32) -> f32 {
+ if t < 0.0 {
+ 0.0
+ } else if t < attack {
+ t / attack
+ } else {
+ (-(t - attack) * rate).exp()
+ }
+}
+
+/// A stereo buffer at [`RATE`].
+#[derive(Clone)]
+struct Track {
+ l: Vec<f32>,
+ r: Vec<f32>,
+}
+
+impl Track {
+ fn new(seconds: f32) -> Self {
+ let n = (seconds * RATE) as usize;
+ Self {
+ l: vec![0.0; n],
+ r: vec![0.0; n],
+ }
+ }
+
+ fn len(&self) -> usize {
+ self.l.len()
+ }
+
+ /// Adds a mono signal at `start` seconds. `pan` goes from -1 (left) to 1 (right) with
+ /// equal power.
+ fn add(&mut self, start: f32, signal: &[f32], gain: f32, pan: f32) {
+ let angle = (pan.clamp(-1.0, 1.0) + 1.0) * PI / 4.0;
+ let (gl, gr) = (angle.cos() * gain, angle.sin() * gain);
+ let offset = (start * RATE).round() as isize;
+ for (i, s) in signal.iter().enumerate() {
+ let j = offset + i as isize;
+ if j >= 0 && (j as usize) < self.l.len() {
+ self.l[j as usize] += s * gl;
+ self.r[j as usize] += s * gr;
+ }
+ }
+ }
+
+ /// Adds `other`, scaled by `gain`.
+ fn mix(&mut self, other: &Track, gain: f32) {
+ for i in 0..self.len().min(other.len()) {
+ self.l[i] += other.l[i] * gain;
+ self.r[i] += other.r[i] * gain;
+ }
+ }
+
+ /// Scales the track so that its peak is at `peak_db`.
+ fn normalize(&mut self, peak_db: f32) {
+ let peak = self
+ .l
+ .iter()
+ .chain(&self.r)
+ .fold(0.0f32, |m, s| m.max(s.abs()));
+ if peak > 0.0 {
+ let gain = 10f32.powf(peak_db / 20.0) / peak;
+ self.l
+ .iter_mut()
+ .chain(self.r.iter_mut())
+ .for_each(|s| *s *= gain);
+ }
+ }
+
+ /// Writes a 16 bit stereo WAV file.
+ fn write(&self, path: &Path) -> std::io::Result<()> {
+ let mut bytes = Vec::with_capacity(44 + self.len() * 4);
+ let data = (self.len() * 4) as u32;
+ bytes.extend_from_slice(b"RIFF");
+ bytes.extend_from_slice(&(36 + data).to_le_bytes());
+ bytes.extend_from_slice(b"WAVEfmt ");
+ bytes.extend_from_slice(&16u32.to_le_bytes());
+ bytes.extend_from_slice(&1u16.to_le_bytes());
+ bytes.extend_from_slice(&2u16.to_le_bytes());
+ bytes.extend_from_slice(&(RATE as u32).to_le_bytes());
+ bytes.extend_from_slice(&(RATE as u32 * 4).to_le_bytes());
+ bytes.extend_from_slice(&4u16.to_le_bytes());
+ bytes.extend_from_slice(&16u16.to_le_bytes());
+ bytes.extend_from_slice(b"data");
+ bytes.extend_from_slice(&data.to_le_bytes());
+ for i in 0..self.len() {
+ for s in [self.l[i], self.r[i]] {
+ bytes.extend_from_slice(&((s.clamp(-1.0, 1.0) * 32767.0) as i16).to_le_bytes());
+ }
+ }
+ std::fs::write(path, bytes)
+ }
+}
+
+/// A stereo reverb in the style of Freeverb.
+fn reverb(input: &Track, room: f32, damp: f32, wet: f32) -> Track {
+ let combs = [1116, 1188, 1277, 1356, 1422, 1491, 1557, 1617];
+ let allpasses = [556, 441, 341, 225];
+ let mut out = input.clone();
+ for (channel, spread) in [(0usize, 0usize), (1, 23)] {
+ let src = if channel == 0 { &input.l } else { &input.r };
+ let mut acc = vec![0.0f32; src.len()];
+ for &size in &combs {
+ let size = (size + spread) * 48 / 44;
+ let mut buf = vec![0.0f32; size];
+ let mut idx = 0;
+ let mut store = 0.0;
+ for (i, x) in src.iter().enumerate() {
+ let y = buf[idx];
+ store = y * (1.0 - damp) + store * damp;
+ buf[idx] = x * 0.015 + store * room;
+ idx = (idx + 1) % size;
+ acc[i] += y;
+ }
+ }
+ for &size in &allpasses {
+ let size = (size + spread) * 48 / 44;
+ let mut buf = vec![0.0f32; size];
+ let mut idx = 0;
+ for a in &mut acc {
+ let b = buf[idx];
+ let y = -*a + b;
+ buf[idx] = *a + b * 0.5;
+ idx = (idx + 1) % size;
+ *a = y;
+ }
+ }
+ let dst = if channel == 0 { &mut out.l } else { &mut out.r };
+ for (d, a) in dst.iter_mut().zip(&acc) {
+ *d = *d * (1.0 - wet * 0.3) + a * wet;
+ }
+ }
+ out
+}
+
+/// Samples `f(t)` for `seconds`.
+fn signal(seconds: f32, mut f: impl FnMut(f32) -> f32) -> Vec<f32> {
+ (0..(seconds * RATE) as usize)
+ .map(|i| f(i as f32 / RATE))
+ .collect()
+}
+
+/// A centered track from a mono signal, normalized to `peak_db`.
+fn mono(signal: &[f32], peak_db: f32) -> Track {
+ let mut t = Track::new(signal.len() as f32 / RATE);
+ t.add(0.0, signal, 1.0, 0.0);
+ t.normalize(peak_db);
+ t
+}
+
+// ------------------------------------------------------------------ Instruments
+
+/// Modal percussion. Each partial is (frequency ratio, amplitude, decay per second).
+fn modal(freq: f32, partials: &[(f32, f32, f32)], length: f32, mallet: f32, seed: u32) -> Vec<f32> {
+ let mut oscs: Vec<Sine> = partials.iter().map(|_| Sine::default()).collect();
+ let mut noise = Noise(seed);
+ let mut low = Biquad::new(Kind::Low, 3000.0, 0.7);
+ signal(length, |t| {
+ let tone: f32 = oscs
+ .iter_mut()
+ .zip(partials)
+ .map(|(o, (r, a, d))| o.next(freq * r) * a * decay(t, *d))
+ .sum();
+ let hit = low.run(noise.next()) * decay(t, 400.0) * mallet;
+ (tone + hit) * smoothstep(0.0, 0.002, t)
+ })
+}
+
+fn marimba(midi: f32, velocity: f32) -> Vec<f32> {
+ let v = velocity;
+ modal(
+ note(midi),
+ &[
+ (1.0, 1.0, 5.0),
+ (3.93, 0.28 * v, 14.0),
+ (9.2, 0.08 * v, 30.0),
+ ],
+ 1.0,
+ 0.5 * v,
+ midi as u32,
+ )
+ .into_iter()
+ .map(|s| s * v)
+ .collect()
+}
+
+fn glock(midi: f32, velocity: f32) -> Vec<f32> {
+ modal(
+ note(midi),
+ &[
+ (1.0, 1.0, 1.4),
+ (2.756, 0.45, 2.8),
+ (5.404, 0.2, 4.5),
+ (8.933, 0.08, 7.0),
+ ],
+ 2.2,
+ 0.3,
+ midi as u32 + 7,
+ )
+ .into_iter()
+ .map(|s| s * velocity)
+ .collect()
+}
+
+fn music_box(midi: f32) -> Vec<f32> {
+ modal(
+ note(midi),
+ &[(1.0, 1.0, 1.8), (3.0, 0.15, 5.0), (4.2, 0.08, 7.0)],
+ 2.0,
+ 0.1,
+ midi as u32 + 13,
+ )
+}
+
+/// Karplus-Strong plucked string.
+fn pluck(midi: f32, length: f32, damping: f32, seed: u32) -> Vec<f32> {
+ let freq = note(midi);
+ let n = (RATE / freq).max(2.0) as usize;
+ let mut noise = Noise(seed);
+ let mut low = Biquad::new(Kind::Low, freq * 6.0, 0.7);
+ let mut buf: Vec<f32> = (0..n).map(|_| low.run(noise.next())).collect();
+ let mut i = 0;
+ signal(length, |t| {
+ let j = (i + 1) % n;
+ let y = buf[i];
+ buf[i] = f32::midpoint(buf[i], buf[j]) * damping;
+ i = j;
+ y * decay(t, 2.0)
+ })
+}
+
+/// A short pizzicato: a pluck that stops quickly.
+fn pizz(midi: f32, velocity: f32, seed: u32) -> Vec<f32> {
+ let s = pluck(midi, 0.45, 0.995, seed);
+ s.into_iter()
+ .enumerate()
+ .map(|(i, x)| x * velocity * decay(i as f32 / RATE, 7.0))
+ .collect()
+}
+
+/// A funny double reed: FM synthesis with a small vibrato.
+fn bassoon(midi: f32, length: f32, slide: f32) -> Vec<f32> {
+ let mut carrier = 0.0f32;
+ let mut modulator = 0.0f32;
+ let mut low = Biquad::new(Kind::Low, 1400.0, 0.8);
+ signal(length, |t| {
+ let f = note(midi + slide * (t / length))
+ * (1.0 + 0.008 * (t * 31.0).sin() * smoothstep(0.1, 0.3, t));
+ modulator = (modulator + f * 2.0 / RATE).fract();
+ let index = 1.8 * (0.6 + 0.4 * decay(t, 3.0));
+ carrier = (carrier + f / RATE).fract();
+ let y = (carrier * TAU + index * (modulator * TAU).sin()).sin();
+ low.run(y) * attack_decay(t, 0.03, 0.8) * (1.0 - smoothstep(length - 0.08, length, t))
+ })
+}
+
+fn soft_kick() -> Vec<f32> {
+ let mut osc = Sine::default();
+ signal(0.4, |t| {
+ (osc.next(48.0 + 70.0 * decay(t, 35.0)) * 1.4).tanh() * decay(t, 9.0)
+ })
+}
+
+fn brush(seed: u32) -> Vec<f32> {
+ let mut noise = Noise(seed);
+ let mut band = Biquad::new(Kind::Band, 3500.0, 0.6);
+ signal(0.25, |t| {
+ band.run(noise.next()) * attack_decay(t, 0.012, 14.0) * 0.8
+ })
+}
+
+fn shaker(seed: u32) -> Vec<f32> {
+ let mut noise = Noise(seed);
+ let mut high = Biquad::new(Kind::High, 6500.0, 0.7);
+ signal(0.08, |t| {
+ high.run(noise.next()) * attack_decay(t, 0.008, 60.0) * 0.5
+ })
+}
+
+fn pad(notes: &[f32], length: f32, attack: f32) -> Vec<f32> {
+ let mut saws: Vec<[Saw; 3]> = notes.iter().map(|_| Default::default()).collect();
+ let mut low = Biquad::new(Kind::Low, 1400.0, 0.6);
+ signal(length, |t| {
+ let raw: f32 = notes
+ .iter()
+ .zip(saws.iter_mut())
+ .map(|(n, s)| {
+ let f = note(*n);
+ s[0].next(f * 0.997) + s[1].next(f) + s[2].next(f * 1.003)
+ })
+ .sum();
+ low.run(raw)
+ * smoothstep(0.0, attack, t)
+ * (1.0 - smoothstep(length - 0.4, length, t))
+ * 0.06
+ })
+}
+
+fn crickets(length: f32, seed: u32) -> Vec<f32> {
+ let mut a = Sine::default();
+ let mut noise = Noise(seed);
+ signal(length, |t| {
+ // Each 0.7 s cycle has a chirp of three pulses. Some cycles are silent.
+ let cycle = (t / 0.7).floor();
+ let within = t - cycle * 0.7;
+ let on = hash(cycle as u32 + seed) > 0.25;
+ let pulse = (within * 32.0).fract() < 0.5 && within < 0.09;
+ let env = if on && pulse { 1.0 } else { 0.0 };
+ (a.next(4600.0 + 60.0 * noise.next()) * env) * 0.4
+ })
+}
+
+// ------------------------------------------------------------------ The score
+
+/// One beat at 120 BPM, in seconds.
+const BEAT: f32 = 0.5;
+
+/// Slows `track` down to a stop in `length` seconds from `at`, as a tape machine without
+/// power does. Everything after the stop is silent.
+fn tape_stop(track: &mut Track, at: f32, length: f32) {
+ let start = (at * RATE) as usize;
+ let n = (length * RATE) as usize;
+ let source = track.clone();
+ for i in 0..track.len().saturating_sub(start) {
+ let (l, r) = if i < n {
+ let s = i as f32 / n as f32;
+ // The read position moves with the speed (1 - s)^2.
+ let pos = start as f32 + n as f32 / 3.0 * (1.0 - (1.0 - s).powi(3));
+ let k = pos as usize;
+ let f = pos - k as f32;
+ let get = |v: &[f32]| {
+ v.get(k).copied().unwrap_or(0.0) * (1.0 - f)
+ + v.get(k + 1).copied().unwrap_or(0.0) * f
+ };
+ let fade = 1.0 - s * s;
+ (get(&source.l) * fade, get(&source.r) * fade)
+ } else {
+ (0.0, 0.0)
+ };
+ track.l[start + i] = l;
+ track.r[start + i] = r;
+ }
+}
+
+/// The marimba melody: eight eighth notes for each of the four bars.
+const PROGRESSION: [[f32; 8]; 4] = [
+ [72.0, 69.0, 65.0, 69.0, 72.0, 74.0, 72.0, 69.0],
+ [74.0, 69.0, 65.0, 69.0, 74.0, 76.0, 74.0, 69.0],
+ [74.0, 70.0, 65.0, 70.0, 74.0, 77.0, 74.0, 70.0],
+ [76.0, 72.0, 67.0, 72.0, 76.0, 79.0, 76.0, 72.0],
+];
+/// The bass note of each bar.
+const ROOTS: [f32; 4] = [41.0, 38.0, 34.0, 36.0];
+/// The pad chord of each bar.
+const CHORDS: [[f32; 3]; 4] = [
+ [65.0, 69.0, 72.0],
+ [62.0, 65.0, 69.0],
+ [58.0, 62.0, 65.0],
+ [60.0, 64.0, 67.0],
+];
+
+/// The groove from `from` to `to`. More `energy` (0 to 1) makes the drums louder and adds
+/// layers.
+fn groove(music: &mut Track, from: f32, to: f32, energy: f32, seed: u32) {
+ let eighth = BEAT / 2.0;
+ let steps = ((to - from) / eighth) as usize;
+ let k = soft_kick();
+ for s in 0..steps {
+ let t = from + s as f32 * eighth;
+ let bar = (s / 8) % 4;
+ let pos = s % 8;
+ let accent = if pos == 0 || pos == 3 || pos == 6 {
+ 1.0
+ } else {
+ 0.7
+ };
+ // The melody skips one note in odd bars. This gives it bounce.
+ if !(pos == 5 && bar % 2 == 1) {
+ music.add(
+ t,
+ &marimba(PROGRESSION[bar][pos], accent * 0.55),
+ 1.0,
+ if pos % 2 == 0 { -0.25 } else { 0.25 },
+ );
+ }
+ if pos == 0 || pos == 3 {
+ music.add(t, &pizz(ROOTS[bar], 0.9, seed + s as u32), 1.0, -0.1);
+ }
+ if pos == 4 {
+ music.add(
+ t,
+ &pizz(ROOTS[bar] + 7.0, 0.7, seed + s as u32 + 99),
+ 1.0,
+ -0.1,
+ );
+ }
+ if pos == 0 || pos == 4 {
+ music.add(t, &k, 0.55 + 0.25 * energy, 0.0);
+ }
+ if pos == 2 || pos == 6 {
+ music.add(t, &brush(seed + s as u32), 0.35 + 0.25 * energy, 0.15);
+ }
+ music.add(
+ t,
+ &shaker(seed + 700 + s as u32),
+ if pos % 2 == 1 { 0.3 } else { 0.18 },
+ 0.4,
+ );
+ if energy > 0.5 && pos == 0 {
+ let top = CHORDS[bar][2] + 12.0;
+ music.add(t, &glock(top + 12.0, 0.25), 1.0, 0.3);
+ music.add(t, &pad(&CHORDS[bar], BEAT * 4.0, 0.3), 1.0, 0.0);
+ }
+ }
+}
+
+fn score(show: &Show, length: f32) -> Track {
+ let b = show.story.beats;
+ let mut music = Track::new(length);
+ // Waking up: a music box over a soft pad.
+ let arp = [
+ 77.0, 81.0, 84.0, 88.0, 84.0, 81.0, 82.0, 86.0, 89.0, 86.0, 82.0, 81.0,
+ ];
+ let mut t = b.wake + 0.1;
+ let mut i = 0;
+ while t < b.work - 0.1 {
+ music.add(
+ t,
+ &music_box(arp[i % arp.len()]),
+ 0.22,
+ if i % 2 == 0 { -0.3 } else { 0.3 },
+ );
+ t += BEAT / 2.0;
+ i += 1;
+ }
+ music.add(
+ b.wake,
+ &pad(&[53.0, 57.0, 60.0, 64.0], b.work - b.wake + 0.3, 1.2),
+ 1.0,
+ 0.0,
+ );
+ // Work: the groove. It gets more energy when the robot gets too confident.
+ let cocky = b.drop - 2.0;
+ groove(&mut music, b.work, cocky, 0.0, 10);
+ groove(&mut music, cocky, b.drop + 1.0, 1.0, 400);
+ // A fast run of notes up into the drop.
+ for (k, n) in [72.0f32, 74.0, 76.0, 77.0, 79.0, 81.0, 82.0, 84.0]
+ .iter()
+ .enumerate()
+ {
+ music.add(b.drop - 0.5 + k as f32 * 0.055, &marimba(*n, 0.6), 1.0, 0.0);
+ }
+ tape_stop(&mut music, b.drop + 0.04, 0.55);
+
+ // The awkward silence: crickets.
+ let crickets_from = b.drop + 1.3;
+ let crick = crickets(b.recover - crickets_from - 0.3, 5);
+ music.add(crickets_from, &crick, 0.35, -0.6);
+ music.add(
+ crickets_from + 0.37,
+ &crickets(b.recover - crickets_from - 0.6, 9),
+ 0.25,
+ 0.6,
+ );
+ // A sad slide down, like a trombone, under the sigh.
+ music.add(b.recover - 1.25, &bassoon(46.0, 0.9, -3.0), 0.5, 0.0);
+
+ // The careful recovery: quiet, short plucks and a low reed.
+ let sneak = [53.0, 56.0, 60.0, 56.0, 55.0, 58.0, 61.0, 58.0];
+ let mut t = b.recover + 0.15;
+ let mut k = 0;
+ while t < b.finish - 0.6 {
+ if k % 4 != 3 {
+ music.add(
+ t,
+ &pizz(sneak[k % sneak.len()], 0.55, 900 + k as u32),
+ 1.0,
+ if k % 2 == 0 { -0.3 } else { 0.3 },
+ );
+ }
+ if k % 4 == 0 {
+ music.add(
+ t,
+ &bassoon(sneak[k % sneak.len()] - 12.0, 0.22, 0.0),
+ 0.35,
+ 0.0,
+ );
+ }
+ t += BEAT;
+ k += 1;
+ }
+
+ // Confident again, then the ta-da.
+ groove(&mut music, b.finish, b.tada - 0.25, 1.0, 1200);
+ music.add(b.tada - 0.25, &glock(84.0, 0.7), 1.0, 0.0);
+ for n in [65.0f32, 69.0, 72.0, 77.0] {
+ music.add(b.tada, &marimba(n, 0.6), 1.0, 0.0);
+ }
+ music.add(b.tada, &glock(89.0, 0.8), 1.0, 0.2);
+ music.add(b.tada, &glock(84.0, 0.6), 1.0, -0.2);
+ music.add(b.tada, &pad(&[53.0, 57.0, 60.0, 65.0], 3.0, 0.05), 0.8, 0.0);
+ music.add(b.tada, &soft_kick(), 1.0, 0.0);
+ music.add(b.tada, &pizz(29.0, 1.0, 77), 1.0, 0.0);
+
+ let wet = reverb(&music, 0.78, 0.4, 0.22);
+ let mut out = Track::new(length);
+ out.mix(&music, 1.0);
+ out.mix(&wet, 0.6);
+ out.normalize(-1.0);
+ out
+}
+
+// ------------------------------------------------------------------ The voice of the robot
+
+/// A chirp that follows `pitch` (Hz over 0..1). A little FM makes it sound like a synthetic
+/// voice.
+fn chirp(length: f32, pitch: impl Fn(f32) -> f32, wobble: f32) -> Track {
+ let mut phase = 0.0f32;
+ let mut m = 0.0f32;
+ let s = signal(length, |t| {
+ let x = t / length;
+ let f = pitch(x);
+ m = (m + f * 2.01 / RATE).fract();
+ phase = (phase + f * (1.0 + wobble * (t * 38.0).sin()) / RATE).fract();
+ (phase * TAU + 0.6 * (m * TAU).sin()).sin()
+ * smoothstep(0.0, 0.01, t)
+ * (1.0 - smoothstep(length - 0.03, length, t))
+ });
+ let mut track = reverb(&mono(&s, -3.0), 0.6, 0.5, 0.15);
+ track.normalize(-2.0);
+ track
+}
+
+/// Mixes the parts at their start times and normalizes the result.
+fn sequence(parts: &[(f32, Track)]) -> Track {
+ let length = parts
+ .iter()
+ .map(|(t, p)| t + p.len() as f32 / RATE)
+ .fold(0.0, f32::max);
+ let mut out = Track::new(length);
+ for (t, p) in parts {
+ let offset = (*t * RATE) as usize;
+ for i in 0..p.len() {
+ if offset + i < out.len() {
+ out.l[offset + i] += p.l[i];
+ out.r[offset + i] += p.r[i];
+ }
+ }
+ }
+ out.normalize(-2.0);
+ out
+}
+
+fn curious() -> Track {
+ chirp(
+ 0.55,
+ |x| {
+ if x < 0.3 {
+ 700.0 + 800.0 * x / 0.3
+ } else if x < 0.6 {
+ 1500.0 - 400.0 * (x - 0.3) / 0.3
+ } else {
+ 1100.0 + 700.0 * ((x - 0.6) / 0.4).powi(2)
+ }
+ },
+ 0.02,
+ )
+}
+
+fn happy() -> Track {
+ chirp(
+ 0.4,
+ |x| {
+ if x < 0.75 {
+ if ((x * 12.0) as u32).is_multiple_of(2) {
+ 1300.0
+ } else {
+ 1750.0
+ }
+ } else {
+ 1500.0 + 1200.0 * (x - 0.75) * 4.0
+ }
+ },
+ 0.0,
+ )
+}
+
+fn uh_oh() -> Track {
+ sequence(&[
+ (0.0, chirp(0.2, |x| 900.0 - 100.0 * x, 0.01)),
+ (0.26, chirp(0.4, |x| 640.0 - 180.0 * x, 0.03)),
+ ])
+}
+
+fn sigh() -> Track {
+ let mut out = chirp(1.0, |x| 560.0 - 380.0 * x.powf(0.7), 0.015);
+ let mut noise = Noise(3);
+ let mut band = Biquad::new(Kind::Band, 900.0, 1.0);
+ let breath = signal(1.0, |t| {
+ band.run(noise.next()) * attack_decay(t, 0.25, 2.5) * 0.4
+ });
+ out.add(0.0, &breath, 1.0, 0.0);
+ out.normalize(-2.0);
+ out
+}
+
+fn proud() -> Track {
+ sequence(&[
+ (0.0, chirp(0.08, |_| 800.0, 0.0)),
+ (0.09, chirp(0.08, |_| 1000.0, 0.0)),
+ (0.18, chirp(0.08, |_| 1200.0, 0.0)),
+ (0.27, chirp(0.3, |x| 1600.0 + 300.0 * x, 0.03)),
+ ])
+}
+
+fn tada() -> Track {
+ sequence(&[
+ (0.0, chirp(0.1, |_| 1200.0, 0.0)),
+ (
+ 0.14,
+ chirp(0.45, |x| 1800.0 + 100.0 * (x * 20.0).sin(), 0.0),
+ ),
+ ])
+}
+
+fn boot() -> Track {
+ let sweep = chirp(0.5, |x| 300.0 + 900.0 * x * x, 0.0);
+ sequence(&[
+ (0.0, sweep),
+ (0.55, chirp(0.06, |_| 1400.0, 0.0)),
+ (0.66, chirp(0.06, |_| 1400.0, 0.0)),
+ (0.77, chirp(0.1, |_| 1900.0, 0.0)),
+ ])
+}
+
+// ------------------------------------------------------------------ Foley
+
+/// A short click of band passed noise.
+fn click(seed: u32, freq: f32, decay_rate: f32, length: f32) -> Vec<f32> {
+ let mut noise = Noise(seed);
+ let mut band = Biquad::new(Kind::Band, freq, 3.0);
+ signal(length, |t| {
+ band.run(noise.next()) * decay(t, decay_rate) * 4.0
+ })
+}
+
+fn blink() -> Track {
+ let mut track = mono(&click(5, 5200.0, 300.0, 0.05), -6.0);
+ track.add(0.04, &click(6, 4200.0, 400.0, 0.04), 0.6, 0.0);
+ track
+}
+
+fn grip() -> Track {
+ let mut noise = Noise(51);
+ let mut high = Biquad::new(Kind::High, 4000.0, 0.7);
+ let mut snap = Biquad::new(Kind::Band, 2800.0, 8.0);
+ let s = signal(0.35, |t| {
+ let n = noise.next();
+ high.run(n) * attack_decay(t, 0.01, 18.0) * 0.5
+ + snap.run(if t > 0.07 {
+ n * decay(t - 0.07, 900.0)
+ } else {
+ 0.0
+ }) * 5.0
+ });
+ reverb(&mono(&s, -2.0), 0.6, 0.5, 0.12)
+}
+
+/// A lacquered letter that the robot puts down on concrete.
+fn place() -> Track {
+ let mut noise = Noise(77);
+ let mut body = Biquad::new(Kind::Band, 520.0, 4.0);
+ let mut sub = Sine::default();
+ let s = signal(0.6, |t| {
+ let n = noise.next();
+ body.run(n * decay(t, 160.0)) * 7.0 * decay(t, 22.0)
+ + sub.next(70.0 + 40.0 * decay(t, 40.0)) * decay(t, 14.0) * 0.8
+ });
+ let mut track = reverb(&mono(&s, -1.0), 0.75, 0.45, 0.15);
+ track.normalize(-1.0);
+ track
+}
+
+/// A hard hit with the ring of a thin plate.
+fn clatter() -> Track {
+ let modes = [(1250.0f32, 9.0f32), (2930.0, 14.0), (4710.0, 22.0)];
+ let mut noise = Noise(31);
+ let mut bands: Vec<Biquad> = modes
+ .iter()
+ .map(|(f, _)| Biquad::new(Kind::Band, *f, 25.0))
+ .collect();
+ let mut sub = Sine::default();
+ let s = signal(0.5, |t| {
+ let n = noise.next() * decay(t, 500.0);
+ let ring: f32 = bands
+ .iter_mut()
+ .zip(modes)
+ .map(|(b, (_, d))| b.run(n) * decay(t, d) * 9.0)
+ .sum();
+ ring + n * 0.6 + sub.next(90.0) * decay(t, 25.0) * 0.6
+ });
+ let mut track = reverb(&mono(&s, -1.0), 0.7, 0.4, 0.18);
+ track.normalize(-1.0);
+ track
+}
+
+fn pat() -> Track {
+ let mut track = mono(&click(8, 900.0, 60.0, 0.15), -3.0);
+ track.add(0.0, &click(9, 2400.0, 200.0, 0.05), 0.4, 0.0);
+ track
+}
+
+fn whoosh() -> Track {
+ let mut noise = Noise(12);
+ let mut band = Biquad::new(Kind::Band, 400.0, 1.2);
+ let s = signal(0.5, |t| {
+ band.set(Kind::Band, 300.0 + 1500.0 * (t / 0.5 * PI).sin(), 1.2);
+ band.run(noise.next()) * (t / 0.5 * PI).sin().powi(2)
+ });
+ mono(&s, -3.0)
+}
+
+fn scratch() -> Track {
+ let mut noise = Noise(44);
+ let mut band = Biquad::new(Kind::Band, 800.0, 4.0);
+ let mut saw = Saw::default();
+ let s = signal(0.42, |t| {
+ // The record moves back and forward two times. The second time is slower.
+ let x = t / 0.42;
+ let pitch = if x < 0.35 {
+ (x / 0.35 * PI).sin()
+ } else {
+ ((x - 0.35) / 0.65 * PI).sin() * 0.7
+ };
+ band.set(Kind::Band, 400.0 + 2600.0 * pitch, 5.0);
+ (band.run(noise.next()) * 2.0 + saw.next(80.0 + 300.0 * pitch) * 0.3) * pitch.abs().sqrt()
+ });
+ mono(&s, -1.0)
+}
+
+/// The lab lights: heavy contactors close, then the tubes start to hum.
+fn lights() -> Track {
+ let mut track = Track::new(2.0);
+ for (k, at) in [0.0f32, 0.06, 0.12, 0.2, 0.27].iter().enumerate() {
+ let thunk = {
+ let mut noise = Noise(100 + k as u32);
+ let mut low = Biquad::new(Kind::Low, 700.0, 0.7);
+ let mut sub = Sine::default();
+ signal(0.3, |t| {
+ low.run(noise.next()) * decay(t, 40.0) * 2.0 + sub.next(55.0) * decay(t, 20.0)
+ })
+ };
+ track.add(
+ *at,
+ &thunk,
+ if k % 2 == 0 { 1.0 } else { 0.5 },
+ if k % 2 == 0 { -0.3 } else { 0.3 },
+ );
+ }
+ let mut hum = [Sine::default(), Sine::default(), Sine::default()];
+ let buzz = signal(1.6, |t| {
+ let s: f32 = hum
+ .iter_mut()
+ .zip([120.0, 240.0, 360.0])
+ .map(|(o, f)| o.next(f))
+ .sum();
+ s * smoothstep(0.3, 0.8, t) * (1.0 - smoothstep(1.0, 1.6, t)) * 0.08
+ });
+ track.add(0.3, &buzz, 1.0, 0.0);
+ let mut track = reverb(&track, 0.85, 0.3, 0.3);
+ track.normalize(-1.0);
+ track
+}
+
+// ------------------------------------------------------------------ Beds
+
+/// The room tone: a low rumble, a little air and a mains hum.
+fn room(length: f32) -> Track {
+ let mut track = Track::new(length);
+ for (channel, seed) in [(0usize, 1u32), (1, 2)] {
+ let mut noise = Noise(seed);
+ let mut low = Biquad::new(Kind::Low, 140.0, 0.7);
+ let mut high = Biquad::new(Kind::High, 5000.0, 0.7);
+ let mut hum = Sine::default();
+ let s = signal(length, |t| {
+ let n = noise.next();
+ low.run(n) * 1.5
+ + high.run(n) * 0.04
+ + hum.next(120.0) * 0.02 * (0.8 + 0.2 * (t * 0.3).sin())
+ });
+ if channel == 0 {
+ track.l = s;
+ } else {
+ track.r = s;
+ }
+ }
+ track.normalize(-6.0);
+ track
+}
+
+/// The motor of each joint: low motors for J1 to J3 and small, high motors for the wrist.
+/// Their level and pitch follow the joint speeds of the animation.
+fn servos(show: &Show, length: f32) -> Track {
+ let rate = 240.0;
+ let samples = (length * rate) as usize + 2;
+ let speeds: Vec<[f32; 6]> = (0..samples)
+ .map(|i| {
+ let t = i as f32 / rate;
+ let a = show.story.track.sample(t).q;
+ let b = show.story.track.sample(t + 1.0 / rate).q;
+ std::array::from_fn(|j| (b.q[j] - a.q[j]).abs() * rate)
+ })
+ .collect();
+ let base = [70.0f32, 95.0, 120.0, 330.0, 380.0, 450.0];
+ let gain = [1.0f32, 1.0, 0.9, 0.5, 0.55, 0.45];
+ let mut track = Track::new(length);
+ for j in 0..6 {
+ let mut a = Sine::default();
+ let mut b = Sine::default();
+ let mut noise = Noise(60 + j as u32);
+ let mut band = Biquad::new(Kind::Band, base[j] * 6.0, 4.0);
+ let mut level = 0.0f32;
+ let s = signal(length, |t| {
+ let x = t * rate;
+ let i = (x as usize).min(samples - 2);
+ let speed = speeds[i][j] + (speeds[i + 1][j] - speeds[i][j]) * (x - i as f32);
+ let target = (speed / 2.5).min(1.0);
+ level += (target - level) * 0.003;
+ let f = base[j] * (1.0 + 0.7 * (speed / 3.0).min(1.5));
+ let gears = band.run(noise.next()) * 0.5;
+ (a.next(f) * 0.6 + b.next(f * 2.02) * 0.3 + gears) * level * gain[j]
+ });
+ track.add(0.0, &s, 1.0, (j as f32 - 2.5) * 0.08);
+ }
+ track.normalize(-3.0);
+ track
+}
+
+fn main() -> std::io::Result<()> {
+ let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("dynamic_media");
+ std::fs::create_dir_all(&dir)?;
+ for old in std::fs::read_dir(&dir)?.flatten() {
+ if old.path().extension().is_some_and(|e| e == "wav") {
+ std::fs::remove_file(old.path())?;
+ }
+ }
+ let show = Show::new();
+ let length = show.duration() + 1.5;
+ for (name, track) in [
+ ("music.wav", score(&show, length)),
+ ("room.wav", room(length)),
+ ("servos.wav", servos(&show, length)),
+ ("lights.wav", lights()),
+ ("boot.wav", boot()),
+ ("blink.wav", blink()),
+ ("curious.wav", curious()),
+ ("happy.wav", happy()),
+ ("grip.wav", grip()),
+ ("place.wav", place()),
+ ("whoosh.wav", whoosh()),
+ ("scratch.wav", scratch()),
+ ("clatter.wav", clatter()),
+ ("uhoh.wav", uh_oh()),
+ ("sigh.wav", sigh()),
+ ("pat.wav", pat()),
+ ("proud.wav", proud()),
+ ("tada.wav", tada()),
+ ] {
+ track.write(&dir.join(name))?;
+ println!(
+ "wrote dynamic_media/{name} ({:.2} s)",
+ track.len() as f32 / RATE
+ );
+ }
+ Ok(())
+}
diff --git a/examples/arm/src/effects.rs b/examples/arm/src/effects.rs
new file mode 100644
index 00000000..68d1c6fc
--- /dev/null
+++ b/examples/arm/src/effects.rs
@@ -0,0 +1,174 @@
+//! Effects that the film builds itself from the building blocks of `fframes_three_d`: random
+//! numbers, camera shake, a light beam in hazy air, sparks and a printed grid.
+
+use fframes::three_d::math::smoothstep;
+use fframes::three_d::*;
+
+/// Maps an integer to a pseudo-random value in `0..1`. The same input always gives the same
+/// value.
+pub fn hash(n: u32) -> f32 {
+ let mut x = n.wrapping_mul(0x9E37_79B9) ^ 0x85EB_CA6B;
+ x ^= x >> 16;
+ x = x.wrapping_mul(0x7FEB_352D);
+ x ^= x >> 15;
+ x = x.wrapping_mul(0x846C_A68B);
+ x ^= x >> 16;
+ (x >> 8) as f32 / (1u32 << 24) as f32
+}
+
+/// Linear progress of `t` from `start` to `end`, clamped to `0..1`.
+pub fn progress(t: f32, start: f32, end: f32) -> f32 {
+ ((t - start) / (end - start)).clamp(0.0, 1.0)
+}
+
+/// Smooth 1D gradient noise in `-1..1`. Each integer `x` has a random slope and the value 0,
+/// and a quintic curve blends the slopes of the two neighbours, so a camera that it moves
+/// does not stop and start again.
+pub fn noise(seed: u32, x: f32) -> f32 {
+ let i = x.floor();
+ let f = x - i;
+ let cell = (i as i32 as u32).wrapping_add(seed.wrapping_mul(1013));
+ let g0 = hash(cell) * 2.0 - 1.0;
+ let g1 = hash(cell.wrapping_add(1)) * 2.0 - 1.0;
+ let u = f * f * f * (f * (f * 6.0 - 15.0) + 10.0);
+ let (a, b) = (g0 * f, g1 * (f - 1.0));
+ // the largest value is 0.5
+ 2.0 * (a + (b - a) * u)
+}
+
+/// A pseudo-random unit vector. The same `seed` always gives the same vector.
+pub fn direction(seed: u32) -> Vec3 {
+ let u = hash(seed.wrapping_mul(2).wrapping_add(1)) * 2.0 - 1.0;
+ let phi = hash(seed.wrapping_mul(2).wrapping_add(2)) * std::f32::consts::TAU;
+ let r = (1.0 - u * u).max(0.0).sqrt();
+ Vec3::new(r * phi.cos(), u, r * phi.sin())
+}
+
+/// Shakes `camera` after the hits at `(time, strength)`: it turns by up to `strength`
+/// degrees and the shake dies out in about 0.4 seconds. The camera keeps its lens, only the
+/// direction of the view changes.
+pub fn shake(camera: Camera, t: f32, hits: impl IntoIterator<Item = (f32, f32)>) -> Camera {
+ let amount: f32 = hits
+ .into_iter()
+ .filter(|&(at, _)| t >= at)
+ .map(|(at, strength)| strength * (-(t - at) * 10.0).exp())
+ .sum();
+ if amount < 1e-3 {
+ return camera;
+ }
+ // Two noise curves for the yaw and the pitch, at 18 turns per second.
+ let yaw = deg(amount * noise(1, t * 18.0));
+ let pitch = deg(amount * noise(2, t * 18.0));
+ let forward = camera.forward();
+ let right = forward.cross(Vec3::Y).normalize_or(Vec3::X);
+ let up = right.cross(forward);
+ let turned = Quat::from_axis_angle(up, yaw) * Quat::from_axis_angle(right, pitch) * forward;
+ let target = camera.position + turned;
+ camera.look_at(target)
+}
+
+/// A beam of light in hazy air, along +Z from the lamp at the origin to a circle of
+/// `radius` at `length`. Draw it with [`Material::glow`]: 16 cones inside each other add
+/// up to a beam that is bright in the middle and soft at the sides, and their vertex colors
+/// fade it out along its length.
+pub fn beam(length: f32, radius: f32) -> Geometry {
+ const CONES: usize = 16;
+ let rings = 16;
+ let cones = (0..CONES).map(|k| {
+ let scale = 1.0 - k as f32 / CONES as f32;
+ // A lathe along -Y, turned so that -Y becomes +Z. The profile goes from the wide end
+ // up to the lamp, so the faces point out, as in three.js.
+ let profile: Vec<Vec2> = (0..=rings)
+ .rev()
+ .map(|i| {
+ let along = i as f32 / rings as f32;
+ vec2((0.004 + radius * along) * scale, -length * along)
+ })
+ .collect();
+ Geometry::lathe(&profile, 32).rotate_x(deg(-90.0))
+ });
+ let mut geometry = Geometry::merge(cones);
+ geometry.colors = geometry
+ .positions
+ .iter()
+ .map(|p| {
+ let along = (p.z / length).clamp(0.0, 1.0);
+ // Bright near the lamp, gone at the end of the beam.
+ let fade = (1.0 - along).powf(1.6) * smoothstep(0.0, 0.06, along) / CONES as f32;
+ vec4(fade, fade, fade, 1.0)
+ })
+ .collect();
+ geometry
+}
+
+/// Sparks thrown from `at` at the time `start`, `count` of them with up to `speed` meters
+/// per second. They fly on a ballistic path, bounce off the floor once and cool down from
+/// white to orange. Nothing is left after a second.
+///
+/// Each spark is a streak: dots along the path it flew in the last `trail` seconds, fading
+/// out towards its tail.
+pub fn sparks(
+ at: Vec3,
+ start: f32,
+ speed: f32,
+ count: u32,
+ seed: u32,
+ t: f32,
+ trail: f32,
+) -> Vec<Particle> {
+ const DOTS: usize = 8;
+ if !(0.0..1.0 + trail).contains(&(t - start)) {
+ return Vec::new();
+ }
+ (0..count)
+ .flat_map(|i| (0..DOTS).map(move |k| (i, k)))
+ .filter_map(|(i, k)| {
+ let tail = k as f32 / DOTS as f32;
+ let age = t - start - tail * trail;
+ if age < 0.0 {
+ return None;
+ }
+ let id = seed.wrapping_mul(7919).wrapping_add(i);
+ let mut v = direction(id) * speed * (0.35 + 0.65 * hash(id ^ 0x5bd1));
+ // Mostly up and out of the floor.
+ v.y = v.y.abs() * 0.8 + 0.3;
+ let life = 0.35 + 0.6 * hash(id ^ 0x2c1b);
+ let x = age / life;
+ if x >= 1.0 {
+ return None;
+ }
+ let mut p = at + v * age + Vec3::Y * (-4.9 * age * age);
+ if p.y < 0.005 {
+ p.y = 0.005 + (0.005 - p.y) * 0.25;
+ }
+ let heat = 1.0 - x;
+ let color = Rgb::hex(0xff5a10).lerp(Rgb::hex(0xfff2c0), heat * heat)
+ * (2.0 + 10.0 * heat)
+ * (1.0 - tail);
+ Some(Particle::new(p, 0.003 + 0.004 * heat, color).opacity(heat * (1.0 - tail)))
+ })
+ .collect()
+}
+
+/// A printed grid on a mat: thin lines every `cell` meters and thicker ones every
+/// `major` cells, on a texture that repeats every `major * cell` meters. The texture is
+/// mipmapped, so the lines do not shimmer far away.
+pub fn grid_texture(cell: f32, major: u32, ink: Rgb, paper: Rgb) -> Texture {
+ let size = 512;
+ let cells = major as f32;
+ // How much of a line of `width` texels covers the texel at `c`, in lines per texture
+ // when `texels` is the texture size, in cells when it is the size of a cell.
+ let line = |c: f32, texels: f32, width: f32| {
+ let f = c.fract();
+ let d = f.min(1.0 - f) * texels;
+ 1.0 - smoothstep(width * 0.5 - 0.75, width * 0.5 + 0.75, d)
+ };
+ Texture::from_fn(size, size, |u, v| {
+ let cell_texels = size as f32 / cells;
+ let minor = line(u * cells, cell_texels, 3.0).max(line(v * cells, cell_texels, 3.0));
+ let major = line(u, size as f32, 10.0).max(line(v, size as f32, 10.0));
+ let ink_amount = (minor * 0.55).max(major);
+ paper.lerp(ink, ink_amount)
+ })
+ .repeat(1.0 / (cell * cells), 1.0 / (cell * cells))
+}
diff --git a/examples/arm/src/lab.rs b/examples/arm/src/lab.rs
new file mode 100644
index 00000000..1bad9bc8
--- /dev/null
+++ b/examples/arm/src/lab.rs
@@ -0,0 +1,398 @@
+//! The lab: a polished concrete floor, the robot cell with hazard stripes and stencils, the
+//! letter rack, the shelves, the walls and the lights.
+
+use std::f32::consts::TAU;
+use std::sync::Arc;
+
+use fframes::three_d::math::smoothstep;
+use fframes::three_d::*;
+
+use crate::effects::{self, hash};
+
+/// Value noise in `0..1` that repeats every `period` cells.
+fn noise(x: f32, y: f32, period: u32, seed: u32) -> f32 {
+ let (xi, yi) = (x.floor(), y.floor());
+ let (fx, fy) = (x - xi, y - yi);
+ let p = period as i32;
+ let at = |i: i32, j: i32| {
+ hash(
+ (i.rem_euclid(p) as u32).wrapping_mul(7919)
+ ^ (j.rem_euclid(p) as u32).wrapping_mul(104_729)
+ ^ seed.wrapping_mul(31),
+ )
+ };
+ let (i, j) = (xi as i32, yi as i32);
+ let (u, v) = (smoothstep(0.0, 1.0, fx), smoothstep(0.0, 1.0, fy));
+ let a = at(i, j) + (at(i + 1, j) - at(i, j)) * u;
+ let b = at(i, j + 1) + (at(i + 1, j + 1) - at(i, j + 1)) * u;
+ a + (b - a) * v
+}
+
+/// Five octaves of [`noise`].
+fn fbm(u: f32, v: f32, seed: u32) -> f32 {
+ let mut sum = 0.0;
+ let mut amp = 0.5;
+ let mut period = 8u32;
+ for o in 0..5 {
+ sum += amp * noise(u * period as f32, v * period as f32, period, seed + o);
+ amp *= 0.5;
+ period *= 2;
+ }
+ sum
+}
+
+/// Size of one floor texture tile in meters. One tile holds two by two concrete slabs.
+const TILE: f32 = 2.4;
+
+/// The maps of the polished concrete: the color (slab colors, mottling, specks, seams and
+/// scuffs), the occlusion and roughness in one texture as in glTF (occlusion in red, the
+/// seams), and the normals (the bumps of the mottling, the edges of the seams).
+fn floor_textures() -> (Texture, Texture, Texture) {
+ let size = 1024;
+ let seam = |u: f32, v: f32| {
+ let d = |c: f32| {
+ let f = (c * 2.0).fract();
+ f.min(1.0 - f) / 2.0 * TILE
+ };
+ let w = d(u).min(d(v));
+ 1.0 - ((w - 0.002) / 0.003).clamp(0.0, 1.0)
+ };
+ // The height of the surface in meters: a 4 mm deep seam and bumps of half a millimeter.
+ let height = |u: f32, v: f32| -0.004 * seam(u, v) + 0.0005 * fbm(u, v, 3);
+ let color = Texture::from_fn(size, size, |u, v| {
+ let slab = hash((u * 2.0) as u32 * 3 + (v * 2.0) as u32 * 7 + 11) * 0.05;
+ let mottle = fbm(u, v, 3);
+ let fine = noise(u * 256.0, v * 256.0, 256, 9);
+ let speck = if hash((u * 900.0) as u32 * 977 + (v * 900.0) as u32) > 0.985 {
+ 0.06
+ } else {
+ 0.0
+ };
+ let scuff = (fbm(u * 0.5 + 0.3, v * 2.0, 21) - 0.6).max(0.0) * 0.3;
+ let mut l = 0.52 + slab + (mottle - 0.5) * 0.1 + (fine - 0.5) * 0.04 - speck - scuff;
+ l *= 1.0 - 0.35 * seam(u, v);
+ let g = (l * 255.0).clamp(0.0, 255.0) as u8;
+ Rgb::srgb8(
+ g,
+ (f32::from(g) * 1.005).min(255.0) as u8,
+ (f32::from(g) * 1.02).min(255.0) as u8,
+ )
+ })
+ .repeat(1.0 / TILE, 1.0 / TILE);
+ let ao_rough = Texture::from_fn_data(size / 2, size / 2, false, |u, v| {
+ let wear = fbm(u + 0.17, v + 0.41, 13);
+ let r = (0.32 + (wear - 0.5) * 0.35 + seam(u, v) * 0.4).clamp(0.12, 1.0);
+ let ao = 1.0 - 0.6 * seam(u, v);
+ [(ao * 255.0) as u8, (r * 255.0) as u8, 0, 255]
+ })
+ .repeat(1.0 / TILE, 1.0 / TILE);
+ let normals = Texture::from_fn_data(size, size, false, |u, v| {
+ // The slope from the height differences over one texel. U runs along +X and V
+ // along +Z, which is down in the image, so the green channel (up in the image)
+ // gets the slope towards -Z.
+ let e = 1.0 / size as f32;
+ let meters = e * TILE;
+ let dx = (height(u + e, v) - height(u - e, v)) / (2.0 * meters);
+ let dz = (height(u, v + e) - height(u, v - e)) / (2.0 * meters);
+ let n = vec3(-dx, dz, 1.0).normalize();
+ let byte = |c: f32| ((c * 0.5 + 0.5) * 255.0).round() as u8;
+ [byte(n.x), byte(n.y), byte(n.z), 255]
+ })
+ .repeat(1.0 / TILE, 1.0 / TILE);
+ (color, ao_rough, normals)
+}
+
+/// Diagonal yellow and black stripes in world space.
+fn hazard_texture() -> Texture {
+ Texture::from_fn(64, 64, |u, v| {
+ if (u + v).fract() < 0.5 {
+ Rgb::srgb8(236, 180, 0)
+ } else {
+ Rgb::srgb8(22, 22, 24)
+ }
+ })
+ .repeat(1.0 / 0.3, 1.0 / 0.3)
+}
+
+/// A strip of floor paint from `a` to `b`, with world space UVs.
+fn strip(a: Vec2, b: Vec2, width: f32) -> Geometry {
+ let len = a.distance(b);
+ let dir = (b - a) / len;
+ let angle = dir.y.atan2(dir.x);
+ let mid = (a + b) * 0.5;
+ let mut g = Geometry::floor(len, width)
+ .rotate_y(-angle)
+ .translate(mid.x, 0.003, mid.y);
+ g.uvs = g.positions.iter().map(|p| Vec2::new(p.x, p.z)).collect();
+ g
+}
+
+/// A lab monitor: a grid, a level meter and a trace.
+fn screen_texture() -> Texture {
+ Texture::from_fn(256, 160, |u, v| {
+ let line = |d: f32, width: f32| 1.0 - smoothstep(0.0, width, d.abs());
+ let grid = line((u * 8.0).fract() - 0.5, 0.06).max(line((v * 5.0).fract() - 0.5, 0.06));
+ let wave = 0.5 + 0.18 * (u * 19.0).sin() * (u * 3.0 + 1.0).cos();
+ let trace = line(v - wave, 0.012);
+ let bar = if u > 0.86 && v > 0.4 { 0.8 } else { 0.0 };
+ let l = (0.1 * grid + trace).max(bar).min(1.0);
+ Rgb::srgb8((40.0 * l) as u8, (190.0 * l) as u8, (255.0 * l) as u8)
+ })
+}
+
+/// The lab nodes that [`set_lights`] changes.
+pub struct Lab {
+ pub key: NodeId,
+ pub fill: NodeId,
+ pub ambient: NodeId,
+ pub light_strips: NodeId,
+}
+
+/// The studio environment of the lab at the light `level`.
+fn environment(level: f32) -> Environment {
+ Environment::Studio(Studio {
+ sky: Rgb::hex(0xeef0f2),
+ horizon: Rgb::hex(0xc9ccd0),
+ ground: Rgb::hex(0x6a6c70),
+ softboxes: vec![
+ // Rows of light panels in the ceiling.
+ SoftBox::new(vec3(-0.35, 1.0, 0.0), 12.0, 70.0, Rgb::WHITE * 3.2),
+ SoftBox::new(vec3(0.35, 1.0, 0.0), 12.0, 70.0, Rgb::WHITE * 3.2),
+ SoftBox::new(vec3(0.0, 0.5, 0.85), 70.0, 10.0, Rgb::hex(0xfff1e0) * 1.6),
+ SoftBox::new(vec3(-1.0, 0.18, -0.3), 8.0, 40.0, Rgb::hex(0xdde8ff) * 1.4),
+ ],
+ intensity: 0.6 * level,
+ rotation: 0.0,
+ })
+}
+
+/// Adds the lab to `scene`.
+pub fn build(scene: &mut Scene, font: &[u8]) -> Lab {
+ let (color, ao_rough, normals) = floor_textures();
+ // The scene reflects in the polished concrete. The roughness map blurs the reflection.
+ scene.reflector = Some(Reflector::floor());
+ let ao_rough = Arc::new(ao_rough);
+ let mut floor_material = Material::standard(0xffffff)
+ .roughness(1.0)
+ .env_intensity(0.9)
+ .reflection(0.85)
+ .map(color)
+ .normal_map(normals)
+ .ao_map(ao_rough.clone());
+ floor_material.metal_rough_map = Some(ao_rough);
+ scene.add(Node::mesh(Geometry::floor(60.0, 60.0), floor_material).shadows(false, true));
+
+ // The robot cell: a hazard stripe border, a dashed circle for the reach, and stencils.
+ let hazard = Material::standard(0xffffff)
+ .roughness(0.55)
+ .map(hazard_texture());
+ let (x0, x1, z0, z1) = (-2.9f32, 2.9f32, -2.15f32, 2.35f32);
+ let border = Geometry::merge([
+ strip(vec2(x0, z0), vec2(x1, z0), 0.14),
+ strip(vec2(x0, z1), vec2(x1, z1), 0.14),
+ strip(vec2(x0, z0 - 0.07), vec2(x0, z1 + 0.07), 0.14),
+ strip(vec2(x1, z0 - 0.07), vec2(x1, z1 + 0.07), 0.14),
+ ]);
+ scene.add(Node::mesh(border, hazard).shadows(false, true));
+ let paint = Material::standard(0xf3f3f0).roughness(0.6);
+ let dashes = Geometry::merge((0..48).filter(|i| i % 2 == 0).map(|i| {
+ let a0 = i as f32 / 48.0 * TAU;
+ let a1 = (i as f32 + 1.0) / 48.0 * TAU;
+ strip(
+ vec2(a0.sin(), a0.cos()) * 2.05,
+ vec2(a1.sin(), a1.cos()) * 2.05,
+ 0.035,
+ )
+ }));
+ scene.add(Node::mesh(dashes, paint.clone()).shadows(false, true));
+ let ring = Geometry::ring(0.62, 0.66, 96)
+ .rotate_x(deg(-90.0))
+ .translate(0.0, 0.003, 0.0);
+ scene.add(Node::mesh(ring, paint.clone()).shadows(false, true));
+ let stencil = |text: &str, size: f32, at: Vec3, yaw: f32| -> Option<Geometry> {
+ let g = Geometry::text(font, text, size, 0.002, 0.0).ok()?;
+ let c = g.bounds().center();
+ Some(
+ g.translate(-c.x, -c.y, 0.0)
+ .rotate_x(deg(-90.0))
+ .rotate_y(yaw)
+ .translate(at.x, 0.003, at.z),
+ )
+ };
+ let mut stencils = Vec::new();
+ stencils.extend(stencil("R-07", 0.22, vec3(1.15, 0.0, -0.75), deg(-30.0)));
+ stencils.extend(stencil("OUTPUT", 0.13, vec3(1.95, 0.0, 1.95), 0.0));
+ stencils.extend(stencil("PARTS", 0.13, vec3(2.1, 0.0, -1.85), 0.0));
+ stencils.extend(stencil("KEEP CLEAR", 0.11, vec3(0.0, 0.0, 2.6), 0.0));
+ scene.add(Node::mesh(Geometry::merge(stencils), paint.clone()).shadows(false, true));
+ // The output tray: a painted outline.
+ let tray = Geometry::merge([
+ strip(vec2(-1.75, 0.95), vec2(1.75, 0.95), 0.025),
+ strip(vec2(-1.75, 1.55), vec2(1.75, 1.55), 0.025),
+ strip(vec2(-1.75, 0.94), vec2(-1.75, 1.56), 0.025),
+ strip(vec2(1.75, 0.94), vec2(1.75, 1.56), 0.025),
+ ]);
+ scene.add(Node::mesh(tray, paint).shadows(false, true));
+ // A calibration grid printed in the tray: 5 cm cells, a thick line every 25 cm.
+ let mut mat = Geometry::floor(3.45, 0.55).translate(0.0, 0.0025, 1.25);
+ mat.uvs = mat.positions.iter().map(|p| vec2(p.x, p.z)).collect();
+ let grid = effects::grid_texture(0.05, 5, Rgb::hex(0x50545a), Rgb::hex(0xa8aaa7));
+ scene.add(
+ Node::mesh(mat, Material::standard(0xffffff).roughness(0.7).map(grid)).shadows(false, true),
+ );
+
+ // Walls far away, with panel seams and light strips.
+ let wall_material = Material::standard(0xc9ccd0).roughness(0.8);
+ scene.add(
+ Node::mesh(
+ Geometry::cuboid(30.0, 7.0, 0.3).translate(0.0, 3.5, -9.0),
+ wall_material.clone(),
+ )
+ .shadows(false, true),
+ );
+ scene.add(
+ Node::mesh(
+ Geometry::cuboid(0.3, 7.0, 30.0).translate(-9.0, 3.5, 0.0),
+ wall_material.clone(),
+ )
+ .shadows(false, true),
+ );
+ let seams = Geometry::merge(
+ (-6..=6).map(|i| Geometry::cuboid(0.03, 7.0, 0.04).translate(i as f32 * 2.4, 3.5, -8.84)),
+ );
+ scene.add(Node::mesh(seams, Material::standard(0xb9bcc0).roughness(0.7)).shadows(false, false));
+ let light_strips = Geometry::merge([
+ Geometry::rounded_box(16.0, 0.12, 0.05, 0.02, 1).translate(0.0, 2.6, -8.82),
+ Geometry::rounded_box(0.05, 0.12, 16.0, 0.02, 1).translate(-8.82, 2.6, 0.0),
+ ]);
+ let light_strips = scene.add(
+ Node::mesh(
+ light_strips,
+ Material::standard(0xffffff).emissive(0xfff4e6, 0.0),
+ )
+ .shadows(false, false),
+ );
+ // Benches along the back wall, with monitors.
+ let screen = Arc::new(screen_texture());
+ let bench = Material::standard(0xd7d9dc).roughness(0.5);
+ for x in [-4.5f32, 3.2] {
+ scene.add(Node::mesh(
+ Geometry::rounded_box(2.6, 0.06, 0.8, 0.02, 2).translate(x, 0.92, -7.9),
+ bench.clone(),
+ ));
+ scene.add(Node::mesh(
+ Geometry::rounded_box(2.5, 0.85, 0.7, 0.03, 2).translate(x, 0.44, -7.95),
+ Material::standard(0xb4b8bd).roughness(0.6),
+ ));
+ scene.add(Node::mesh(
+ Geometry::rounded_box(0.5, 0.35, 0.05, 0.02, 2).translate(x - 0.6, 1.2, -8.1),
+ Material::standard(0x1b1c1f)
+ .roughness(0.15)
+ .emissive(0xffffff, 1.2)
+ .emissive_map(screen.clone()),
+ ));
+ }
+
+ // Shelves with parts bins against the back wall. The bins are one instanced mesh with a
+ // color for each copy, three.js `InstancedMesh`.
+ let shelves = Geometry::merge(
+ [0.3f32, 0.82, 1.34, 1.86]
+ .map(|y| Geometry::cuboid(4.5, 0.03, 0.5).translate(-0.6, y, -8.58))
+ .into_iter()
+ .chain(
+ [-2.85f32, -0.6, 1.65]
+ .map(|x| Geometry::cuboid(0.04, 2.0, 0.5).translate(x, 1.0, -8.58)),
+ ),
+ );
+ scene.add(Node::mesh(shelves, Material::metal(0x8d9196, 0.45)).shadows(false, true));
+ let bin_colors = [0x2f6fd0, 0x2f6fd0, 0x2f6fd0, 0xf2bd00, 0xd8422b, 0x9ea3a8];
+ let (transforms, colors): (Vec<Mat4>, Vec<Rgb>) = (0..4)
+ .flat_map(|row| (0..10).map(move |i| (row, i)))
+ .filter(|&(row, i)| hash(row * 31 + i * 7 + 3) > 0.12)
+ .map(|(row, i)| {
+ let x = -2.6 + i as f32 * 0.445 + if i >= 5 { 0.04 } else { 0.0 };
+ let y = [0.3f32, 0.82, 1.34, 1.86][row as usize] + 0.015 + 0.13;
+ let pick = (hash(row * 13 + i * 5 + 1) * bin_colors.len() as f32) as usize;
+ (
+ Mat4::from_translation(vec3(x, y, -8.55)),
+ Rgb::hex(bin_colors[pick]),
+ )
+ })
+ .unzip();
+ scene.add(
+ Node::instanced(
+ Geometry::rounded_box(0.4, 0.26, 0.42, 0.02, 2),
+ Material::standard(0xffffff).roughness(0.55),
+ Instances::new(transforms).colors(colors),
+ )
+ .shadows(false, true),
+ );
+
+ // The letter rack: an aluminium frame on a base plate.
+ let alu = Material::metal(0xc9ccd1, 0.32);
+ scene.add(Node::mesh(
+ Geometry::rounded_box(4.3, 0.02, 0.36, 0.008, 2).translate(0.0, 0.01, crate::RACK_Z),
+ Material::metal(0x34363b, 0.45),
+ ));
+ for z in [crate::RACK_Z - 0.14, crate::RACK_Z + 0.14] {
+ scene.add(Node::mesh(
+ Geometry::rounded_box(4.2, 0.04, 0.04, 0.006, 2).translate(0.0, 0.12, z),
+ alu.clone(),
+ ));
+ scene.add(Node::mesh(
+ Geometry::rounded_box(4.2, 0.006, 0.012, 0.002, 1).translate(0.0, 0.142, z),
+ Material::metal(0x5b5e64, 0.5),
+ ));
+ }
+ let posts = Geometry::merge((0..8).flat_map(|i| {
+ let x = -1.82 + i as f32 * 0.52;
+ [crate::RACK_Z - 0.14, crate::RACK_Z + 0.14]
+ .map(|z| Geometry::rounded_box(0.04, 0.12, 0.04, 0.006, 1).translate(x, 0.06, z))
+ }));
+ scene.add(Node::mesh(posts, alu));
+
+ let key = scene.add(Node::light(
+ Light::sun(Rgb::hex(0xfff6ea), 0.0, vec3(1.8, 7.0, 4.0)).with_shadow(Shadow {
+ map_size: 3072,
+ softness: 3.5,
+ strength: 0.95,
+ bounds: Some(Aabb {
+ min: vec3(-3.2, 0.0, -2.2),
+ max: vec3(3.2, 3.2, 2.6),
+ }),
+ ..Default::default()
+ }),
+ ));
+ let fill = scene.add(Node::light(Light::directional(
+ Rgb::hex(0xcfe0ff),
+ 0.0,
+ vec3(-4.0, 3.0, -2.0),
+ )));
+ let ambient = scene.add(Node::light(Light::hemisphere(0xf2f4f6, 0x8a8680, 0.0)));
+ Lab {
+ key,
+ fill,
+ ambient,
+ light_strips,
+ }
+}
+
+/// Sets the light level of the lab: 0 is dark blue, 1 is fully lit.
+pub fn set_lights(scene: &mut Scene, lab: &Lab, level: f32) {
+ scene.environment = environment(level.max(0.04));
+ *scene[lab.key].light_mut().expect("key").intensity_mut() = 2.4 * level;
+ *scene[lab.fill].light_mut().expect("fill").intensity_mut() = 0.6 * level;
+ *scene[lab.ambient]
+ .light_mut()
+ .expect("ambient")
+ .intensity_mut() = level + 0.25;
+ let air = Rgb::hex(0x0c1220).lerp(Rgb::hex(0xbfc3c7), level);
+ scene.background = Background::Color(air);
+ scene.fog = Some(Fog::Exp2 {
+ color: air,
+ density: 0.045,
+ });
+ if let Some(m) = scene[lab.light_strips].material_mut() {
+ m.emissive_intensity = 2.2 * level;
+ }
+}
diff --git a/examples/arm/src/lib.rs b/examples/arm/src/lib.rs
new file mode 100644
index 00000000..57ca4730
--- /dev/null
+++ b/examples/arm/src/lib.rs
@@ -0,0 +1,544 @@
+//! FFRAMES, ASSEMBLED: a short film about a lab robot with a camera eye. It spells
+//! `fframes` with letter pieces, throws the "a" across the floor by mistake, and fixes it.
+
+// Colors are hex numbers, as in three.js: `0xff4a00`.
+#![allow(clippy::unreadable_literal)]
+
+pub mod arm;
+pub mod effects;
+pub mod lab;
+pub mod story;
+
+use fframes::three_d::math::smoothstep;
+use fframes::three_d::*;
+use fframes::{
+ AudioMap, AudioTimestamp, AudioTrack, Color, Duration, FFramesContext, Frame, Svgr, Video,
+ include_media_dir, svgr,
+};
+
+use crate::arm::{Arm, Expression, Joints, Palette};
+use crate::effects::{hash, noise, progress};
+use crate::story::{Phase, Sound, Story};
+
+include_media_dir!(pub struct ArmMedia, "examples/arm/media");
+
+pub const WIDTH: usize = 1920;
+pub const HEIGHT: usize = 1080;
+pub const FPS: usize = 60;
+
+/// The font of the letter pieces and of the lettering on the arm.
+pub const FONT: &[u8] = include_bytes!("../media/Inter_18pt-ExtraBold.ttf");
+/// The word that the robot spells.
+pub const WORD: &str = "fframes";
+/// Z of the row where the robot spells the word.
+pub const WORD_Z: f32 = 1.25;
+/// Z of the rack where the letter pieces wait.
+pub const RACK_Z: f32 = -1.3;
+
+const MONO: &str = "IBM Plex Mono";
+const INK: &str = "#1c1d20";
+const ORANGE: &str = "#ff4a00";
+
+/// The part of a frame that the shutter is open in the shots with motion blur (180°).
+const SHUTTER: f32 = 0.5;
+
+/// The film: the 3D scene, the story and the renderer.
+pub struct Show {
+ scene: Scene,
+ arm: Arm,
+ lab: lab::Lab,
+ letter_nodes: Vec<NodeId>,
+ /// Dust in the air, lit by the eye in the dark lab.
+ dust: NodeId,
+ /// The sparks of the dropped letter.
+ sparks: NodeId,
+ pub story: Story,
+ renderer: Renderer,
+ read_back: bool,
+}
+
+impl std::fmt::Debug for Show {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Show").finish_non_exhaustive()
+ }
+}
+
+impl Show {
+ pub fn new() -> Self {
+ let mut scene = Scene::new();
+ let lab = lab::build(&mut scene, FONT);
+ let arm = Arm::build(&mut scene, &Palette::new(), FONT);
+ let story = Story::new(FONT, WORD);
+ let lacquer = Material::standard(0x111113).roughness(0.2).clearcoat(1.0);
+ let letter_nodes = story
+ .letters
+ .iter()
+ .map(|l| scene.add(Node::mesh(l.geometry.clone(), lacquer.clone())))
+ .collect();
+ let dust = scene.add(Node::particles(Vec::new(), Blending::Additive));
+ let sparks = scene.add(Node::particles(Vec::new(), Blending::Additive));
+ Self {
+ scene,
+ arm,
+ lab,
+ letter_nodes,
+ dust,
+ sparks,
+ story,
+ renderer: Renderer::new(WIDTH as u32, HEIGHT as u32)
+ .gpu()
+ .tone_mapping(ToneMapping::Neutral)
+ .exposure(0.92)
+ .bloom(Bloom {
+ strength: 0.4,
+ radius: 0.45,
+ threshold: 1.2,
+ }),
+ read_back: false,
+ }
+ }
+
+ /// Length of the film in seconds.
+ pub fn duration(&self) -> f32 {
+ self.story.beats.end + 0.6
+ }
+
+ /// Renders the 3D with the CPU rasterizer instead of the GPU.
+ pub fn on_cpu(mut self) -> Self {
+ self.renderer = self.renderer.cpu();
+ self
+ }
+
+ /// Reads the 3D back from the GPU and gives Skia pixels instead of the GPU texture.
+ /// Use it to compare and to measure.
+ pub fn read_back(mut self) -> Self {
+ self.read_back = true;
+ self
+ }
+
+ /// The 3D image of the frame at `t`. It is a GPU texture when the backend shares the
+ /// GPU, and pixels otherwise.
+ pub fn image(&self, t: f32) -> fframes::media::ImageData<'static> {
+ if self.motion_blur(t) {
+ // Three moments in the open shutter blur the spin and the tumble.
+ let moment = |offset: f32| self.scene_at(t + offset * SHUTTER / FPS as f32);
+ if self.read_back {
+ return self
+ .renderer
+ .render_motion_blur_pixels(3, moment)
+ .into_image();
+ }
+ return self.renderer.render_motion_blur(3, moment);
+ }
+ let (scene, camera) = self.scene_at(t);
+ if self.read_back {
+ return self.renderer.render_pixels(&scene, &camera).into_image();
+ }
+ self.renderer.render(&scene, &camera)
+ }
+
+ /// The fast part: the spin, the throw and the tumble of the letter.
+ fn motion_blur(&self, t: f32) -> bool {
+ (self.show_off()..self.reaction()).contains(&t)
+ }
+
+ /// The time when the robot starts to show off with the "a".
+ fn show_off(&self) -> f32 {
+ self.placed_time(2) + 0.45
+ }
+
+ /// The time when the robot looks into the camera after the throw.
+ fn reaction(&self) -> f32 {
+ self.story.beats.drop + 1.25
+ }
+
+ /// The light level of the lab at `t`: off, a flicker, then on.
+ fn lights(&self, t: f32) -> f32 {
+ let on = self.story.beats.lights;
+ if t < on {
+ return 0.0;
+ }
+ let x = t - on;
+ if x < 0.35 {
+ // The tubes go on and off at these times.
+ let flick = [0.0f32, 0.06, 0.12, 0.2, 0.27];
+ let lit = flick.iter().filter(|&&f| x >= f).count() % 2 == 1;
+ if lit { 0.75 } else { 0.08 }
+ } else {
+ smoothstep(0.35, 0.6, x) * 0.25 + 0.75
+ }
+ }
+
+ /// The mean of `point` over the last 0.2 s, so that the cameras follow smoothly.
+ fn lagged(&self, t: f32, point: impl Fn(&Joints) -> Vec3) -> Vec3 {
+ (0..5)
+ .map(|k| point(&self.story.track.sample((t - k as f32 * 0.05).max(0.0)).q))
+ .sum::<Vec3>()
+ / 5.0
+ }
+
+ fn lagged_tip(&self, t: f32) -> Vec3 {
+ self.lagged(t, |q| arm::tip(q).w_axis.truncate())
+ }
+
+ fn lagged_eye(&self, t: f32) -> Vec3 {
+ self.lagged(t, arm::eye)
+ }
+
+ /// The time at which letter `i` goes into its place for the last time.
+ fn placed_time(&self, i: usize) -> f32 {
+ let letter = &self.story.letters[i];
+ letter
+ .phases
+ .iter()
+ .rev()
+ .find(|(_, p)| matches!(p, Phase::Still(m) if *m == letter.slot))
+ .map_or(0.0, |(t, _)| *t)
+ }
+
+ /// The cut list: one camera for each part of the story.
+ fn camera(&self, t: f32) -> Camera {
+ let b = &self.story.beats;
+ let lens = Camera::perspective(32.0);
+ let r_start = self.placed_time(2) - 1.2;
+ let (show_off, reaction) = (self.show_off(), self.reaction());
+ let last = self.placed_time(6);
+ if t < b.work {
+ // Hello: a low camera at the front right. The robot looks into this lens.
+ let x = progress(t, 0.0, b.work);
+ let eye = self.lagged_eye(t);
+ lens.fov(30.0)
+ .position(story::HELLO_CAMERA + vec3(0.25 * (1.0 - x), 0.05 * x, 0.35 * (1.0 - x)))
+ .look_at(eye.lerp(vec3(0.0, 0.9, 0.6), 0.35))
+ .focus_on(eye, 5.0)
+ } else if t < r_start {
+ // Work: a slow orbit that follows the gripper.
+ let x = progress(t, b.work, r_start);
+ let tip = self.lagged_tip(t);
+ lens.orbit(
+ vec3(0.0, 0.75, 0.2).lerp(tip, 0.25),
+ 5.4 - 0.4 * x,
+ -42.0 + 24.0 * x,
+ 13.0,
+ )
+ .focus_on(tip, 8.0)
+ } else if t < show_off {
+ // Low at the word when the r arrives.
+ let target = vec3(-0.35, 0.33, WORD_Z);
+ lens.fov(30.0)
+ .position(vec3(1.35, 0.42, 3.15))
+ .look_at(target)
+ .focus_on(target, 12.0)
+ } else if t < reaction {
+ // Wide for the swing and the throw. Each hit of the letter shakes the camera.
+ let x = progress(t, show_off, reaction);
+ let camera = lens
+ .fov(36.0)
+ .position(vec3(3.7 - 0.3 * x, 1.75, 4.4 - 0.3 * x))
+ .look_at(vec3(-0.25, 0.75, 0.25))
+ .focus(5.6, 5.0);
+ let hits = self.story.falls.iter().flat_map(|f| &f.impacts);
+ effects::shake(camera, t, hits.map(|&(at, speed)| (at, 0.35 * speed)))
+ } else if t < b.recover {
+ // Close on the eye. The robot looks into the lens.
+ let eye = self.lagged_eye(t);
+ lens.fov(28.0)
+ .position(story::GUILTY_CAMERA)
+ .look_at(eye.lerp(vec3(-0.2, 0.6, 0.6), 0.15))
+ .focus_on(eye, 14.0)
+ } else if t < b.finish {
+ // Low near the fallen letter while the robot moves over carefully.
+ let tip = self.lagged_tip(t);
+ let letter = self.story.letters[self.story.dropped]
+ .world(t, &self.story.track, &self.story.falls)
+ .w_axis
+ .truncate();
+ let target = letter.lerp(tip, 0.4);
+ lens.fov(34.0)
+ .position(vec3(2.9, 0.75, 2.9))
+ .look_at(target + vec3(0.0, 0.1, 0.0))
+ .focus_on(target, 9.0)
+ } else if t < last + 0.3 {
+ // High and wide for the fast work.
+ let x = progress(t, b.finish, last + 0.3);
+ lens.orbit(vec3(0.0, 0.55, 0.35), 6.4, 28.0 - 18.0 * x, 24.0 - 4.0 * x)
+ .focus(6.4, 4.0)
+ } else {
+ // The word, with the robot behind it as it bows.
+ let x = smoothstep(last + 0.3, b.end, t);
+ lens.fov(30.0)
+ .position(story::FINAL_CAMERA + vec3(0.0, -0.05 * x, -0.5 * x))
+ .look_at(vec3(0.0, 0.92, 0.55))
+ .focus(story::FINAL_CAMERA.z - WORD_Z - 0.5 * x, 6.0)
+ }
+ }
+
+ /// Dust in the air around the robot. Only the dust in the cone of the eye light shows,
+ /// as in a beam of sunlight: `beam` is how much the beam shows.
+ fn dust(&self, t: f32, q: &Joints, beam: f32) -> Vec<Particle> {
+ if beam <= 0.0 {
+ return Vec::new();
+ }
+ let eye = arm::eye(q);
+ let axis = arm::flange(q).z_axis.truncate();
+ let color = Rgb::hex(0xffd6a8);
+ (0..4000u32)
+ .filter_map(|i| {
+ let r = |k: u32| hash(i * 4 + k);
+ let home = vec3(-1.4 + 3.4 * r(0), 0.05 + 2.4 * r(1), -0.8 + 3.4 * r(2));
+ // The dust drifts slowly and sinks.
+ let drift = vec3(
+ noise(i, t * 0.25),
+ noise(i + 7919, t * 0.2),
+ noise(i + 15_485, t * 0.25),
+ );
+ let p = home + drift * 0.08 - Vec3::Y * 0.01 * t;
+ let to = p - eye;
+ let distance = to.length();
+ let cone = smoothstep(deg(17.0).cos(), deg(9.0).cos(), to.dot(axis) / distance);
+ let light = beam * cone / (1.0 + distance * distance);
+ (light > 0.01).then(|| {
+ // A few pixels wide: the depth of field gathers on a spiral, and it
+ // breaks a dot of one bright pixel into a pattern of dots.
+ Particle::new(p, 0.006 + 0.004 * r(3), color * (3.0 * light))
+ .opacity(light.min(1.0))
+ })
+ })
+ .collect()
+ }
+
+ /// The sparks of the dropped letter where it hits the floor.
+ fn sparks(&self, t: f32) -> Vec<Particle> {
+ let letter = &self.story.letters[self.story.dropped];
+ self.story
+ .falls
+ .iter()
+ .flat_map(|fall| &fall.impacts)
+ .enumerate()
+ .filter(|&(_, &(_, speed))| speed > 0.8)
+ .flat_map(|(i, &(at, speed))| {
+ let center = letter
+ .world(at, &self.story.track, &self.story.falls)
+ .w_axis;
+ let hit = vec3(center.x, 0.01, center.z);
+ let count = (speed * 12.0) as u32;
+ effects::sparks(hit, at, speed * 0.9, count, i as u32, t, 1.5 / FPS as f32)
+ })
+ .collect()
+ }
+
+ /// True while the gripper holds a letter.
+ fn carrying(&self, t: f32) -> bool {
+ self.story
+ .letters
+ .iter()
+ .any(|l| matches!(l.phase(t), Phase::Carried(_)))
+ }
+
+ /// The posed scene and the camera at `t`.
+ pub fn scene_at(&self, t: f32) -> (Scene, Camera) {
+ let mut scene = self.scene.clone();
+ lab::set_lights(&mut scene, &self.lab, self.lights(t));
+ let state = self.story.track.sample(t);
+ let wake = self.story.beats.wake;
+ let booting = smoothstep(wake, wake + 0.5, t);
+ // The eye flickers when it comes on.
+ let flicker = if (wake + 0.5..wake + 0.8).contains(&t)
+ && hash(((t - wake) * 40.0) as u32 + 5) > 0.5
+ {
+ 0.3
+ } else {
+ 1.0
+ };
+ let beam = (1.0 - self.lights(t)).clamp(0.0, 1.0);
+ let face = Expression {
+ ring: 0.8
+ + booting * (2.2 + 0.8 * (t * 2.0).sin().max(0.0))
+ + 3.0 * smoothstep(self.story.beats.tada, self.story.beats.tada + 0.3, t),
+ status: if self.carrying(t) { 7.0 } else { 0.5 * booting },
+ eye: 7.0 * smoothstep(wake + 0.5, wake + 0.8, t) * flicker,
+ lid: self.story.lid(t),
+ beam,
+ };
+ self.arm.apply(&mut scene, &state.q, state.gap, &face);
+ // The eye glows up to 7.
+ let dust = self.dust(t, &state.q, beam * face.eye / 7.0 * face.lid);
+ if let Object::Particles(p) = &mut scene[self.dust].object {
+ p.items = dust;
+ }
+ if let Object::Particles(p) = &mut scene[self.sparks].object {
+ p.items = self.sparks(t);
+ }
+ for (letter, node) in self.story.letters.iter().zip(&self.letter_nodes) {
+ let (_, rotation, position) = letter
+ .world(t, &self.story.track, &self.story.falls)
+ .to_scale_rotation_translation();
+ scene[*node].position = position;
+ scene[*node].rotation = rotation;
+ }
+ (scene, self.camera(t))
+ }
+
+ /// A bracket on the thrown letter while it lies on the floor, pinned to it with
+ /// [`Camera::project`] and sized with [`Camera::pixel_size`].
+ fn marker(&self, t: f32, camera: &Camera) -> Svgr<'static> {
+ let letter = &self.story.letters[self.story.dropped];
+ let lost = match letter.phase(t) {
+ Phase::Falling(_) => true,
+ Phase::Still(m) => *m != letter.slot,
+ Phase::Carried(_) => false,
+ };
+ let shown = smoothstep(self.story.beats.drop + 0.3, self.story.beats.drop + 0.5, t);
+ if !lost || shown <= 0.0 {
+ return Svgr::empty();
+ }
+ let world = letter.world(t, &self.story.track, &self.story.falls);
+ let center = world.transform_point3(letter.bounds.center());
+ let Some(at) = camera.project(center, WIDTH as f32, HEIGHT as f32) else {
+ return Svgr::empty();
+ };
+ let size = camera.pixel_size(center, 0.42, HEIGHT as f32);
+ let (x0, y0) = (at.x - size * 0.5, at.y - size * 0.5);
+ let (x1, y1) = (x0 + size, y0 + size);
+ let corner = (size * 0.22).max(8.0);
+ let corners = format!(
+ "M{x0} {} V{y0} H{} M{} {y0} H{x1} V{} M{x1} {} V{y1} H{} M{} {y1} H{x0} V{}",
+ y0 + corner,
+ x0 + corner,
+ x1 - corner,
+ y0 + corner,
+ y1 - corner,
+ x1 - corner,
+ x0 + corner,
+ y1 - corner,
+ );
+ let slot = letter.slot.transform_point3(letter.bounds.center());
+ let away = format!("{:.2} M FROM SLOT", center.distance(slot));
+ let name = WORD.chars().nth(self.story.dropped).unwrap_or('?');
+ let label = format!("PIECE {:02} \"{name}\"", self.story.dropped + 1);
+ svgr!(
+ <g opacity={shown} font-family={MONO} fill={ORANGE}>
+ <path d={corners} fill="none" stroke={ORANGE} stroke-width="2.5" />
+ <text x={x1 + 12.0} y={y0 + 14.0} font-weight="600" font-size="15" letter-spacing="2">{label}</text>
+ <text x={x1 + 12.0} y={y0 + 34.0} font-weight="400" font-size="13" letter-spacing="1.5">{away}</text>
+ </g>
+ )
+ }
+
+ /// The console, the counter, the caption and the fades.
+ fn overlay(&self, t: f32) -> Svgr<'static> {
+ let placed = self
+ .story
+ .letters
+ .iter()
+ .filter(|l| matches!(l.phase(t), Phase::Still(m) if *m == l.slot))
+ .count();
+ let b = &self.story.beats;
+ // The console is dark ink. It shows once the lab is lit.
+ let ui =
+ smoothstep(b.lights, b.lights + 0.4, t) * (1.0 - smoothstep(b.end - 0.6, b.end, t));
+ // The console shows the last five lines. They type out, and the newest is at the bottom.
+ let shown: Vec<_> = self.story.log.iter().filter(|l| l.t <= t).collect();
+ let tail = &shown[shown.len().saturating_sub(5)..];
+ let lines: Vec<Svgr> = tail
+ .iter()
+ .enumerate()
+ .map(|(i, line)| {
+ let chars = (((t - line.t) * 45.0) as usize).min(line.text.len());
+ let text: String = line.text.chars().take(chars).collect();
+ let y = 1000.0 - (tail.len() - 1 - i) as f32 * 24.0;
+ let fade = 0.35 + 0.65 * (i as f32 + 1.0) / tail.len() as f32;
+ let color = if line.alert { ORANGE } else { INK };
+ let cursor = if i == tail.len() - 1 && (t * 2.5).fract() < 0.5 { "_" } else { "" };
+ svgr!(<text x="96" y={y} fill={color} opacity={fade}>{format!("> {text}{cursor}")}</text>)
+ })
+ .collect();
+ let caption = smoothstep(b.tada + 0.3, b.tada + 0.8, t);
+ let d = self.duration();
+ let black = (1.0 - smoothstep(0.0, 0.4, t)).max(smoothstep(d - 0.5, d, t));
+ svgr!(
+ <g>
+ <g opacity={ui} font-family={MONO} font-weight="600" font-size="14" letter-spacing="3" fill={INK}>
+ <text x="96" y="100">"OD-ARM 7.2"</text>
+ <text x="96" y="122" opacity="0.5">"LAB 3 / CELL R-07"</text>
+ <text x="1824" y="100" text-anchor="end">{format!("{placed:02} / {:02}", self.story.letters.len())}</text>
+ <text x="1824" y="122" text-anchor="end" opacity="0.5">"PIECES IN PLACE"</text>
+ <g font-weight="400" font-size="15" letter-spacing="1.5">{lines}</g>
+ </g>
+ <g opacity={caption} font-family={MONO} fill={INK}>
+ <rect x="938" y="968" width="44" height="2" fill={ORANGE} />
+ <text x="960" y="1004" text-anchor="middle" font-weight="400" font-size="13" letter-spacing="6" opacity="0.6">"BUILT WITH FFRAMES-3D"</text>
+ </g>
+ <rect x="0" y="0" width="1920" height="1080" fill="#000000" opacity={black} />
+ </g>
+ )
+ }
+}
+
+impl Default for Show {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// The sound file and the level in dB of an event.
+fn effect(sound: Sound) -> (&'static str, f32) {
+ match sound {
+ Sound::LightsOn => ("lights.wav", -4.0),
+ Sound::Boot => ("boot.wav", -16.0),
+ Sound::Blink => ("blink.wav", -16.0),
+ Sound::Curious => ("curious.wav", -15.0),
+ Sound::Happy => ("happy.wav", -16.0),
+ Sound::Grip => ("grip.wav", -10.0),
+ Sound::Place => ("place.wav", -5.0),
+ Sound::Whoosh => ("whoosh.wav", -16.0),
+ Sound::Scratch => ("scratch.wav", -4.0),
+ Sound::Clatter(speed) => ("clatter.wav", -14.0 + 4.0 * speed.min(4.0)),
+ Sound::UhOh => ("uhoh.wav", -13.0),
+ Sound::Sigh => ("sigh.wav", -14.0),
+ Sound::Pat => ("pat.wav", -9.0),
+ Sound::Proud => ("proud.wav", -15.0),
+ Sound::TaDa => ("tada.wav", -14.0),
+ }
+}
+
+impl Video for Show {
+ const FPS: usize = FPS;
+ const WIDTH: usize = WIDTH;
+ const HEIGHT: usize = HEIGHT;
+ const BACKGROUND_COLOR: Color = Color::BLACK;
+
+ fn duration(&self) -> Duration<'_> {
+ Duration::Seconds(Show::duration(self))
+ }
+
+ fn audio(&self) -> AudioMap<'_> {
+ use AudioTimestamp::{Eof, Second};
+ let mut tracks = vec![
+ AudioTrack::new("music.wav", Second(0.0)..Eof).gain_db(-4.0),
+ AudioTrack::new("room.wav", Second(0.0)..Eof)
+ .gain_db(-18.0)
+ .fade_in(0.5),
+ AudioTrack::new("servos.wav", Second(0.0)..Eof).gain_db(-11.0),
+ ];
+ for &(t, sound) in &self.story.sounds {
+ let (file, gain) = effect(sound);
+ tracks.push(AudioTrack::new(file, Second(t.max(0.0))..Eof).gain_db(gain));
+ }
+ AudioMap::from(tracks)
+ }
+
+ fn render_frame<'a>(&'a self, frame: Frame, _ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {
+ let t = frame.seconds();
+ let image = self.image(t);
+ let marker = self.marker(t, &self.camera(t));
+ let overlay = self.overlay(t);
+ svgr!(
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1920 1080" width={WIDTH} height={HEIGHT}>
+ <image href={image.href()} x="0" y="0" width="1920" height="1080" />
+ {marker}
+ {overlay}
+ </svg>
+ )
+ }
+}
diff --git a/examples/arm/src/main.rs b/examples/arm/src/main.rs
new file mode 100644
index 00000000..30fb08d9
--- /dev/null
+++ b/examples/arm/src/main.rs
@@ -0,0 +1,85 @@
+use std::path::Path;
+use std::process::ExitCode;
+
+use arm_example::{ArmMedia, HEIGHT, Show, WIDTH};
+use fframes::cli::{self, clap};
+use fframes::{
+ AudioMixOptions, CombinedMediaProvider, EncoderOptions, LimiterOptions, MediaDirectory,
+ MediaProvider, RenderOptions, StaticMediaProvider,
+};
+use fframes_skia_renderer::{
+ SkiaFFramesRenderer, SkiaPipelineConcurrencyPolicy, SkiaPipelineConfig,
+};
+
+#[derive(Debug, clap::Args)]
+struct Args {
+ /// Render everything on the CPU: the 3D with the software rasterizer and the frame with
+ /// the tiny-skia backend.
+ #[arg(long, global = true)]
+ cpu: bool,
+ /// Read the 3D back from the GPU and upload it to Skia again. Use it to compare with the
+ /// GPU texture.
+ #[arg(long, global = true)]
+ readback: bool,
+}
+
+fn main() -> ExitCode {
+ let args = cli::parse::<Args>();
+ let media = ArmMedia::prepare().expect("media");
+ // `include_media_dir!` makes audio mono. The soundtrack is stereo, so it loads at run time.
+ let folder = Path::new(env!("CARGO_MANIFEST_DIR")).join("dynamic_media");
+ let dir = MediaDirectory::read_folder(&folder)
+ .expect("dynamic_media: run `cargo run -p arm-example --bin arm-soundtrack` first");
+ let sounds = dir.process_media_source().expect("dynamic media");
+ let all = CombinedMediaProvider::from([&media as &dyn MediaProvider, &sounds]);
+ let video = if args.app.cpu {
+ Show::new().on_cpu()
+ } else if args.app.readback {
+ Show::new().read_back()
+ } else {
+ Show::new()
+ };
+
+ let options = RenderOptions {
+ media: Some(&all),
+ video_encoder_options: EncoderOptions {
+ preferred_encoder: Some("libx264"),
+ codec_params: Some(&[("crf", "17"), ("preset", "medium"), ("tune", "film")]),
+ ..Default::default()
+ },
+ // The mix measures about -17.5 LUFS. This gain lifts it to about -14 LUFS.
+ audio_mix: AudioMixOptions {
+ master_gain_db: 6.5,
+ limiter: Some(LimiterOptions {
+ ceiling_db: -1.3,
+ ..Default::default()
+ }),
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let cpu = args.app.cpu;
+ let command = cli::new(&video, options)
+ .args(args)
+ .preview(fframes_native_player::cli_preview)
+ .default_output("out.mp4");
+ if cpu {
+ return command.run();
+ }
+
+ #[cfg(target_os = "macos")]
+ let gpu = fframes_skia_renderer::metal::SkiaMetalCtx::new(WIDTH, HEIGHT).expect("GPU context");
+ #[cfg(not(target_os = "macos"))]
+ let gpu =
+ fframes_skia_renderer::vulkan::SkiaVulkanCtx::new(WIDTH, HEIGHT).expect("GPU context");
+ let pipeline = SkiaPipelineConfig {
+ concurrency_policy: SkiaPipelineConcurrencyPolicy::MaxPerformance,
+ ..Default::default()
+ };
+ #[cfg(target_os = "macos")]
+ let backend = SkiaFFramesRenderer::new_metal(&gpu, pipeline);
+ #[cfg(not(target_os = "macos"))]
+ let backend = SkiaFFramesRenderer::new_vulkan(&gpu, pipeline);
+ command.backend(backend.expect("skia renderer")).run()
+}
diff --git a/examples/arm/src/story.rs b/examples/arm/src/story.rs
new file mode 100644
index 00000000..62983d5b
--- /dev/null
+++ b/examples/arm/src/story.rs
@@ -0,0 +1,899 @@
+//! The performance of the arm: keys with anticipation, overshoot and idle motion. It also
+//! holds the timelines of the letters, the tumble of the dropped letter and the events.
+
+use fframes::three_d::math::smoothstep;
+use fframes::three_d::*;
+
+use crate::arm::{self, Joints, OPEN, frame, looking, solve, tool_down};
+
+/// The easing into a key.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub enum Ease {
+ /// Slow start and slow stop (quintic).
+ Smooth,
+ /// Fast start and gentle stop.
+ Out,
+ /// Gentle start and fast stop.
+ In,
+ /// Goes past the key by `s` and comes back.
+ OutBack(f32),
+ /// Moves back by `s` before it goes (anticipation).
+ InBack(f32),
+}
+
+impl Ease {
+ pub fn apply(self, x: f32) -> f32 {
+ let x = x.clamp(0.0, 1.0);
+ match self {
+ Ease::Smooth => x * x * x * (x * (x * 6.0 - 15.0) + 10.0),
+ Ease::Out => 1.0 - (1.0 - x).powi(3),
+ Ease::In => x * x * x,
+ Ease::OutBack(s) => 1.0 + (s + 1.0) * (x - 1.0).powi(3) + s * (x - 1.0).powi(2),
+ Ease::InBack(s) => (s + 1.0) * x * x * x - s * x * x,
+ }
+ }
+}
+
+/// A key of the arm animation.
+#[derive(Debug, Clone, Copy)]
+pub struct Key {
+ pub t: f32,
+ pub q: Joints,
+ /// Half the finger gap.
+ pub gap: f32,
+ pub ease: Ease,
+ /// Amplitude of the idle motion.
+ pub alive: f32,
+}
+
+/// The arm at one moment.
+#[derive(Debug, Clone, Copy)]
+pub struct ArmState {
+ pub q: Joints,
+ pub gap: f32,
+}
+
+/// The keys of the arm, in time order.
+#[derive(Debug, Clone, Default)]
+pub struct Track {
+ pub keys: Vec<Key>,
+}
+
+impl Track {
+ pub fn sample(&self, t: f32) -> ArmState {
+ let k = self.keys.partition_point(|k| k.t <= t);
+ let (q, gap, alive) = if k == 0 {
+ let f = &self.keys[0];
+ (f.q, f.gap, f.alive)
+ } else if k >= self.keys.len() {
+ let l = &self.keys[self.keys.len() - 1];
+ (l.q, l.gap, l.alive)
+ } else {
+ let (a, b) = (&self.keys[k - 1], &self.keys[k]);
+ let s = (t - a.t) / (b.t - a.t).max(1e-6);
+ let x = b.ease.apply(s);
+ let linear = s.clamp(0.0, 1.0);
+ (
+ a.q.lerp(&b.q, x),
+ a.gap + (b.gap - a.gap) * x,
+ a.alive + (b.alive - a.alive) * linear,
+ )
+ };
+ // Idle motion: each joint sways slowly with its own frequency and phase.
+ let idle = [
+ 0.035 * (t * 1.3).sin(),
+ 0.03 * (t * 1.7 + 1.0).sin(),
+ 0.04 * (t * 2.1 + 2.0).sin(),
+ 0.05 * (t * 0.9 + 3.0).sin(),
+ 0.07 * (t * 1.1 + 0.5).sin(),
+ 0.04 * (t * 0.7 + 1.5).sin(),
+ ];
+ ArmState {
+ q: q.add(idle.map(|v| v * alive)),
+ gap,
+ }
+ }
+}
+
+/// Where a letter is during one part of its timeline.
+#[derive(Debug, Clone)]
+pub enum Phase {
+ /// At rest with this world transform.
+ Still(Mat4),
+ /// Held by the gripper with this offset from the grip point.
+ Carried(Mat4),
+ /// Falls along the tumble with this index in [`Story::falls`].
+ Falling(usize),
+}
+
+/// A precomputed tumble of a dropped letter.
+#[derive(Debug, Clone)]
+pub struct Fall {
+ pub start: f32,
+ /// The transforms at [`Fall::RATE`] steps per second.
+ pub frames: Vec<Mat4>,
+ /// The time and the speed in m/s of each hit on the floor.
+ pub impacts: Vec<(f32, f32)>,
+}
+
+impl Fall {
+ /// Simulation steps per second.
+ pub const RATE: f32 = 480.0;
+
+ /// The transform at `t`, interpolated between the simulation steps.
+ pub fn at(&self, t: f32) -> Mat4 {
+ let x = ((t - self.start) * Self::RATE).max(0.0);
+ let i = (x as usize).min(self.frames.len() - 1);
+ let j = (i + 1).min(self.frames.len() - 1);
+ let f = (x - i as f32).clamp(0.0, 1.0);
+ let (sa, ra, ta) = self.frames[i].to_scale_rotation_translation();
+ let (_, rb, tb) = self.frames[j].to_scale_rotation_translation();
+ Mat4::from_scale_rotation_translation(sa, ra.slerp(rb, f), ta.lerp(tb, f))
+ }
+
+ /// The time at which the tumble stops.
+ pub fn end(&self) -> f32 {
+ self.start + self.frames.len() as f32 / Self::RATE
+ }
+}
+
+/// A letter piece and its timeline.
+#[derive(Debug, Clone)]
+pub struct Letter {
+ pub geometry: Geometry,
+ /// Bounds in glyph space.
+ pub bounds: Aabb,
+ /// The transform of the letter in the rack.
+ pub rack: Mat4,
+ /// The transform of the letter in the word.
+ pub slot: Mat4,
+ /// The grip point on top of the letter, in glyph space.
+ pub top: Vec3,
+ /// Center and half width of the rightmost stem, in glyph space.
+ pub stem: (Vec3, f32),
+ /// The start time of each phase, in time order.
+ pub phases: Vec<(f32, Phase)>,
+}
+
+impl Letter {
+ /// The phase of the letter at `t`.
+ pub fn phase(&self, t: f32) -> &Phase {
+ let i = self
+ .phases
+ .partition_point(|(s, _)| *s <= t)
+ .saturating_sub(1);
+ &self.phases[i].1
+ }
+
+ /// The world transform of the letter at `t`.
+ pub fn world(&self, t: f32, track: &Track, falls: &[Fall]) -> Mat4 {
+ match self.phase(t) {
+ Phase::Still(m) => *m,
+ Phase::Carried(rel) => arm::tip(&track.sample(t).q) * *rel,
+ Phase::Falling(f) => falls[*f].at(t),
+ }
+ }
+}
+
+/// The sound events.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub enum Sound {
+ LightsOn,
+ Boot,
+ Blink,
+ Curious,
+ Happy,
+ Grip,
+ Place,
+ Whoosh,
+ Scratch,
+ /// A hit on the floor at this speed in m/s.
+ Clatter(f32),
+ UhOh,
+ Sigh,
+ Pat,
+ Proud,
+ TaDa,
+}
+
+/// A line of the robot console.
+#[derive(Debug, Clone)]
+pub struct LogLine {
+ pub t: f32,
+ pub text: &'static str,
+ /// The overlay shows the line in orange.
+ pub alert: bool,
+}
+
+/// The story beats. The cameras, the music and the overlay follow them.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct Beats {
+ pub lights: f32,
+ pub wake: f32,
+ pub work: f32,
+ pub drop: f32,
+ pub recover: f32,
+ pub finish: f32,
+ pub tada: f32,
+ pub end: f32,
+}
+
+/// The whole performance, built once.
+pub struct Story {
+ pub track: Track,
+ pub letters: Vec<Letter>,
+ pub falls: Vec<Fall>,
+ /// The sound events, in time order.
+ pub sounds: Vec<(f32, Sound)>,
+ pub log: Vec<LogLine>,
+ pub blinks: Vec<f32>,
+ pub beats: Beats,
+ /// Index of the letter that slips.
+ pub dropped: usize,
+}
+
+/// The camera the robot looks into after the drop.
+pub const GUILTY_CAMERA: Vec3 = Vec3::new(0.55, 1.32, 3.25);
+/// The camera the robot bows to at the end.
+pub const FINAL_CAMERA: Vec3 = Vec3::new(0.0, 1.25, 7.2);
+/// The camera the robot looks into when it wakes up.
+pub const HELLO_CAMERA: Vec3 = Vec3::new(3.2, 1.25, 4.9);
+
+/// Adds the keys one after the other. The last key is the inverse kinematics hint for the
+/// next key.
+struct Director {
+ track: Track,
+ t: f32,
+}
+
+impl Director {
+ fn last(&self) -> Key {
+ *self.track.keys.last().expect("first key")
+ }
+
+ /// Adds a key `dt` seconds after the last key.
+ fn key(&mut self, dt: f32, q: Joints, gap: f32, ease: Ease, alive: f32) {
+ self.t += dt;
+ self.track.keys.push(Key {
+ t: self.t,
+ q,
+ gap,
+ ease,
+ alive,
+ });
+ }
+
+ /// Adds a key that puts the grip point at `tip` with the tool frame `rotation`.
+ fn pose(
+ &mut self,
+ dt: f32,
+ tip: Vec3,
+ rotation: Quat,
+ gap: f32,
+ ease: Ease,
+ alive: f32,
+ ) -> Joints {
+ let q = solve(tip, rotation, &self.last().q);
+ self.key(dt, q, gap, ease, alive);
+ q
+ }
+
+ /// Adds a key with the eye at `at`, looking at `target`.
+ fn look(
+ &mut self,
+ dt: f32,
+ at: Vec3,
+ target: Vec3,
+ roll: f32,
+ ease: Ease,
+ alive: f32,
+ ) -> Joints {
+ let gap = self.last().gap;
+ self.pose(dt, at, looking(target - at, roll), gap, ease, alive)
+ }
+
+ /// Keeps the last pose for `dt` seconds.
+ fn hold(&mut self, dt: f32, alive: f32) {
+ let k = self.last();
+ self.key(dt, k.q, k.gap, Ease::Smooth, alive);
+ }
+
+ /// Opens or closes the fingers to `gap`.
+ fn gap(&mut self, dt: f32, gap: f32) {
+ let k = self.last();
+ self.key(dt, k.q, gap, Ease::Out, 0.0);
+ }
+
+ /// Adds `offsets` to the joint angles of the last key.
+ fn joints(&mut self, dt: f32, offsets: [f32; 6], ease: Ease, alive: f32) {
+ let k = self.last();
+ self.key(dt, k.q.add(offsets), k.gap, ease, alive);
+ }
+}
+
+/// The inside spans of a glyph at height `y`, by the even-odd rule.
+fn spans(shapes: &[Shape], y: f32) -> Vec<(f32, f32)> {
+ let mut xs = Vec::new();
+ for shape in shapes {
+ for contour in std::iter::once(&shape.outer).chain(&shape.holes) {
+ for i in 0..contour.len() {
+ let (a, b) = (contour[i], contour[(i + 1) % contour.len()]);
+ if (a.y > y) != (b.y > y) {
+ xs.push(a.x + (y - a.y) * (b.x - a.x) / (b.y - a.y));
+ }
+ }
+ }
+ }
+ xs.sort_by(f32::total_cmp);
+ xs.as_chunks::<2>().0.iter().map(|c| (c[0], c[1])).collect()
+}
+
+/// Simulates the tumble of a rigid letter: gravity and bounces that lose energy. Then the
+/// letter settles flat on its back, as a thin plate does.
+fn simulate_fall(start: f32, m0: Mat4, v0: Vec3, w0: Vec3, bounds: &Aabb) -> Fall {
+ let corners = bounds.corners();
+ let (_, mut rot, mut pos) = m0.to_scale_rotation_translation();
+ let (mut v, mut w) = (v0, w0);
+ let dt = 1.0 / Fall::RATE;
+ let mut frames = Vec::new();
+ let mut impacts = Vec::new();
+ let mut t = 0.0;
+ let mut settling: Option<(f32, Quat, Vec3)> = None;
+ loop {
+ frames.push(Mat4::from_rotation_translation(rot, pos));
+ if let Some((since, from_rot, from_pos)) = settling {
+ let x = ((t - since) / 0.45).min(1.0);
+ // The letter settles with the front face up. The up axis of the glyph keeps the
+ // horizontal direction of the fall.
+ let up = rot * Vec3::Y;
+ let heading = vec3(up.x, 0.0, up.z).normalize_or(Vec3::NEG_Z);
+ let target_rot = Quat::from_mat3(&Mat3::from_cols(
+ heading.cross(Vec3::Y).normalize(),
+ heading,
+ Vec3::Y,
+ ));
+ let e = 1.0 - (1.0 - x).powi(3);
+ rot = from_rot.slerp(target_rot, e);
+ let slide = from_pos + v * 0.12 * e;
+ pos = vec3(slide.x, 0.0, slide.z);
+ // The lowest corner stays on the floor.
+ let lowest = corners
+ .iter()
+ .map(|c| (rot * *c).y)
+ .fold(f32::INFINITY, f32::min);
+ pos.y = -lowest + (1.0 - e) * 0.03 * (x * 20.0).sin().abs();
+ if x >= 1.0 {
+ frames.push(Mat4::from_rotation_translation(rot, pos));
+ break;
+ }
+ } else {
+ v.y -= 9.81 * dt;
+ pos += v * dt;
+ rot = (Quat::from_scaled_axis(w * dt) * rot).normalize();
+ let lowest = corners
+ .iter()
+ .map(|c| (rot * *c + pos).y)
+ .fold(f32::INFINITY, f32::min);
+ if lowest < 0.0 && v.y < 0.0 {
+ pos.y -= lowest;
+ impacts.push((start + t, -v.y));
+ v.y = -v.y * 0.32;
+ v.x *= 0.55;
+ v.z *= 0.55;
+ // The corner that hits the floor changes the spin.
+ w = w * 0.45 + vec3(v.z, 0.0, -v.x) * 3.0;
+ if impacts.len() >= 2 || v.y < 0.7 {
+ settling = Some((t, rot, pos));
+ }
+ }
+ }
+ t += dt;
+ if t > 4.0 {
+ break;
+ }
+ }
+ Fall {
+ start,
+ frames,
+ impacts,
+ }
+}
+
+impl Story {
+ /// Builds the performance for `word`, with letters cut from `font`.
+ pub fn new(font: &[u8], word: &str) -> Story {
+ const SIZE: f32 = 0.68;
+ const DEPTH: f32 = 0.1;
+ const TRACKING: f32 = 0.035;
+ let glyphs = Geometry::text_glyphs(font, word, SIZE, DEPTH, 0.012)
+ .expect("the font has the letters");
+ let shapes =
+ Geometry::text_shapes(font, word, SIZE, 0.0).expect("the font has the letters");
+ let count = glyphs.len();
+ let width =
+ glyphs.last().map_or(0.0, |g| g.origin.x + g.advance) + TRACKING * (count - 1) as f32;
+ // The letter at each rack position, from left to right.
+ let rack_order = [4usize, 1, 6, 0, 3, 5, 2];
+ let mut letters: Vec<Letter> = glyphs
+ .into_iter()
+ .zip(shapes)
+ .enumerate()
+ .map(|(i, (glyph, outline))| {
+ let bounds = glyph.geometry.bounds();
+ let top_y = bounds.max.y;
+ let near: Vec<f32> = glyph
+ .geometry
+ .positions
+ .iter()
+ .filter(|p| p.y > top_y - 0.03)
+ .map(|p| p.x)
+ .collect();
+ let grip_x = near.iter().sum::<f32>() / near.len().max(1) as f32;
+ let stem_y = 0.32 * (bounds.max.y - bounds.min.y) + bounds.min.y;
+ let stem = spans(&outline.shapes, stem_y)
+ .last()
+ .map_or((vec3(bounds.center().x, stem_y, 0.0), 0.05), |&(a, b)| {
+ (vec3(f32::midpoint(a, b), stem_y, 0.0), (b - a) * 0.5)
+ });
+ let slot_index = rack_order.iter().position(|&r| r == i).unwrap_or(i) as f32;
+ let rack_x = -1.56 + slot_index * 0.52 - bounds.center().x;
+ let rack = Mat4::from_translation(vec3(rack_x, 0.02, crate::RACK_Z));
+ let slot = Mat4::from_translation(vec3(
+ glyph.origin.x + i as f32 * TRACKING - width * 0.5,
+ 0.0,
+ crate::WORD_Z,
+ ));
+ Letter {
+ geometry: glyph.geometry,
+ bounds,
+ rack,
+ slot,
+ top: vec3(grip_x, top_y - 0.035, 0.0),
+ stem,
+ phases: vec![(0.0, Phase::Still(rack))],
+ }
+ })
+ .collect();
+
+ let mut sounds: Vec<(f32, Sound)> = Vec::new();
+ let mut log: Vec<LogLine> = Vec::new();
+ let mut blinks = Vec::new();
+ let mut falls = Vec::new();
+ let mut beats = Beats::default();
+ let say = |log: &mut Vec<LogLine>, t: f32, text: &'static str, alert: bool| {
+ log.push(LogLine { t, text, alert });
+ };
+
+ // ---------------------------------------------------------------- Asleep
+ let asleep_tip = vec3(0.05, 0.24, 0.95);
+ let asleep = solve(
+ asleep_tip,
+ looking(vec3(0.05, -1.0, 0.45), 0.25),
+ &Joints {
+ q: [0.0, 0.4, 1.0, 0.0, 0.8, 0.0],
+ },
+ );
+ let mut d = Director {
+ track: Track {
+ keys: vec![Key {
+ t: 0.0,
+ q: asleep,
+ gap: 0.03,
+ ease: Ease::Smooth,
+ alive: 0.15,
+ }],
+ },
+ t: 0.0,
+ };
+ // The robot wakes up in the dark lab. Its eye comes on and lights the floor.
+ beats.wake = 0.8;
+ sounds.push((0.75, Sound::Boot));
+ say(&mut log, 0.8, "BOOT OD-ARM 7.2 ...... OK", false);
+ d.hold(2.0, 0.15);
+
+ // ---------------------------------------------------------------- Waking up
+ // A slow, tired lift with a sag halfway, a big stretch, then curiosity.
+ d.look(
+ 0.9,
+ vec3(0.1, 0.62, 0.95),
+ vec3(0.2, 0.0, 2.2),
+ 0.15,
+ Ease::InBack(0.4),
+ 0.3,
+ );
+ d.joints(0.35, [0.0, 0.08, 0.1, 0.0, 0.25, 0.0], Ease::Smooth, 0.2);
+ blinks.push(d.t + 0.1);
+ sounds.push((d.t + 0.1, Sound::Blink));
+ d.look(
+ 0.75,
+ vec3(0.0, 2.15, 0.55),
+ vec3(0.0, 3.5, 1.4),
+ 0.0,
+ Ease::OutBack(1.6),
+ 0.0,
+ );
+ // The lab lights flicker on when it reaches up.
+ beats.lights = d.t - 0.2;
+ sounds.push((beats.lights, Sound::LightsOn));
+ d.gap(0.2, OPEN);
+ d.look(
+ 0.55,
+ vec3(0.25, 1.35, 1.05),
+ HELLO_CAMERA,
+ 0.35,
+ Ease::OutBack(1.2),
+ 0.5,
+ );
+ sounds.push((d.t - 0.2, Sound::Curious));
+ say(&mut log, d.t - 0.2, "VISION ONLINE FACE DETECTED", false);
+ d.look(
+ 0.25,
+ vec3(0.25, 1.35, 1.05),
+ HELLO_CAMERA,
+ -0.25,
+ Ease::Smooth,
+ 0.4,
+ );
+ blinks.push(d.t);
+ sounds.push((d.t, Sound::Blink));
+ d.hold(0.3, 0.6);
+ // It looks at the rack, quickly at the camera, then happily back at the rack.
+ let rack_center = vec3(0.0, 0.3, crate::RACK_Z);
+ d.look(
+ 0.45,
+ vec3(-0.2, 1.4, -0.35),
+ rack_center,
+ 0.0,
+ Ease::Smooth,
+ 0.3,
+ );
+ d.look(0.2, vec3(0.2, 1.4, 0.7), HELLO_CAMERA, 0.2, Ease::Out, 0.2);
+ d.look(
+ 0.3,
+ vec3(-0.15, 1.45, -0.4),
+ rack_center,
+ -0.1,
+ Ease::OutBack(1.3),
+ 0.3,
+ );
+ sounds.push((d.t, Sound::Happy));
+ say(&mut log, d.t, "TASK SPELL \"fframes\"", false);
+ d.hold(0.25, 0.5);
+ beats.work = d.t;
+
+ // ---------------------------------------------------------------- Work
+ // The arm carries the letters this high above the rack and the word.
+ let carry = 0.68;
+ // The tool points down. The fingers clamp the thickness of the letter (world Z).
+ let rot = tool_down(Vec3::Z);
+ let pick_place = |d: &mut Director,
+ letters: &mut [Letter],
+ sounds: &mut Vec<(f32, Sound)>,
+ i: usize,
+ pace: f32,
+ flourish: bool| {
+ let l = &letters[i];
+ let grab = l.rack.transform_point3(l.top);
+ let place = l.slot.transform_point3(l.top);
+ d.pose(
+ 0.62 * pace,
+ grab + Vec3::Y * carry,
+ rot,
+ OPEN,
+ Ease::Smooth,
+ 0.0,
+ );
+ d.pose(0.24 * pace, grab, rot, OPEN, Ease::Smooth, 0.0);
+ d.gap(0.12 * pace, 0.057);
+ let t_grab = d.t - 0.04 * pace;
+ sounds.push((t_grab - 0.05, Sound::Grip));
+ let tip = arm::tip(&d.track.sample(t_grab).q);
+ let rel = tip.inverse() * letters[i].rack;
+ letters[i].phases.push((t_grab, Phase::Carried(rel)));
+ d.pose(
+ 0.24 * pace,
+ grab + Vec3::Y * carry,
+ rot,
+ 0.057,
+ Ease::OutBack(0.6),
+ 0.0,
+ );
+ sounds.push((d.t, Sound::Whoosh));
+ d.pose(
+ 0.62 * pace,
+ place + Vec3::Y * carry,
+ rot,
+ 0.057,
+ if flourish {
+ Ease::OutBack(1.0)
+ } else {
+ Ease::Smooth
+ },
+ 0.0,
+ );
+ d.pose(0.24 * pace, place, rot, 0.057, Ease::In, 0.0);
+ let t_place = d.t;
+ let slot = letters[i].slot;
+ letters[i].phases.push((t_place, Phase::Still(slot)));
+ sounds.push((t_place, Sound::Place));
+ d.gap(0.1 * pace, OPEN);
+ d.pose(
+ 0.22 * pace,
+ place + Vec3::Y * 0.35,
+ rot,
+ OPEN,
+ Ease::Out,
+ 0.2,
+ );
+ t_place
+ };
+ let t0 = pick_place(&mut d, &mut letters, &mut sounds, 0, 1.05, false);
+ say(&mut log, t0, "PLACE f ............. OK", false);
+ let t1 = pick_place(&mut d, &mut letters, &mut sounds, 1, 0.8, false);
+ say(&mut log, t1, "PLACE f ............. OK", false);
+ // It gets too confident: a small wiggle after the r.
+ let t2 = pick_place(&mut d, &mut letters, &mut sounds, 2, 0.68, true);
+ say(&mut log, t2, "PLACE r ............. OK", false);
+ d.joints(0.12, [0.0, 0.0, 0.0, 0.0, 0.0, 0.5], Ease::Out, 0.0);
+ d.joints(0.12, [0.0, 0.0, 0.0, 0.0, 0.0, -1.0], Ease::Smooth, 0.0);
+ d.joints(
+ 0.14,
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.5],
+ Ease::OutBack(1.0),
+ 0.0,
+ );
+ sounds.push((d.t, Sound::Happy));
+
+ // ---------------------------------------------------------------- The swing
+ let a = 3;
+ let l = &letters[a];
+ let grab = l.rack.transform_point3(l.top);
+ d.pose(0.5, grab + Vec3::Y * carry, rot, OPEN, Ease::Smooth, 0.0);
+ d.pose(0.2, grab, rot, OPEN, Ease::Smooth, 0.0);
+ d.gap(0.1, 0.057);
+ let t_grab = d.t - 0.03;
+ sounds.push((t_grab - 0.05, Sound::Grip));
+ let rel = arm::tip(&d.track.sample(t_grab).q).inverse() * letters[a].rack;
+ letters[a].phases.push((t_grab, Phase::Carried(rel)));
+ say(&mut log, d.t, "PLACE a WITH STYLE", false);
+ // Up high, a small move back, then a big swing with a spin towards the word.
+ let high = grab + vec3(0.0, 1.05, 0.25);
+ d.pose(0.3, high, rot, 0.057, Ease::OutBack(0.8), 0.0);
+ d.joints(0.25, [0.12, -0.1, -0.1, 0.0, 0.0, -0.6], Ease::Smooth, 0.0);
+ let swing_from = d.t;
+ let target_above = letters[a].slot.transform_point3(letters[a].top) + Vec3::Y * carry;
+ let mut q = solve(target_above + vec3(0.25, 0.25, 0.0), rot, &d.last().q);
+ q.q[5] += std::f32::consts::TAU * 1.5;
+ d.key(0.95, q, 0.057, Ease::InBack(0.25), 0.0);
+ sounds.push((swing_from + 0.15, Sound::Whoosh));
+ // It opens the gripper a little too early.
+ let t_drop = swing_from + 0.62;
+ beats.drop = t_drop;
+ let dt = 1.0 / 240.0;
+ let at = |t: f32| arm::tip(&d.track.sample(t).q) * rel;
+ let (m0, ma, mb) = (at(t_drop), at(t_drop - dt), at(t_drop + dt));
+ let v0 = (mb.w_axis - ma.w_axis).truncate() / (2.0 * dt);
+ let (_, ra, _) = ma.to_scale_rotation_translation();
+ let (_, rb, _) = mb.to_scale_rotation_translation();
+ let w0 = (rb * ra.inverse()).to_scaled_axis() / (2.0 * dt);
+ // Aim the throw so that the letter lands in the reach of the arm and in view.
+ let landing = vec3(1.3, 0.0, 0.4);
+ let p0 = m0.w_axis.truncate();
+ let vy = v0.y.clamp(-0.5, 1.5);
+ let flight = (vy + (vy * vy + 2.0 * 9.81 * p0.y).sqrt()) / 9.81;
+ let reach = (landing - p0) * 0.85 / flight;
+ let v0 = vec3(reach.x, vy, reach.z);
+ let fall = simulate_fall(t_drop, m0, v0, w0 * 0.6, &letters[a].bounds);
+ let lying = *fall.frames.last().expect("frames");
+ for &(t, speed) in &fall.impacts {
+ sounds.push((t, Sound::Clatter(speed)));
+ }
+ let fall_end = fall.end();
+ falls.push(fall);
+ letters[a].phases.push((t_drop, Phase::Falling(0)));
+ letters[a].phases.push((fall_end, Phase::Still(lying)));
+ sounds.push((t_drop, Sound::Scratch));
+ say(&mut log, t_drop + 0.05, "ERR 0x7A GRIP LOST", true);
+ sounds.push((t_drop - 0.05, Sound::Grip));
+
+ // ---------------------------------------------------------------- After the drop
+ d.gap(0.15, OPEN);
+ d.hold(0.55, 0.0);
+ let letter_at = lying.transform_point3(letters[a].bounds.center());
+ let head = d.last();
+ let head_pos = arm::tip(&head.q).w_axis.truncate();
+ // A slow turn to the letter on the floor.
+ d.look(
+ 0.8,
+ head_pos + vec3(0.0, -0.1, 0.0),
+ letter_at,
+ 0.2,
+ Ease::Smooth,
+ 0.1,
+ );
+ sounds.push((d.t - 0.1, Sound::UhOh));
+ say(&mut log, d.t, "STATUS NOBODY SAW THAT", false);
+ d.hold(0.5, 0.2);
+ // Then it looks into the camera.
+ let guilty = vec3(0.3, 1.3, 1.25);
+ d.look(0.7, guilty, GUILTY_CAMERA, -0.25, Ease::Smooth, 0.0);
+ blinks.push(d.t + 0.5);
+ sounds.push((d.t + 0.5, Sound::Blink));
+ d.hold(1.0, 0.3);
+ // A quick look at the letter and back into the camera.
+ d.look(0.16, guilty, letter_at, 0.1, Ease::Out, 0.0);
+ d.hold(0.18, 0.0);
+ d.look(0.16, guilty, GUILTY_CAMERA, -0.2, Ease::Out, 0.0);
+ d.hold(0.35, 0.2);
+ blinks.push(d.t - 0.1);
+ say(&mut log, d.t, "SOMEBODY SAW THAT", true);
+ // The sigh: the whole arm sags.
+ d.joints(0.75, [0.0, 0.18, 0.28, 0.0, 0.45, 0.0], Ease::Smooth, 0.0);
+ sounds.push((d.t - 0.6, Sound::Sigh));
+ d.hold(0.35, 0.2);
+ beats.recover = d.t;
+
+ // ---------------------------------------------------------------- The careful recovery
+ say(&mut log, d.t, "RETRY a (CAREFULLY)", false);
+ let (stem_center, stem_half) = letters[a].stem;
+ let stem_world = lying.transform_point3(stem_center);
+ let (_, lying_rot, _) = lying.to_scale_rotation_translation();
+ let grab_rot = lying_rot * frame(Vec3::X, Vec3::NEG_Z);
+ // It moves over carefully and looks at the letter.
+ d.look(
+ 0.75,
+ stem_world + vec3(0.0, 0.55, 0.25),
+ stem_world,
+ 0.3,
+ Ease::Smooth,
+ 0.1,
+ );
+ d.hold(0.3, 0.2);
+ d.pose(
+ 0.6,
+ stem_world + Vec3::Y * 0.3,
+ grab_rot,
+ OPEN,
+ Ease::Smooth,
+ 0.0,
+ );
+ d.pose(0.45, stem_world, grab_rot, OPEN, Ease::Smooth, 0.0);
+ let stem_gap = stem_half + 0.007;
+ d.gap(0.2, stem_gap);
+ let t_regrab = d.t - 0.05;
+ sounds.push((t_regrab - 0.05, Sound::Grip));
+ let rel2 = arm::tip(&d.track.sample(t_regrab).q).inverse() * lying;
+ letters[a].phases.push((t_regrab, Phase::Carried(rel2)));
+ d.pose(
+ 0.55,
+ stem_world + Vec3::Y * 0.4,
+ grab_rot,
+ stem_gap,
+ Ease::Smooth,
+ 0.0,
+ );
+ // It stands the letter up in the air. Then it lowers the letter into its place.
+ let slot_tip = letters[a].slot * rel2.inverse();
+ let (_, slot_rot, slot_pos) = slot_tip.to_scale_rotation_translation();
+ d.pose(
+ 1.0,
+ slot_pos + Vec3::Y * 0.35,
+ slot_rot,
+ stem_gap,
+ Ease::Smooth,
+ 0.0,
+ );
+ d.pose(0.5, slot_pos, slot_rot, stem_gap, Ease::Smooth, 0.0);
+ let t_place = d.t;
+ let slot = letters[a].slot;
+ letters[a].phases.push((t_place, Phase::Still(slot)));
+ sounds.push((t_place, Sound::Place));
+ say(&mut log, t_place, "PLACE a ............. OK", false);
+ d.gap(0.12, OPEN);
+ let back = slot_rot * Vec3::NEG_Z;
+ d.pose(
+ 0.35,
+ slot_pos + back * 0.2 + Vec3::Y * 0.05,
+ slot_rot,
+ OPEN,
+ Ease::Out,
+ 0.0,
+ );
+ // Two pats on the letter.
+ let top = letters[a].slot.transform_point3(letters[a].top);
+ d.pose(0.45, top + Vec3::Y * 0.16, rot, 0.03, Ease::Smooth, 0.0);
+ for _ in 0..2 {
+ d.pose(0.1, top + Vec3::Y * 0.05, rot, 0.03, Ease::In, 0.0);
+ sounds.push((d.t, Sound::Pat));
+ d.pose(0.14, top + Vec3::Y * 0.16, rot, 0.03, Ease::Out, 0.0);
+ }
+ d.joints(
+ 0.25,
+ [0.0, -0.05, -0.05, 0.0, -0.3, 0.0],
+ Ease::OutBack(1.5),
+ 0.3,
+ );
+ sounds.push((d.t - 0.1, Sound::Happy));
+ beats.finish = d.t;
+
+ // ---------------------------------------------------------------- Confident again
+ for (i, pace) in [(4usize, 0.62f32), (5, 0.58), (6, 0.56)] {
+ let t = pick_place(&mut d, &mut letters, &mut sounds, i, pace, false);
+ say(
+ &mut log,
+ t,
+ match i {
+ 4 => "PLACE m ............. OK",
+ 5 => "PLACE e ............. OK",
+ _ => "PLACE s ............. OK",
+ },
+ false,
+ );
+ }
+ say(&mut log, d.t + 0.1, "TASK COMPLETE 1 INCIDENT", false);
+
+ // ---------------------------------------------------------------- Admire, bow, ta-da
+ let word_center = vec3(0.0, 0.25, crate::WORD_Z);
+ d.look(
+ 0.7,
+ vec3(0.0, 1.55, 0.55),
+ word_center,
+ 0.0,
+ Ease::Smooth,
+ 0.3,
+ );
+ d.hold(0.5, 0.5);
+ d.look(
+ 0.5,
+ vec3(0.0, 1.5, 0.75),
+ FINAL_CAMERA,
+ 0.25,
+ Ease::OutBack(1.2),
+ 0.3,
+ );
+ sounds.push((d.t - 0.1, Sound::Proud));
+ d.hold(0.35, 0.4);
+ // The bow.
+ d.joints(0.45, [0.0, 0.22, 0.3, 0.0, 0.65, 0.0], Ease::Smooth, 0.0);
+ d.hold(0.25, 0.0);
+ d.joints(
+ 0.4,
+ [0.0, -0.24, -0.32, 0.0, -0.7, 0.0],
+ Ease::OutBack(1.3),
+ 0.2,
+ );
+ beats.tada = d.t;
+ sounds.push((d.t, Sound::TaDa));
+ say(&mut log, d.t, "HUMILITY NOT FOUND", false);
+ for _ in 0..2 {
+ d.gap(0.09, 0.02);
+ d.gap(0.09, OPEN);
+ }
+ blinks.push(d.t + 0.2);
+ d.hold(1.7, 0.6);
+ beats.end = d.t;
+
+ sounds.sort_by(|a, b| a.0.total_cmp(&b.0));
+ Story {
+ track: d.track,
+ letters,
+ falls,
+ sounds,
+ log,
+ blinks,
+ beats,
+ dropped: a,
+ }
+ }
+
+ /// The eye lid at `t`: 1 is open, 0 is closed.
+ pub fn lid(&self, t: f32) -> f32 {
+ let awake = smoothstep(self.beats.wake + 0.6, self.beats.wake + 1.0, t);
+ let blink = self
+ .blinks
+ .iter()
+ .map(|b| 1.0 - smoothstep(0.0, 0.07, (t - b).abs()))
+ .fold(0.0, f32::max);
+ awake * (1.0 - blink)
+ }
+}
diff --git a/fframes-media/Cargo.toml b/fframes-media/Cargo.toml
index 06c51211..ca069b15 100644
--- a/fframes-media/Cargo.toml
+++ b/fframes-media/Cargo.toml
@@ -30,6 +30,9 @@ image = { version = "0.25.6", default-features = false, features = [
] }
usvgr.workspace = true
libc = "0.2.159"
+log = "0.4"
+# The `wgpu` feature only: the editor never shares a GPU.
+wgpu = { version = "30", optional = true, default-features = false, features = ["std", "parking_lot", "wgsl", "vulkan", "metal", "dx12"] }
# FFmpeg is linked statically everywhere except Windows. ffmpeg-sys-fframes downloads a
# prebuilt static FFmpeg for the target and codec features from its GitHub releases and
@@ -69,6 +72,9 @@ mediacodec = ["ffmpeg-sys-fframes/build-mediacodec"]
direct3d11 = ["ffmpeg-sys-fframes/build-lib-d3d11va"]
direct3d9 = ["ffmpeg-sys-fframes/build-lib-dxva2"]
exif = ["kamadak-exif"]
+# `wgpu_layer`: textures rendered with wgpu on the GPU of the rendering backend go into
+# frames without leaving the GPU (fframes re-exports it, fframes_three_d uses it)
+wgpu = ["dep:wgpu"]
# licensing stuff
libav-agree-gpl = ["ffmpeg-sys-fframes/build-license-gpl"]
diff --git a/fframes-media/src/lib.rs b/fframes-media/src/lib.rs
index b6a695a7..67c2e1b1 100644
--- a/fframes-media/src/lib.rs
+++ b/fframes-media/src/lib.rs
@@ -29,6 +29,14 @@ mod video_decoder;
pub use ffmpeg_sys_fframes;
#[cfg(not(target_arch = "wasm32"))]
pub use video_decoder::*;
+// For fframes shaders and wgpu layers, not public API.
+#[cfg(not(target_arch = "wasm32"))]
+#[doc(hidden)]
+pub mod markers;
+#[cfg(all(feature = "wgpu", not(target_arch = "wasm32")))]
+pub use wgpu;
+#[cfg(all(feature = "wgpu", not(target_arch = "wasm32")))]
+pub mod wgpu_layer;
#[cfg(feature = "exif")]
pub use exif;
diff --git a/fframes-media/src/markers.rs b/fframes-media/src/markers.rs
new file mode 100644
index 00000000..dbec100c
--- /dev/null
+++ b/fframes-media/src/markers.rs
@@ -0,0 +1,115 @@
+//! Markers: images in a frame that stand for something a rendering backend draws itself,
+//! for example a shader or a GPU texture. The backend resolves a marker to its value.
+//!
+//! A marker is a 1x1 transparent image with a unique id. A renderer that does not know
+//! the marker draws nothing. A cache keyed by the id never returns an old marker.
+
+use std::borrow::Cow;
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{Arc, Mutex, PoisonError, Weak};
+
+use crate::{ImageData, ImageMetadata};
+
+static PIXEL: [u8; 4] = [0; 4];
+
+/// The markers of one kind of value: the live ones of the frames in flight, a few dozen at
+/// most, each with the image that stands for it.
+pub struct Markers<T> {
+ prefix: &'static str,
+ next: AtomicU64,
+ entries: Mutex<Vec<(Weak<usvgr::PreloadedImageData>, Arc<T>)>>,
+}
+
+impl<T> Markers<T> {
+ pub const fn new(prefix: &'static str) -> Self {
+ Self {
+ prefix,
+ next: AtomicU64::new(0),
+ entries: Mutex::new(Vec::new()),
+ }
+ }
+
+ /// A marker that resolves to `value`. `width` and `height` are what the frame reports
+ /// for the image.
+ pub fn create(&self, value: T, width: u32, height: u32) -> ImageData<'static> {
+ let image = self.image();
+ let mut entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
+ // a value lives as long as its image: drop the ones whose frames are done
+ entries.retain(|(image, _)| image.strong_count() > 0);
+ entries.push((Arc::downgrade(&image), Arc::new(value)));
+ Self::image_data(image, width, height)
+ }
+
+ /// A marker that resolves to nothing: an image that draws nothing.
+ pub fn empty(&self, width: u32, height: u32) -> ImageData<'static> {
+ Self::image_data(self.image(), width, height)
+ }
+
+ /// The value of `image` if it is one of these markers.
+ pub fn resolve(&self, image: &Arc<usvgr::PreloadedImageData>) -> Option<Arc<T>> {
+ if !image.id.starts_with(self.prefix) {
+ return None;
+ }
+ let entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
+ entries
+ .iter()
+ .find(|(weak, _)| weak.as_ptr() == Arc::as_ptr(image))
+ .map(|(_, value)| Arc::clone(value))
+ }
+
+ /// Drops the values for which `keep` is false.
+ pub fn retain(&self, keep: impl Fn(&T) -> bool) {
+ let mut entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
+ entries.retain(|(_, value)| keep(value));
+ }
+
+ fn image(&self) -> Arc<usvgr::PreloadedImageData> {
+ Arc::new(usvgr::PreloadedImageData {
+ data: Cow::Borrowed(&PIXEL),
+ width: 1,
+ height: 1,
+ id: format!(
+ "{}{}",
+ self.prefix,
+ self.next.fetch_add(1, Ordering::Relaxed)
+ ),
+ })
+ }
+
+ fn image_data(
+ image: Arc<usvgr::PreloadedImageData>,
+ width: u32,
+ height: u32,
+ ) -> ImageData<'static> {
+ let id = image.id.clone();
+ ImageData::new_from_raw_data(image, id, ImageMetadata { width, height })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn markers_resolve_while_their_image_lives() {
+ static MARKERS: Markers<u32> = Markers::new("test:");
+ let marker = MARKERS.create(7, 4, 4);
+ let image = marker.href();
+ assert!(image.id.starts_with("test:"));
+ assert_eq!(MARKERS.resolve(&image).as_deref(), Some(&7));
+
+ let plain = Arc::new(usvgr::PreloadedImageData {
+ data: Cow::Owned(vec![255; 4]),
+ width: 1,
+ height: 1,
+ id: "photo.png".to_owned(),
+ });
+ assert!(MARKERS.resolve(&plain).is_none());
+
+ drop(marker);
+ drop(image);
+ // the next marker sweeps the dead one
+ let _next = MARKERS.create(8, 1, 1);
+ assert_eq!(MARKERS.entries.lock().unwrap().len(), 1);
+ }
+}
diff --git a/fframes-media/src/wgpu_layer.rs b/fframes-media/src/wgpu_layer.rs
new file mode 100644
index 00000000..6323b1ec
--- /dev/null
+++ b/fframes-media/src/wgpu_layer.rs
@@ -0,0 +1,340 @@
+//! Textures rendered with wgpu as images of a frame (feature `wgpu`).
+//!
+//! A rendering backend that can share its GPU opens its device as a wgpu device and
+//! registers it with [`register_shared_gpu`]. Code that renders with wgpu gets the device
+//! from [`shared_gpu`], renders into a texture, and puts the texture into the frame with
+//! [`wgpu_layer`]. The backend draws the texture where the frame shows it. The pixels stay
+//! on the GPU.
+//!
+//! ```rust,ignore
+//! use fframes::wgpu;
+//!
+//! let Some(gpu) = fframes::shared_gpu() else {
+//! return render_on_the_cpu(); // the CPU backend, the editor
+//! };
+//! let texture = gpu.device().create_texture(&wgpu::TextureDescriptor {
+//! label: Some("my layer"),
+//! size: wgpu::Extent3d { width: 1920, height: 1080, depth_or_array_layers: 1 },
+//! mip_level_count: 1,
+//! sample_count: 1,
+//! dimension: wgpu::TextureDimension::D2,
+//! format: fframes::WGPU_LAYER_FORMAT,
+//! usage: fframes::WGPU_LAYER_USAGE | wgpu::TextureUsages::RENDER_ATTACHMENT,
+//! view_formats: &[],
+//! });
+//! let mut encoder = gpu.device().create_command_encoder(&Default::default());
+//! // render passes into `texture`
+//! fframes::finish_wgpu_layer(&mut encoder, &texture);
+//! gpu.submit([encoder.finish()]);
+//! let layer = fframes::wgpu_layer(&gpu, &texture);
+//! svgr!(<image href={layer.href()} x="0" y="0" width="1920" height="1080" />)
+//! ```
+//!
+//! Render into the texture again only after the image from [`wgpu_layer`] is dropped. At
+//! that point the backend has submitted the frame that samples the texture, and the queue
+//! orders the next render after it. The GPU can still sample the texture then, so keep it
+//! alive: reuse it from a pool and drop it with the device. wgpu waits for its own
+//! submissions before it frees a texture, not for the frames of the backend.
+
+use std::any::{Any, TypeId};
+use std::collections::HashMap;
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{Arc, Mutex, OnceLock, PoisonError, Weak};
+
+use crate::ImageData;
+use crate::markers::Markers;
+
+/// The texture format of a layer: premultiplied, sRGB encoded RGBA, like every other image
+/// of a frame.
+pub const WGPU_LAYER_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
+
+/// The usages a layer texture needs in addition to the ones it is rendered with. The
+/// backend samples it. Skia requires copies in both directions on a wrapped texture, and a
+/// copy out is the fallback for backends without the shared GPU.
+pub const WGPU_LAYER_USAGE: wgpu::TextureUsages = wgpu::TextureUsages::TEXTURE_BINDING
+ .union(wgpu::TextureUsages::COPY_SRC)
+ .union(wgpu::TextureUsages::COPY_DST);
+
+/// The GPU of a rendering backend, opened as a wgpu device. Its queue is the queue the
+/// backend draws frames with. The queue orders a layer before the frame that samples it.
+#[derive(Clone)]
+pub struct SharedGpu {
+ inner: Arc<SharedGpuInner>,
+}
+
+struct SharedGpuInner {
+ id: u64,
+ device: wgpu::Device,
+ queue: wgpu::Queue,
+ queue_lock: Arc<Mutex<()>>,
+ /// A cell for each type of state, see [`SharedGpu::state`].
+ state: Mutex<HashMap<TypeId, Arc<StateCell>>>,
+}
+
+/// The state of one type on a [`SharedGpu`].
+type StateCell = OnceLock<Arc<dyn Any + Send + Sync>>;
+
+static NEXT_ID: AtomicU64 = AtomicU64::new(1);
+/// The ids of the pixels read back from layers.
+static NEXT_PIXELS: AtomicU64 = AtomicU64::new(0);
+static ACTIVE: Mutex<Weak<SharedGpuInner>> = Mutex::new(Weak::new());
+static LAYERS: Markers<WgpuLayer> = Markers::new("fframes-wgpu:");
+
+impl SharedGpu {
+ /// `queue` is the queue the backend submits frames to. The backend holds `queue_lock`
+ /// while it submits to that queue.
+ pub fn new(device: wgpu::Device, queue: wgpu::Queue, queue_lock: Arc<Mutex<()>>) -> Self {
+ Self {
+ inner: Arc::new(SharedGpuInner {
+ id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
+ device,
+ queue,
+ queue_lock,
+ state: Mutex::new(HashMap::new()),
+ }),
+ }
+ }
+
+ /// Unique for each device, for caches keyed by device.
+ pub fn id(&self) -> u64 {
+ self.inner.id
+ }
+
+ pub fn device(&self) -> &wgpu::Device {
+ &self.inner.device
+ }
+
+ pub fn queue(&self) -> &wgpu::Queue {
+ &self.inner.queue
+ }
+
+ /// Submits with the backend's queue lock held. Submit all layer work here. A plain
+ /// `queue.submit` races the backend's own submissions.
+ pub fn submit<I: IntoIterator<Item = wgpu::CommandBuffer>>(
+ &self,
+ command_buffers: I,
+ ) -> wgpu::SubmissionIndex {
+ let _queue = self
+ .inner
+ .queue_lock
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner);
+ self.inner.queue.submit(command_buffers)
+ }
+
+ /// The backend's queue lock, for code that keeps the device but not the `SharedGpu`.
+ pub fn queue_lock(&self) -> Arc<Mutex<()>> {
+ Arc::clone(&self.inner.queue_lock)
+ }
+
+ /// State of code that renders on this device: pipelines, caches, texture pools. `init`
+ /// makes it on first use. It is dropped with the device, so it must not hold a
+ /// `SharedGpu`; keep the `wgpu::Device` and `wgpu::Queue` instead.
+ ///
+ /// `init` runs once for each type. It can use the state of other types. Other threads
+ /// that want the same type wait for it.
+ pub fn state<T: Any + Send + Sync>(&self, init: impl FnOnce(&SharedGpu) -> T) -> Arc<T> {
+ // The map is locked only to find the cell. `init` runs on the cell.
+ let cell = Arc::clone(
+ self.inner
+ .state
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .entry(TypeId::of::<T>())
+ .or_default(),
+ );
+ let state: Arc<dyn Any + Send + Sync> =
+ Arc::clone(cell.get_or_init(|| Arc::new(init(self))));
+ state
+ .downcast::<T>()
+ .unwrap_or_else(|_| unreachable!("state is keyed by its type"))
+ }
+}
+
+impl std::fmt::Debug for SharedGpu {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("SharedGpu")
+ .field("id", &self.inner.id)
+ .finish_non_exhaustive()
+ }
+}
+
+/// Makes `gpu` the device that [`shared_gpu`] returns, as long as the backend keeps it.
+/// Called by backends.
+pub fn register_shared_gpu(gpu: &SharedGpu) {
+ *ACTIVE.lock().unwrap_or_else(PoisonError::into_inner) = Arc::downgrade(&gpu.inner);
+}
+
+/// The GPU of the backend that renders the video, when the backend shares it (the Skia
+/// Vulkan backend with its `wgpu` feature). `None` with every other backend: the CPU
+/// backend, Skia without the feature, the editor. Render into pixels then.
+///
+/// It is the GPU of the Skia Vulkan context that was made last and is still alive. The
+/// tiny-skia CPU backend draws no layers, so do not keep such a context alive while it
+/// renders.
+pub fn shared_gpu() -> Option<SharedGpu> {
+ let inner = ACTIVE
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .upgrade()?;
+ Some(SharedGpu { inner })
+}
+
+/// Records the transition of `texture` to the sampled state. A layer must be in this state
+/// at the end of the last submission that renders it.
+pub fn finish_wgpu_layer(encoder: &mut wgpu::CommandEncoder, texture: &wgpu::Texture) {
+ encoder.transition_resources(
+ std::iter::empty(),
+ std::iter::once(wgpu::TextureTransition {
+ texture,
+ selector: None,
+ state: wgpu::TextureUses::RESOURCE,
+ }),
+ );
+}
+
+/// A texture rendered on the [`SharedGpu`] as an image of the frame. Use it as
+/// `<image href={layer.href()} .../>` like any other image.
+///
+/// The texture must be a 2D texture with one layer and one sample, with
+/// [`WGPU_LAYER_FORMAT`] and [`WGPU_LAYER_USAGE`]. Finish it with [`finish_wgpu_layer`] and
+/// submit it with [`SharedGpu::submit`] before the frame is returned. Render into it again
+/// only after the returned image is dropped, and keep it alive, see the [module](self).
+pub fn wgpu_layer(gpu: &SharedGpu, texture: &wgpu::Texture) -> ImageData<'static> {
+ let (width, height) = (texture.width(), texture.height());
+ // The backends wrap and read back one 2D image.
+ let single = texture.dimension() == wgpu::TextureDimension::D2
+ && texture.depth_or_array_layers() == 1
+ && texture.sample_count() == 1;
+ if !single
+ || texture.format() != WGPU_LAYER_FORMAT
+ || !texture.usage().contains(WGPU_LAYER_USAGE)
+ {
+ log::warn!(
+ "fframes: a wgpu layer needs a 2D {WGPU_LAYER_FORMAT:?} texture with one layer, one sample and {WGPU_LAYER_USAGE:?}, got a {:?} {:?} texture with {} layers, {} samples and {:?}",
+ texture.dimension(),
+ texture.format(),
+ texture.depth_or_array_layers(),
+ texture.sample_count(),
+ texture.usage()
+ );
+ return LAYERS.empty(width, height);
+ }
+ LAYERS.create(
+ WgpuLayer {
+ gpu: gpu.clone(),
+ texture: texture.clone(),
+ pixels: OnceLock::new(),
+ },
+ width,
+ height,
+ )
+}
+
+/// The layer behind `image`, if [`wgpu_layer`] made it. Rendering backends call this for
+/// every raster image.
+pub fn resolve_wgpu_layer(image: &Arc<usvgr::PreloadedImageData>) -> Option<Arc<WgpuLayer>> {
+ LAYERS.resolve(image)
+}
+
+/// Drops every layer rendered on `gpu`, so that no texture outlives the device, and stops
+/// [`shared_gpu`] from returning it. The backend calls this when its contexts are done.
+pub fn release_wgpu_layers(gpu: &SharedGpu) {
+ LAYERS.retain(|layer| layer.gpu.id() != gpu.id());
+ let mut active = ACTIVE.lock().unwrap_or_else(PoisonError::into_inner);
+ if std::ptr::eq(active.as_ptr(), Arc::as_ptr(&gpu.inner)) {
+ *active = Weak::new();
+ }
+}
+
+/// A texture of a frame, see [`wgpu_layer`].
+pub struct WgpuLayer {
+ gpu: SharedGpu,
+ texture: wgpu::Texture,
+ pixels: OnceLock<Option<Arc<usvgr::PreloadedImageData>>>,
+}
+
+impl WgpuLayer {
+ /// The [`SharedGpu::id`] of the device the texture lives on. A backend samples the
+ /// texture only on that device. On other devices it uses [`Self::pixels`].
+ pub fn gpu_id(&self) -> u64 {
+ self.gpu.id()
+ }
+
+ pub fn texture(&self) -> &wgpu::Texture {
+ &self.texture
+ }
+
+ /// The texture read back as premultiplied RGBA pixels, for a backend that cannot sample
+ /// it: another device, or a picture recording. This waits for the GPU.
+ pub fn pixels(&self) -> Option<Arc<usvgr::PreloadedImageData>> {
+ self.pixels.get_or_init(|| self.read_back()).clone()
+ }
+
+ fn read_back(&self) -> Option<Arc<usvgr::PreloadedImageData>> {
+ let (width, height) = (self.texture.width(), self.texture.height());
+ let row = width * 4;
+ let padded = row.next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT);
+ let device = self.gpu.device();
+ let buffer = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("fframes wgpu layer readback"),
+ size: u64::from(padded) * u64::from(height),
+ usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
+ encoder.copy_texture_to_buffer(
+ self.texture.as_image_copy(),
+ wgpu::TexelCopyBufferInfo {
+ buffer: &buffer,
+ layout: wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(padded),
+ rows_per_image: Some(height),
+ },
+ },
+ self.texture.size(),
+ );
+ finish_wgpu_layer(&mut encoder, &self.texture);
+ let submission = self.gpu.submit([encoder.finish()]);
+ let slice = buffer.slice(..);
+ let (sender, receiver) = std::sync::mpsc::channel();
+ slice.map_async(wgpu::MapMode::Read, move |result| {
+ let _ = sender.send(result);
+ });
+ device
+ .poll(wgpu::PollType::Wait {
+ submission_index: Some(submission),
+ timeout: None,
+ })
+ .ok()?;
+ receiver.recv().ok()?.ok()?;
+ let mapped = slice.get_mapped_range().ok()?;
+ let rgba: Vec<u8> = mapped
+ .chunks(padded as usize)
+ .flat_map(|line| &line[..row as usize])
+ .copied()
+ .collect();
+ drop(mapped);
+ buffer.unmap();
+ Some(Arc::new(usvgr::PreloadedImageData {
+ data: std::borrow::Cow::Owned(rgba),
+ width,
+ height,
+ id: format!(
+ "fframes-wgpu-pixels:{}",
+ NEXT_PIXELS.fetch_add(1, Ordering::Relaxed)
+ ),
+ }))
+ }
+}
+
+impl std::fmt::Debug for WgpuLayer {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("WgpuLayer")
+ .field("gpu", &self.gpu.id())
+ .field("width", &self.texture.width())
+ .field("height", &self.texture.height())
+ .finish_non_exhaustive()
+ }
+}
diff --git a/fframes-native-player/src/presenter/mod.rs b/fframes-native-player/src/presenter/mod.rs
index 95ce3727..ece7f6c1 100644
--- a/fframes-native-player/src/presenter/mod.rs
+++ b/fframes-native-player/src/presenter/mod.rs
@@ -23,6 +23,12 @@ use crate::options::PlayerBackend;
trait WindowTarget {
fn is_gpu(&self) -> bool;
+ /// An empty cache for the canvas of this target. A target on a GPU that the backend
+ /// shares with wgpu samples the wgpu layers of the frames in place.
+ fn render_cache(&self) -> RenderCache {
+ RenderCache::new()
+ }
+
/// The window has a new size in physical pixels, neither is zero.
fn resize(&mut self, width: u32, height: u32) -> PlayerResult<()>;
@@ -65,7 +71,7 @@ impl Presenter {
);
let mut presenter = Self {
- render_cache: RenderCache::new(),
+ render_cache: target.render_cache(),
target,
window,
background: Color::from_argb(background.a, background.r, background.g, background.b),
diff --git a/fframes-native-player/src/presenter/vulkan.rs b/fframes-native-player/src/presenter/vulkan.rs
index 8785d3ea..73740b6a 100644
--- a/fframes-native-player/src/presenter/vulkan.rs
+++ b/fframes-native-player/src/presenter/vulkan.rs
@@ -2,6 +2,7 @@ use std::ffi::CStr;
use std::mem::ManuallyDrop;
use std::rc::Rc;
+use fframes_skia_renderer::render::RenderCache;
use fframes_skia_renderer::skia_safe::gpu::ganesh::vk::backend_render_targets;
use fframes_skia_renderer::skia_safe::gpu::{
self, DirectContext, FlushInfo, SurfaceOrigin, SyncCpu,
@@ -372,6 +373,10 @@ impl WindowTarget for VulkanTarget {
true
}
+ fn render_cache(&self) -> RenderCache {
+ RenderCache::new().for_backend(&self.backend)
+ }
+
fn resize(&mut self, width: u32, height: u32) -> PlayerResult<()> {
self.size = (width, height);
if let Some(swapchain) = self.swapchain.as_mut() {
diff --git a/fframes-skia-renderer/Cargo.toml b/fframes-skia-renderer/Cargo.toml
index 9ca5562c..013f3407 100644
--- a/fframes-skia-renderer/Cargo.toml
+++ b/fframes-skia-renderer/Cargo.toml
@@ -23,6 +23,8 @@ ash = { version = "0.38.0", optional = true }
metal-rs = { package = "metal", version = "0.32.0", optional = true }
uuid = "1.12.1"
foreign-types-shared = "0.3.1"
+# `vulkan-portability`: the Vulkan backend on macOS too (MoltenVK), where `vulkan` alone has none
+wgpu = { version = "30", optional = true, default-features = false, features = ["std", "parking_lot", "wgsl", "vulkan", "vulkan-portability", "metal", "dx12"] }
# Cargo merges these features into the skia-safe dependency above.
[target.'cfg(target_os = "macos")'.dependencies]
@@ -34,7 +36,8 @@ core-foundation = { version = "0.10", optional = true }
skia-safe = { version = "0.153.3", features = ["svg", "webp"] }
[dev-dependencies]
-fframes = { workspace = true, features = ["compile-time-svgtree"] }
+# `3d`: `tests/wgpu_layers.rs` draws a 3D frame through the shared GPU
+fframes = { workspace = true, features = ["compile-time-svgtree", "3d"] }
png = "0.17"
svgr.workspace = true
low-poly-art-example = { path = "../examples/low-poly-art" }
@@ -50,6 +53,9 @@ vulkan = ["gpu", "skia-safe/vulkan", "ash"]
vulkan-video = ["vulkan", "fframes/vulkan"]
# `--renderer skia-cpu|gpu` for `fframes::cli`, see `cli::SkiaRenderers`
cli = ["fframes/cli"]
+# Open the Vulkan device as a wgpu device as well (`fframes::shared_gpu`): textures rendered
+# with wgpu (`fframes::three_d`) are drawn into the frames on the GPU, without a readback.
+wgpu = ["vulkan", "fframes/wgpu", "dep:wgpu"]
d3d = ["skia-safe/d3d"]
gl = ["skia-safe/gl"]
x11 = ["skia-safe/x11"]
diff --git a/fframes-skia-renderer/src/backends/mod.rs b/fframes-skia-renderer/src/backends/mod.rs
index b982bd12..fb4a845c 100644
--- a/fframes-skia-renderer/src/backends/mod.rs
+++ b/fframes-skia-renderer/src/backends/mod.rs
@@ -4,6 +4,8 @@ pub mod metal;
pub mod vulkan;
#[cfg(feature = "vulkan")]
pub(crate) mod vulkan_readback;
+#[cfg(feature = "wgpu")]
+mod vulkan_wgpu;
use fframes::{EncoderInput, FFramesRendererError, FFramesRendererResult, VideoEncoderInfo};
use skia_safe::{Surface, gpu::DirectContext, surfaces};
@@ -54,6 +56,12 @@ pub struct SkiaContext {
}
pub trait SkiaBackend: Sync + Send {
+ /// The [`fframes::SharedGpu::id`] of the device this backend's contexts draw on, when
+ /// the backend shares it with wgpu: layers rendered on it are sampled in place.
+ fn shared_gpu_id(&self) -> Option<u64> {
+ None
+ }
+
fn create_skia_surface(&self) -> FFramesRendererResult<(Surface, Option<DirectContext>)>;
/// Like [`Self::create_skia_surface`], with what the context needs to share its GPU
diff --git a/fframes-skia-renderer/src/backends/vulkan.rs b/fframes-skia-renderer/src/backends/vulkan.rs
index 6bfd95df..1312b0ed 100644
--- a/fframes-skia-renderer/src/backends/vulkan.rs
+++ b/fframes-skia-renderer/src/backends/vulkan.rs
@@ -33,6 +33,9 @@ pub struct SkiaVulkanCtx {
/// ([`Self::new_shared_with_encoder`]). The device belongs to `FFmpeg` then.
#[cfg(feature = "vulkan-video")]
encoder_device: Option<fframes::AvBuffer>,
+ /// The device opened as a wgpu device, see [`Self::shared_gpu`].
+ #[cfg(feature = "wgpu")]
+ shared_gpu: Option<fframes::SharedGpu>,
}
struct ForeignDevice {
@@ -88,7 +91,7 @@ impl SkiaVulkanCtx {
extension_names.push(*name);
}
}
- let instance: Instance = {
+ let instance = {
let app_name = CString::new("fframes_skia_renderer").map_err(|e| {
FFramesRendererError::Skia(format!("Failed to create CString: {e}"))
})?;
@@ -123,11 +126,19 @@ impl SkiaVulkanCtx {
})?
};
- Self::new_with_device(entry, instance, physical_device, width, height)
+ Self::create(
+ entry,
+ instance,
+ physical_device,
+ width,
+ height,
+ Some((api_version, &extension_names)),
+ )
}
}
- /// Create vulkan context with a pointer to the specific device and queue
+ /// A context on a physical device of an instance you created. The device is not shared
+ /// with wgpu: the version and the extensions of `instance` are not known here.
pub fn new_with_device(
entry: Entry,
instance: Instance,
@@ -135,6 +146,21 @@ impl SkiaVulkanCtx {
width: usize,
height: usize,
) -> FFramesRendererResult<Self> {
+ Self::create(entry, instance, physical_device, width, height, None)
+ }
+
+ /// `instance_info` is the API version and the extensions of `instance`. wgpu needs them
+ /// to share the device.
+ fn create(
+ entry: Entry,
+ instance: Instance,
+ physical_device: vk::PhysicalDevice,
+ width: usize,
+ height: usize,
+ instance_info: Option<(u32, &[&'static std::ffi::CStr])>,
+ ) -> FFramesRendererResult<Self> {
+ #[cfg(not(feature = "wgpu"))]
+ let _ = instance_info;
unsafe {
let (queue_family_index, queue_count) = instance
.get_physical_device_queue_family_properties(physical_device)
@@ -151,35 +177,76 @@ impl SkiaVulkanCtx {
FFramesRendererError::Skia("Failed to find graphics queue family".to_string())
})?;
- let device = {
- let priorities = vec![1.0; queue_count as usize];
- let queue_info = [vk::DeviceQueueCreateInfo::default()
- .queue_family_index(queue_family_index)
- .queue_priorities(&priorities)];
-
- // TODO figure out if we need more required extensions
- let device_extension_names = [vk::KHR_SWAPCHAIN_NAME];
- let device_extension_ptrs: Vec<*const c_char> = device_extension_names
- .iter()
- .map(|name| name.as_ptr())
- .collect();
-
- let features = vk::PhysicalDeviceFeatures::default();
- let device_create_info = vk::DeviceCreateInfo::default()
- .queue_create_infos(&queue_info)
- .enabled_extension_names(&device_extension_ptrs)
- .enabled_features(&features);
-
- instance
- .create_device(physical_device, &device_create_info, None)
- .map_err(|e| {
- FFramesRendererError::Skia(format!("Failed to create device: {e}"))
- })?
+ // wgpu shares the device only if the device has the extensions and the
+ // features wgpu relies on, so they go into the device before it is created
+ #[cfg(feature = "wgpu")]
+ let mut interop = instance_info.and_then(|(api_version, extensions)| {
+ super::vulkan_wgpu::Interop::new(
+ &entry,
+ &instance,
+ api_version,
+ extensions,
+ physical_device,
+ )
+ .inspect_err(|e| eprintln!("fframes: wgpu can not share the GPU ({e})"))
+ .ok()
+ });
+ #[cfg(feature = "wgpu")]
+ let wgpu_extensions = interop
+ .as_ref()
+ .map(|interop| interop.extensions().to_vec())
+ .unwrap_or_default();
+ #[cfg(not(feature = "wgpu"))]
+ let wgpu_extensions: Vec<&'static std::ffi::CStr> = Vec::new();
+
+ let priorities = vec![1.0; queue_count as usize];
+ let queue_info = [vk::DeviceQueueCreateInfo::default()
+ .queue_family_index(queue_family_index)
+ .queue_priorities(&priorities)];
+ let mut device_extensions = vec![vk::KHR_SWAPCHAIN_NAME];
+ device_extensions.extend(
+ wgpu_extensions
+ .into_iter()
+ .filter(|name| *name != vk::KHR_SWAPCHAIN_NAME),
+ );
+ let device_extension_ptrs: Vec<*const c_char> =
+ device_extensions.iter().map(|name| name.as_ptr()).collect();
+ let features = vk::PhysicalDeviceFeatures::default();
+ let device_create_info = vk::DeviceCreateInfo::default()
+ .queue_create_infos(&queue_info)
+ .enabled_extension_names(&device_extension_ptrs)
+ .enabled_features(&features);
+ #[cfg(feature = "wgpu")]
+ let device_create_info = match interop.as_mut() {
+ Some(interop) => interop.add_to_device_create(device_create_info),
+ None => device_create_info,
};
+ let device = instance
+ .create_device(physical_device, &device_create_info, None)
+ .map_err(|e| FFramesRendererError::Skia(format!("Failed to create device: {e}")))?;
let queues: Vec<_> = (0..queue_count)
.map(|index| device.get_device_queue(queue_family_index, index))
.collect();
+ let queue_locks = queue_locks(&queues);
+
+ // the wgpu device renders on the first queue; a shared device keeps every Skia
+ // context on that queue, which orders layers before the frames that sample them.
+ // On success the device belongs to wgpu, see `Drop`
+ #[cfg(feature = "wgpu")]
+ let shared_gpu = interop.and_then(|interop| {
+ match interop.open(&device, &device_extensions, queue_family_index, 0) {
+ Ok((device, queue)) => {
+ let gpu = fframes::SharedGpu::new(device, queue, queue_locks[0].clone());
+ fframes::register_shared_gpu(&gpu);
+ Some(gpu)
+ }
+ Err(e) => {
+ eprintln!("fframes: wgpu can not share the GPU ({e})");
+ None
+ }
+ }
+ });
Ok(SkiaVulkanCtx {
entry,
@@ -187,7 +254,7 @@ impl SkiaVulkanCtx {
device,
physical_device,
queue_family_index,
- queue_locks: queue_locks(&queues),
+ queue_locks,
queues,
next_queue: std::sync::atomic::AtomicUsize::new(0),
width,
@@ -195,6 +262,8 @@ impl SkiaVulkanCtx {
foreign_device: None,
#[cfg(feature = "vulkan-video")]
encoder_device: None,
+ #[cfg(feature = "wgpu")]
+ shared_gpu,
})
}
}
@@ -286,6 +355,8 @@ impl SkiaVulkanCtx {
),
}),
encoder_device: Some(encoder_device),
+ #[cfg(feature = "wgpu")]
+ shared_gpu: None,
})
}
}
@@ -318,6 +389,13 @@ impl SkiaVulkanCtx {
self.queue_family_index
}
+ /// The device opened as a wgpu device (feature `wgpu`). It is also the
+ /// [`fframes::shared_gpu`]. `None` when wgpu cannot use the GPU.
+ #[cfg(feature = "wgpu")]
+ pub fn shared_gpu(&self) -> Option<&fframes::SharedGpu> {
+ self.shared_gpu.as_ref()
+ }
+
/// A new Skia context on the next queue of the device.
pub fn create_context(&self) -> FFramesRendererResult<VulkanContext> {
unsafe {
@@ -338,10 +416,16 @@ impl SkiaVulkanCtx {
}
};
+ // a device shared with wgpu uses the wgpu queue only, see `create`
+ let queues = match () {
+ #[cfg(feature = "wgpu")]
+ () if self.shared_gpu.is_some() => 1,
+ () => self.queues.len(),
+ };
let queue_index = self
.next_queue
.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
- % self.queues.len();
+ % queues;
let queue = self.queues[queue_index];
let queue_lock = self.queue_locks[queue_index].clone();
// The factory may destroy a partially initialized GPU context on failure.
@@ -412,6 +496,11 @@ impl SkiaVulkanCtx {
}
impl SkiaBackend for SkiaVulkanCtx {
+ #[cfg(feature = "wgpu")]
+ fn shared_gpu_id(&self) -> Option<u64> {
+ self.shared_gpu.as_ref().map(fframes::SharedGpu::id)
+ }
+
fn create_skia_surface(&self) -> FFramesRendererResult<(Surface, Option<DirectContext>)> {
let context = self.create_skia_context()?;
Ok((context.surface, context.gpu))
@@ -498,6 +587,28 @@ impl SkiaBackend for SkiaVulkanCtx {
impl Drop for SkiaVulkanCtx {
fn drop(&mut self) {
+ // A device shared with wgpu belongs to wgpu (`vulkan_wgpu::Interop::open`): it is
+ // destroyed with the last wgpu object, which may outlive this context
+ #[cfg(feature = "wgpu")]
+ if let Some(gpu) = self.shared_gpu.take() {
+ {
+ let _queues: Vec<_> = self
+ .queue_locks
+ .iter()
+ .map(|lock| {
+ lock.lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ })
+ .collect();
+ unsafe {
+ let _ = self.device.device_wait_idle();
+ }
+ }
+ fframes::release_wgpu_layers(&gpu);
+ let _ = gpu.device().poll(wgpu::PollType::wait_indefinitely());
+ return;
+ }
+
// a device shared with FFmpeg is destroyed with its last reference
#[cfg(feature = "vulkan-video")]
if self.encoder_device.is_some() {
diff --git a/fframes-skia-renderer/src/backends/vulkan_wgpu.rs b/fframes-skia-renderer/src/backends/vulkan_wgpu.rs
new file mode 100644
index 00000000..86f76ab9
--- /dev/null
+++ b/fframes-skia-renderer/src/backends/vulkan_wgpu.rs
@@ -0,0 +1,136 @@
+//! Opens the Vulkan device of a [`super::vulkan::SkiaVulkanCtx`] as a wgpu device too
+//! (feature `wgpu`). Skia then samples textures rendered with wgpu in place.
+//!
+//! wgpu needs the device created with the extensions and the features it relies on. The
+//! [`Interop`] finds them before the device exists and adds them to the device creation.
+
+use std::ffi::CStr;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, Ordering};
+
+use ash::vk;
+use wgpu::hal;
+use wgpu::hal::api::Vulkan;
+
+/// What wgpu needs from a device, found before the device exists.
+pub(super) struct Interop {
+ instance: hal::vulkan::Instance,
+ adapter: hal::ExposedAdapter<Vulkan>,
+ extensions: Vec<&'static CStr>,
+ features: hal::vulkan::PhysicalDeviceFeatures,
+}
+
+impl Interop {
+ /// # Safety
+ ///
+ /// `instance` must come from `entry` with `api_version` and `instance_extensions`. It
+ /// must outlive everything made from the result.
+ pub(super) unsafe fn new(
+ entry: &ash::Entry,
+ instance: &ash::Instance,
+ api_version: u32,
+ instance_extensions: &[&'static CStr],
+ physical_device: vk::PhysicalDevice,
+ ) -> Result<Self, String> {
+ let instance = unsafe {
+ hal::vulkan::Instance::from_raw(
+ entry.clone(),
+ instance.clone(),
+ api_version,
+ 0,
+ None,
+ instance_extensions.to_vec(),
+ wgpu::InstanceFlags::empty(),
+ wgpu::MemoryBudgetThresholds::default(),
+ false,
+ // the instance belongs to the Skia context
+ Some(Box::new(|| ())),
+ )
+ }
+ .map_err(|e| e.to_string())?;
+ let adapter = instance
+ .expose_adapter(physical_device)
+ .ok_or_else(|| "wgpu does not support this GPU".to_owned())?;
+ let extensions = adapter
+ .adapter
+ .required_device_extensions(wgpu::Features::empty());
+ let features = adapter
+ .adapter
+ .physical_device_features(&extensions, wgpu::Features::empty());
+ Ok(Self {
+ instance,
+ adapter,
+ extensions,
+ features,
+ })
+ }
+
+ /// The device extensions wgpu relies on.
+ pub(super) fn extensions(&self) -> &[&'static CStr] {
+ &self.extensions
+ }
+
+ /// Adds the features wgpu relies on to the device creation.
+ pub(super) fn add_to_device_create<'a>(
+ &'a mut self,
+ info: vk::DeviceCreateInfo<'a>,
+ ) -> vk::DeviceCreateInfo<'a> {
+ self.features.add_to_device_create(info)
+ }
+
+ /// The wgpu device on queue `queue_index` of `family_index` of `device`.
+ ///
+ /// On success the wgpu device owns `device`: the last wgpu object that refers to it
+ /// destroys it, so no wgpu object outlives it. On failure the caller keeps it.
+ ///
+ /// # Safety
+ ///
+ /// `device` must come from the physical device of [`Self::new`], created with
+ /// [`Self::add_to_device_create`] and `extensions` (a superset of [`Self::extensions`]).
+ /// The caller must not destroy it after a success.
+ pub(super) unsafe fn open(
+ self,
+ device: &ash::Device,
+ extensions: &[&'static CStr],
+ family_index: u32,
+ queue_index: u32,
+ ) -> Result<(wgpu::Device, wgpu::Queue), String> {
+ // the device becomes wgpu's only when the wgpu device exists, see below
+ let owned = Arc::new(AtomicBool::new(false));
+ let destroy = {
+ let (owned, device) = (Arc::clone(&owned), device.clone());
+ move || {
+ if owned.load(Ordering::Acquire) {
+ unsafe { device.destroy_device(None) };
+ }
+ }
+ };
+ let open = unsafe {
+ self.adapter.adapter.device_from_raw(
+ device.clone(),
+ Some(Box::new(destroy)),
+ extensions,
+ wgpu::Features::empty(),
+ &wgpu::Limits::default(),
+ &wgpu::MemoryHints::Performance,
+ family_index,
+ queue_index,
+ )
+ }
+ .map_err(|e| e.to_string())?;
+ let instance = unsafe { wgpu::Instance::from_hal::<Vulkan>(self.instance) };
+ let adapter = unsafe { instance.create_adapter_from_hal(self.adapter) };
+ let shared = unsafe {
+ adapter.create_device_from_hal(
+ open,
+ &wgpu::DeviceDescriptor {
+ label: Some("fframes shared"),
+ ..Default::default()
+ },
+ )
+ }
+ .map_err(|e| e.to_string())?;
+ owned.store(true, Ordering::Release);
+ Ok(shared)
+ }
+}
diff --git a/fframes-skia-renderer/src/frame_export/mod.rs b/fframes-skia-renderer/src/frame_export/mod.rs
index 0a796e80..c805da31 100644
--- a/fframes-skia-renderer/src/frame_export/mod.rs
+++ b/fframes-skia-renderer/src/frame_export/mod.rs
@@ -272,7 +272,7 @@ impl<'b> SkiaEncoderFrameRenderer<'b> {
Ok(Self {
target: Some(target),
- render_cache: crate::render::RenderCache::new(),
+ render_cache: crate::render::RenderCache::new().for_backend(backend),
converter: None,
input: input.clone(),
width,
@@ -285,7 +285,7 @@ impl<'b> SkiaEncoderFrameRenderer<'b> {
/// Uses these cache limits and clears previously cached render resources.
pub fn with_cache_config(mut self, config: crate::SkiaCacheConfig) -> Self {
- self.render_cache = crate::render::RenderCache::with_config(config);
+ self.render_cache = self.render_cache.cleared(config);
self
}
diff --git a/fframes-skia-renderer/src/frame_renderer.rs b/fframes-skia-renderer/src/frame_renderer.rs
index 78731357..92b7b726 100644
--- a/fframes-skia-renderer/src/frame_renderer.rs
+++ b/fframes-skia-renderer/src/frame_renderer.rs
@@ -85,7 +85,7 @@ impl<TBackend: SkiaBackend> SkiaFrameRenderer<'_, TBackend> {
}) = self.surface.take()
{
// what lives on the context goes first
- self.render_cache = crate::render::RenderCache::with_config(self.cache_config);
+ self.render_cache = self.render_cache.cleared(self.cache_config);
drop(surface);
let _queue = lock_queue(queue_lock.as_ref());
drop(gpu);
@@ -107,14 +107,14 @@ impl<'a, TBackend: SkiaBackend> SkiaFrameRenderer<'a, TBackend> {
backend,
cache_config: crate::SkiaCacheConfig::default(),
surface: None,
- render_cache: crate::render::RenderCache::new(),
+ render_cache: crate::render::RenderCache::new().for_backend(backend),
}
}
/// Uses these cache limits for subsequent frames. Clears previously cached render resources.
pub fn with_cache_config(mut self, config: crate::SkiaCacheConfig) -> Self {
self.cache_config = config;
- self.render_cache = crate::render::RenderCache::with_config(config);
+ self.render_cache = self.render_cache.cleared(config);
self
}
}
diff --git a/fframes-skia-renderer/src/instant_rendering.rs b/fframes-skia-renderer/src/instant_rendering.rs
index f9e7e944..778f719f 100644
--- a/fframes-skia-renderer/src/instant_rendering.rs
+++ b/fframes-skia-renderer/src/instant_rendering.rs
@@ -4,6 +4,7 @@ use fframes::{
MediaProvider, TextCache, TimeBase, Video, VideoDecodersWorker, usvgr,
};
use skia_safe::Surface;
+use std::mem::ManuallyDrop;
/// Creates a new GPU context that can be used for instant rendering.
/// Recommended for use with externally provided textures to minimize the copying overhead.
@@ -11,51 +12,71 @@ use skia_safe::Surface;
/// Each `InstantRenderingGPUBackend` owns its own render caches, so multiple backends can
/// render frames concurrently without contention.
pub struct InstantRenderingGPUBackend<TBackend: SkiaBackend> {
+ render_cache: crate::render::RenderCache,
+ converter_cache: usvgr::Cache,
+ // Skia submits when these go, so `Drop` drops them under the queue lock
+ surface: ManuallyDrop<Surface>,
+ gpu_context: ManuallyDrop<skia_safe::gpu::DirectContext>,
+ /// Held around every call that reaches the queue, see [`crate::SkiaContext::queue_lock`].
+ queue_lock: Option<crate::QueueLock>,
+ // Last: the device of the backend outlives everything made on it.
#[allow(dead_code)] // this is required for lifetime in case of ffi usage
backend: TBackend,
- surface: Surface,
- gpu_context: skia_safe::gpu::DirectContext,
- converter_cache: usvgr::Cache,
- render_cache: crate::render::RenderCache,
}
impl<TBackend: SkiaBackend> InstantRenderingGPUBackend<TBackend> {
pub fn new(backend: TBackend) -> FFramesRendererResult<Self> {
- let (surface, gpu_context) = backend.create_skia_surface()?;
+ let context = backend.create_skia_context()?;
- let gpu_context = gpu_context.ok_or_else(|| {
+ let gpu_context = context.gpu.ok_or_else(|| {
FFramesRendererError::Skia(
"Instant Rendering is only available for gpu renderers".to_string(),
)
})?;
Ok(Self {
- backend,
- surface,
- gpu_context,
+ render_cache: crate::render::RenderCache::new().for_backend(&backend),
converter_cache: usvgr::Cache::default(),
- render_cache: crate::render::RenderCache::new(),
+ surface: ManuallyDrop::new(context.surface),
+ gpu_context: ManuallyDrop::new(gpu_context),
+ queue_lock: context.queue_lock,
+ backend,
})
}
/// Applies cache limits to instant rendering and clears cached resources.
pub fn with_cache_config(mut self, config: crate::SkiaCacheConfig) -> Self {
self.converter_cache = usvgr::Cache::new_with_text_cache(config.text_capacity);
- self.render_cache = crate::render::RenderCache::with_config(config);
+ self.render_cache = self.render_cache.cleared(config);
self
}
+ /// Renders into `surface` of `gpu_context`. They must submit to a queue that nothing
+ /// else uses at the same time.
pub fn new_from_existing_texture(
backend: TBackend,
surface: Surface,
gpu_context: skia_safe::gpu::DirectContext,
) -> Self {
Self {
- backend,
- surface,
- gpu_context,
+ render_cache: crate::render::RenderCache::new().for_backend(&backend),
converter_cache: usvgr::Cache::default(),
- render_cache: crate::render::RenderCache::new(),
+ surface: ManuallyDrop::new(surface),
+ gpu_context: ManuallyDrop::new(gpu_context),
+ queue_lock: None,
+ backend,
+ }
+ }
+}
+
+impl<TBackend: SkiaBackend> Drop for InstantRenderingGPUBackend<TBackend> {
+ fn drop(&mut self) {
+ let _queue = crate::lock_queue(self.queue_lock.as_ref());
+ self.render_cache = crate::render::RenderCache::new();
+ // SAFETY: dropped once, here; the fields are not used after this
+ unsafe {
+ ManuallyDrop::drop(&mut self.surface);
+ ManuallyDrop::drop(&mut self.gpu_context);
}
}
}
@@ -164,6 +185,7 @@ impl<TBackend: SkiaBackend> SkiaFFramesRenderer<'_, TBackend> {
native_ctx.surface.canvas(),
&mut native_ctx.render_cache,
);
+ let _queue = crate::lock_queue(native_ctx.queue_lock.as_ref());
native_ctx.gpu_context.flush_and_submit();
Ok(frame_index < fframes_ctx.runtime.timeline.duration_in_frames - 1)
diff --git a/fframes-skia-renderer/src/render/mod.rs b/fframes-skia-renderer/src/render/mod.rs
index 7b7b80a7..2cabeb88 100644
--- a/fframes-skia-renderer/src/render/mod.rs
+++ b/fframes-skia-renderer/src/render/mod.rs
@@ -14,6 +14,8 @@ mod image;
mod occlusion;
mod resources;
mod shader;
+#[cfg(feature = "wgpu")]
+mod wgpu_layer;
pub use shader::compile_shader;
@@ -157,6 +159,10 @@ pub struct RenderCache {
/// `static_hash` → whether the static subtree contains filters, such subtrees are
/// not recorded as pictures so the filtered groups inside can be rasterized.
static_has_filters: AHashMap<u64, bool>,
+ /// The `fframes::SharedGpu` the context of this cache draws on: wgpu layers rendered
+ /// there are sampled in place, all others are read back.
+ #[cfg_attr(not(feature = "wgpu"), allow(dead_code))]
+ shared_gpu: Option<u64>,
}
struct FilteredLayer {
@@ -183,6 +189,21 @@ impl RenderCache {
}
}
+ /// Makes the cache one of a context of `backend`. wgpu layers on the backend's shared GPU
+ /// are then sampled in place, see [`crate::SkiaBackend::shared_gpu_id`].
+ pub fn for_backend<B: crate::SkiaBackend + ?Sized>(mut self, backend: &B) -> Self {
+ self.shared_gpu = backend.shared_gpu_id();
+ self
+ }
+
+ /// An empty cache with `config` for the same context as this cache.
+ pub fn cleared(&self, config: crate::SkiaCacheConfig) -> Self {
+ Self {
+ shared_gpu: self.shared_gpu,
+ ..Self::with_config(config)
+ }
+ }
+
fn begin_frame(&mut self) {
self.paths.begin_frame();
self.geometry.begin_frame();
@@ -1127,11 +1148,34 @@ fn render_raster_image(
cache: &mut RenderCache,
alpha: f32,
) {
+ #[cfg(feature = "wgpu")]
+ if let Some(layer) = fframes::resolve_wgpu_layer(img) {
+ if let Some(image) = wgpu_layer::image(&layer, canvas, cache.shared_gpu) {
+ draw_raster_image(&image, view_box, rendering_mode, canvas, alpha);
+ } else if let Some(pixels) = layer.pixels()
+ && let Some(image) = SkiaImage::new(&pixels)
+ {
+ draw_raster_image(image.image(), view_box, rendering_mode, canvas, alpha);
+ }
+ return;
+ }
+
let Some(sk_image) = cache.image(img).map(SkiaImage::image) else {
return;
};
+ draw_raster_image(sk_image, view_box, rendering_mode, canvas, alpha);
+}
- let Some(img_size) = usvgr::Size::from_wh(img.width as f32, img.height as f32) else {
+/// Draws `sk_image` into the `view_box` of an `<image>` element.
+fn draw_raster_image(
+ sk_image: &skia_safe::Image,
+ view_box: usvgr::ViewBox,
+ rendering_mode: usvgr::ImageRendering,
+ canvas: &Canvas,
+ alpha: f32,
+) {
+ let (width, height) = (sk_image.width(), sk_image.height());
+ let Some(img_size) = usvgr::Size::from_wh(width as f32, height as f32) else {
return;
};
@@ -1180,7 +1224,7 @@ fn render_raster_image(
),
};
- let rect = skia_safe::Rect::from_wh(img.width as f32, img.height as f32);
+ let rect = skia_safe::Rect::from_wh(width as f32, height as f32);
canvas.draw_image_rect_with_sampling_options(
sk_image,
Some((&rect, skia_safe::canvas::SrcRectConstraint::Strict)),
diff --git a/fframes-skia-renderer/src/render/wgpu_layer.rs b/fframes-skia-renderer/src/render/wgpu_layer.rs
new file mode 100644
index 00000000..ac71d9d5
--- /dev/null
+++ b/fframes-skia-renderer/src/render/wgpu_layer.rs
@@ -0,0 +1,90 @@
+//! Textures of `fframes::wgpu_layer`s, sampled in place (feature `wgpu`).
+//!
+//! Skia borrows the texture in the sampled layout that wgpu left it in
+//! (`fframes::finish_wgpu_layer`), so Skia records no barrier. The transition at the end of
+//! the layer's submission orders the layer before every later submission on the queue.
+
+use ash::vk::{self, Handle};
+use skia_safe::gpu::{self, SurfaceOrigin, ganesh::vk::backend_textures};
+use skia_safe::{AlphaType, Canvas, ColorType, Image};
+
+/// The layer's texture as an image of the canvas's GPU context. `None` when the canvas
+/// records a picture, or does not draw on the layer's device (`shared_gpu` is the device
+/// of the context). Read the pixels back then.
+pub(super) fn image(
+ layer: &fframes::WgpuLayer,
+ canvas: &Canvas,
+ shared_gpu: Option<u64>,
+) -> Option<Image> {
+ if shared_gpu != Some(layer.gpu_id()) {
+ return None;
+ }
+ let mut context = canvas.recording_context()?;
+ let texture = layer.texture();
+ let raw = {
+ let hal = unsafe { texture.as_hal::<wgpu::hal::api::Vulkan>() }?;
+ unsafe { hal.raw_handle() }
+ };
+ let mut info = unsafe {
+ gpu::vk::ImageInfo::new(
+ raw.as_raw() as _,
+ gpu::vk::Alloc::default(),
+ gpu::vk::ImageTiling::OPTIMAL,
+ gpu::vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL,
+ gpu::vk::Format::R8G8B8A8_UNORM,
+ 1,
+ None,
+ None,
+ gpu::Protected::No,
+ None,
+ )
+ };
+ info.image_usage_flags = usage_flags(texture.usage()).as_raw();
+ info.sample_count = 1;
+ let backend_texture = unsafe {
+ backend_textures::make_vk(
+ (texture.width() as i32, texture.height() as i32),
+ &info,
+ "fframes wgpu layer",
+ )
+ };
+ gpu::images::borrow_texture_from(
+ &mut context,
+ &backend_texture,
+ SurfaceOrigin::TopLeft,
+ ColorType::RGBA8888,
+ AlphaType::Premul,
+ None,
+ )
+}
+
+fn usage_flags(usage: wgpu::TextureUsages) -> vk::ImageUsageFlags {
+ let mut flags = vk::ImageUsageFlags::empty();
+ for (from, to) in [
+ (
+ wgpu::TextureUsages::COPY_SRC,
+ vk::ImageUsageFlags::TRANSFER_SRC,
+ ),
+ (
+ wgpu::TextureUsages::COPY_DST,
+ vk::ImageUsageFlags::TRANSFER_DST,
+ ),
+ (
+ wgpu::TextureUsages::TEXTURE_BINDING,
+ vk::ImageUsageFlags::SAMPLED,
+ ),
+ (
+ wgpu::TextureUsages::STORAGE_BINDING,
+ vk::ImageUsageFlags::STORAGE,
+ ),
+ (
+ wgpu::TextureUsages::RENDER_ATTACHMENT,
+ vk::ImageUsageFlags::COLOR_ATTACHMENT,
+ ),
+ ] {
+ if usage.contains(from) {
+ flags |= to;
+ }
+ }
+ flags
+}
diff --git a/fframes-skia-renderer/tests/wgpu_layers.rs b/fframes-skia-renderer/tests/wgpu_layers.rs
new file mode 100644
index 00000000..c6f49166
--- /dev/null
+++ b/fframes-skia-renderer/tests/wgpu_layers.rs
@@ -0,0 +1,237 @@
+//! Skia draws textures rendered with wgpu on its own device in place.
+#![cfg(feature = "wgpu")]
+
+use fframes::{usvgr, wgpu};
+use fframes_skia_renderer::render::{RenderCache, render_tree};
+use fframes_skia_renderer::vulkan::SkiaVulkanCtx;
+use fframes_skia_renderer::{SkiaBackend, lock_queue};
+use skia_safe::{AlphaType, ColorType, ImageInfo};
+
+const SIZE: u32 = 64;
+
+/// `fframes::shared_gpu` is the GPU of the last Skia Vulkan context. The tests make one
+/// each, so they take turns.
+static SHARED_GPU: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
+fn take_turn() -> std::sync::MutexGuard<'static, ()> {
+ SHARED_GPU
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+}
+
+/// Clears the layer texture to `color` (premultiplied, as stored).
+fn fill(gpu: &fframes::SharedGpu, texture: &wgpu::Texture, color: [f64; 4]) {
+ let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
+ let mut encoder = gpu
+ .device()
+ .create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
+ encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: None,
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &view,
+ depth_slice: None,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color {
+ r: color[0],
+ g: color[1],
+ b: color[2],
+ a: color[3],
+ }),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ ..Default::default()
+ });
+ fframes::finish_wgpu_layer(&mut encoder, texture);
+ gpu.submit([encoder.finish()]);
+}
+
+/// Draws `layer` over white with `cache`. Returns the center pixel.
+fn draw(
+ ctx: &SkiaVulkanCtx,
+ layer: &fframes::media::ImageData<'static>,
+ cache: &mut RenderCache,
+) -> [u8; 4] {
+ let tree = fframes::svgr!(
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
+ <image href={layer.href()} x="0" y="0" width="64" height="64" />
+ </svg>
+ )
+ .into_svg_tree(
+ &usvgr::Options::default(),
+ &mut usvgr::Cache::default(),
+ &usvgr::fontdb::Database::new(),
+ )
+ .unwrap();
+ let mut context = ctx.create_skia_context().unwrap();
+ context.surface.canvas().clear(skia_safe::Color::WHITE);
+ render_tree(&tree, context.surface.canvas(), cache);
+ let info = ImageInfo::new(
+ (SIZE as i32, SIZE as i32),
+ ColorType::RGBA8888,
+ AlphaType::Premul,
+ None,
+ );
+ let mut pixels = vec![0u8; (SIZE * SIZE * 4) as usize];
+ {
+ let _queue = lock_queue(context.queue_lock.as_ref());
+ assert!(
+ context
+ .surface
+ .read_pixels(&info, &mut pixels, SIZE as usize * 4, (0, 0))
+ );
+ }
+ drop(tree);
+ let queue_lock = context.queue_lock.clone();
+ let _queue = lock_queue(queue_lock.as_ref());
+ drop(context);
+ let i = ((SIZE / 2 * SIZE + SIZE / 2) * 4) as usize;
+ [pixels[i], pixels[i + 1], pixels[i + 2], pixels[i + 3]]
+}
+
+fn assert_near(actual: [u8; 4], expected: [u8; 4]) {
+ let close = actual
+ .iter()
+ .zip(expected)
+ .all(|(a, e)| (i32::from(*a) - i32::from(e)).abs() <= 1);
+ assert!(close, "expected {expected:?}, got {actual:?}");
+}
+
+#[test]
+fn layers_are_sampled_in_place_and_reused() {
+ let _turn = take_turn();
+ let Ok(ctx) = SkiaVulkanCtx::new(SIZE as usize, SIZE as usize) else {
+ eprintln!("no Vulkan device, skipped");
+ return;
+ };
+ let gpu = ctx.shared_gpu().expect("wgpu opens the device").clone();
+ let texture = gpu.device().create_texture(&wgpu::TextureDescriptor {
+ label: Some("test layer"),
+ size: wgpu::Extent3d {
+ width: SIZE,
+ height: SIZE,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: fframes::WGPU_LAYER_FORMAT,
+ usage: fframes::WGPU_LAYER_USAGE | wgpu::TextureUsages::RENDER_ATTACHMENT,
+ view_formats: &[],
+ });
+ let mut cache = RenderCache::new().for_backend(&ctx);
+
+ // opaque orange, then the same texture with half transparent blue: Skia draws the
+ // last render, blended over white
+ fill(&gpu, &texture, [1.0, 0.5, 0.0, 1.0]);
+ let layer = fframes::wgpu_layer(&gpu, &texture);
+ assert_near(draw(&ctx, &layer, &mut cache), [255, 128, 0, 255]);
+ drop(layer);
+
+ fill(&gpu, &texture, [0.0, 0.0, 0.5, 0.5]);
+ let layer = fframes::wgpu_layer(&gpu, &texture);
+ assert_near(draw(&ctx, &layer, &mut cache), [128, 128, 255, 255]);
+
+ // a context on another device reads the texture back
+ assert_near(
+ draw(&ctx, &layer, &mut RenderCache::new()),
+ [128, 128, 255, 255],
+ );
+ drop(layer);
+
+ // an sRGB view changes the colors, and Skia needs the copy usages: not a layer
+ let wrong = gpu.device().create_texture(&wgpu::TextureDescriptor {
+ label: None,
+ size: wgpu::Extent3d {
+ width: SIZE,
+ height: SIZE,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8UnormSrgb,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING,
+ view_formats: &[],
+ });
+ let layer = fframes::wgpu_layer(&gpu, &wrong);
+ assert!(fframes::resolve_wgpu_layer(&layer.href()).is_none());
+
+ // the backends wrap and read back one 2D image: not a layer
+ let layered = gpu.device().create_texture(&wgpu::TextureDescriptor {
+ label: None,
+ size: wgpu::Extent3d {
+ width: SIZE,
+ height: SIZE,
+ depth_or_array_layers: 2,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: fframes::WGPU_LAYER_FORMAT,
+ usage: fframes::WGPU_LAYER_USAGE,
+ view_formats: &[],
+ });
+ let layer = fframes::wgpu_layer(&gpu, &layered);
+ assert!(fframes::resolve_wgpu_layer(&layer.href()).is_none());
+}
+
+/// The state of a type is made once, and its `init` can use the state of another type.
+#[test]
+fn state_is_made_once_and_can_use_other_state() {
+ struct Inner(u32);
+ struct Outer(u32);
+
+ let _turn = take_turn();
+ let Ok(ctx) = SkiaVulkanCtx::new(SIZE as usize, SIZE as usize) else {
+ eprintln!("no Vulkan device, skipped");
+ return;
+ };
+ let gpu = ctx.shared_gpu().expect("wgpu opens the device").clone();
+ let made = std::sync::atomic::AtomicUsize::new(0);
+ let outers: Vec<_> = std::thread::scope(|scope| {
+ let threads: Vec<_> = (0..8)
+ .map(|_| {
+ scope.spawn(|| {
+ gpu.state(|gpu| {
+ made.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ Outer(gpu.state(|_| Inner(7)).0 + 1)
+ })
+ })
+ })
+ .collect();
+ threads.into_iter().map(|t| t.join().unwrap()).collect()
+ });
+ assert_eq!(made.into_inner(), 1);
+ assert!(outers.iter().all(|outer| outer.0 == 8));
+}
+
+/// A `fframes_three_d` frame on the shared GPU is a layer, and Skia draws the same picture as the
+/// pixels that the renderer reads back.
+#[test]
+fn fframes_three_d_frames_are_layers() {
+ use fframes::three_d::{Background, Camera, Geometry, Material, Node, Renderer, Rgb, Scene};
+
+ let _turn = take_turn();
+ let Ok(ctx) = SkiaVulkanCtx::new(SIZE as usize, SIZE as usize) else {
+ eprintln!("no Vulkan device, skipped");
+ return;
+ };
+ assert!(ctx.shared_gpu().is_some(), "wgpu opens the device");
+ let mut scene = Scene::new().background(Background::Color(Rgb::from("#2040ff")));
+ scene.add(Node::mesh(
+ Geometry::cuboid(1.0, 1.0, 1.0),
+ Material::unlit("#ff8000"),
+ ));
+ let camera = Camera::perspective(40.0).at(0.0, 0.0, 4.0);
+ let renderer = Renderer::new(SIZE, SIZE).gpu();
+
+ let layer = renderer.render(&scene, &camera);
+ assert!(fframes::resolve_wgpu_layer(&layer.href()).is_some());
+ let drawn = draw(&ctx, &layer, &mut RenderCache::new().for_backend(&ctx));
+ let expected = renderer.render_pixels(&scene, &camera);
+ let center = (SIZE / 2) as usize * SIZE as usize + (SIZE / 2) as usize;
+ let expected = expected.rgba.as_chunks::<4>().0[center];
+ assert_near(drawn, expected);
+}
diff --git a/fframes-three-d/Cargo.toml b/fframes-three-d/Cargo.toml
new file mode 100644
index 00000000..9f3384ad
--- /dev/null
+++ b/fframes-three-d/Cargo.toml
@@ -0,0 +1,41 @@
+[package]
+name = "fframes_three_d"
+version = "1.2.0"
+edition = "2024"
+authors = ["Dmitriy Kovalenko <[email protected]>"]
+license = "MIT"
+description = "3D scenes for fframes: a three.js style scene graph, glTF and STL models, a CPU rasterizer and a wgpu renderer"
+homepage = "https://fframes.studio"
+
+[lib]
+doctest = false
+
+[features]
+# Renders on the GPU with wgpu (Vulkan, Metal or DX12), see `Renderer::gpu`. Off by default.
+# The `3d` and `wgpu` features of fframes turn it on.
+gpu = ["dep:wgpu", "dep:pollster", "dep:bytemuck", "fframes-media/wgpu"]
+
+[dependencies]
+# Not fframes: fframes re-exports this crate as `fframes::three_d` (feature `3d`).
+fframes-media.workspace = true
+glam = "0.30"
+gltf = { version = "1.4", default-features = false, features = ["utils", "names", "KHR_materials_emissive_strength", "KHR_lights_punctual", "KHR_materials_unlit"] }
+image = { version = "0.25", default-features = false, features = ["png", "jpeg", "hdr", "webp"] }
+base64 = "0.22"
+# Runs on the current thread in wasm.
+rayon = "1.10"
+ttf-parser = "0.25.1"
+
+[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
+usvgr.workspace = true
+# The `gpu` feature only.
+wgpu = { version = "30", optional = true, default-features = false, features = ["std", "parking_lot", "wgsl", "vulkan", "metal", "dx12"] }
+pollster = { version = "1", optional = true }
+bytemuck = { version = "1", features = ["derive"], optional = true }
+
+[target.'cfg(target_arch = "wasm32")'.dependencies]
+# Encodes the images as PNG data URLs in the editor.
+png = "0.17"
+
+[lints]
+workspace = true
diff --git a/fframes-three-d/src/animation.rs b/fframes-three-d/src/animation.rs
new file mode 100644
index 00000000..69946387
--- /dev/null
+++ b/fframes-three-d/src/animation.rs
@@ -0,0 +1,212 @@
+use std::ops::{Add, Mul};
+
+use glam::{FloatExt, Quat, Vec3};
+
+use crate::{NodeId, Scene};
+
+/// How values change between keyframes, the glTF sampler interpolation.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Interpolation {
+ /// The value jumps at each keyframe.
+ Step,
+ /// A straight line between keyframes. Rotations use slerp.
+ Linear,
+ /// A Hermite spline. Each keyframe stores three values: in tangent, value, out tangent.
+ CubicSpline,
+}
+
+/// The keyframe values of one [`Channel`].
+#[derive(Debug, Clone)]
+pub enum Keyframes {
+ Translation(Vec<Vec3>),
+ Rotation(Vec<Quat>),
+ Scale(Vec<Vec3>),
+ /// Morph target weights, `targets` values for each keyframe.
+ Weights {
+ targets: usize,
+ values: Vec<f32>,
+ },
+}
+
+/// The animation of one property of one node.
+#[derive(Debug, Clone)]
+pub struct Channel {
+ /// The node id in the model, see [`ModelInstance`](crate::ModelInstance).
+ pub node: NodeId,
+ pub interpolation: Interpolation,
+ /// The keyframe times in seconds, in ascending order.
+ pub times: Vec<f32>,
+ pub keyframes: Keyframes,
+}
+
+/// A keyframe animation, three.js `AnimationClip`. [`Model`](crate::Model) loads clips from
+/// glTF.
+#[derive(Debug, Clone)]
+pub struct AnimationClip {
+ pub name: String,
+ /// The length in seconds.
+ pub duration: f32,
+ pub channels: Vec<Channel>,
+}
+
+impl AnimationClip {
+ /// Poses the nodes at `time` seconds, clamped to the clip.
+ ///
+ /// `weight` blends the pose over the current pose: 1 replaces it. `offset` is added to
+ /// each node id, see [`ModelInstance::offset`](crate::ModelInstance::offset). To
+ /// crossfade two clips, apply the first with weight 1 and the second with the progress
+ /// of the crossfade.
+ pub fn apply(&self, scene: &mut Scene, offset: u32, time: f32, weight: f32) {
+ let time = time.clamp(0.0, self.duration.max(0.0));
+ for channel in &self.channels {
+ let id = NodeId(channel.node.0 + offset);
+ let Some(key) = Key::locate(&channel.times, time, channel.interpolation) else {
+ continue;
+ };
+ if let Keyframes::Weights { targets, values } = &channel.keyframes {
+ let weights: Vec<Option<f32>> = (0..*targets)
+ .map(|target| {
+ key.sample(|i| values.get(i * targets + target).copied(), f32::lerp)
+ })
+ .collect();
+ set_weights(scene, id, &weights, weight);
+ continue;
+ }
+ let Some(node) = scene.get_mut(id) else {
+ continue;
+ };
+ match &channel.keyframes {
+ Keyframes::Translation(values) => {
+ if let Some(v) = key.sample(|i| values.get(i).copied(), Vec3::lerp) {
+ node.position = node.position.lerp(v, weight);
+ }
+ }
+ Keyframes::Scale(values) => {
+ if let Some(v) = key.sample(|i| values.get(i).copied(), Vec3::lerp) {
+ node.scale = node.scale.lerp(v, weight);
+ }
+ }
+ Keyframes::Rotation(values) => {
+ if let Some(q) = key.sample(|i| values.get(i).copied(), Quat::slerp) {
+ node.rotation = node.rotation.slerp(q.normalize(), weight).normalize();
+ }
+ }
+ Keyframes::Weights { .. } => {}
+ }
+ }
+ }
+
+ /// [`AnimationClip::apply`] with the time wrapped around the clip.
+ pub fn apply_looped(&self, scene: &mut Scene, offset: u32, time: f32, weight: f32) {
+ let time = if self.duration > 0.0 {
+ time.rem_euclid(self.duration)
+ } else {
+ 0.0
+ };
+ self.apply(scene, offset, time, weight);
+ }
+}
+
+/// Blends `weights` with `weight` into the morph weights of the mesh `id`. A glTF node with
+/// several primitives is a group with a mesh child for each, and they all get them.
+fn set_weights(scene: &mut Scene, id: NodeId, weights: &[Option<f32>], weight: f32) {
+ let Some(node) = scene.get(id) else {
+ return;
+ };
+ let meshes: Vec<NodeId> = if node.as_mesh().is_some() {
+ vec![id]
+ } else {
+ (node.children().iter().copied())
+ .filter(|&child| scene[child].as_mesh().is_some())
+ .collect()
+ };
+ for mesh in meshes {
+ let Some(mesh) = scene[mesh].mesh_mut() else {
+ continue;
+ };
+ mesh.morph_weights.resize(weights.len(), 0.0);
+ for (out, value) in mesh.morph_weights.iter_mut().zip(weights) {
+ if let Some(value) = value {
+ *out += (value - *out) * weight;
+ }
+ }
+ }
+}
+
+/// The place of a time between two keyframes of a channel.
+struct Key {
+ interpolation: Interpolation,
+ /// The keyframe at or before the time.
+ index: usize,
+ /// The progress to the next keyframe, `0..1`. It is 0 before the first and after the
+ /// last keyframe.
+ t: f32,
+ /// The time between the two keyframes in seconds.
+ dt: f32,
+}
+
+impl Key {
+ /// Finds the keyframes around `time`. `None` for a channel without keyframes.
+ fn locate(times: &[f32], time: f32, interpolation: Interpolation) -> Option<Self> {
+ let last = times.len().checked_sub(1)?;
+ let next = times.partition_point(|&t| t <= time);
+ let (index, t, dt) = if next == 0 || next > last {
+ // Before the first and after the last keyframe, the value does not change.
+ (next.min(last), 0.0, 0.0)
+ } else {
+ let dt = times[next] - times[next - 1];
+ let t = if dt > 0.0 {
+ (time - times[next - 1]) / dt
+ } else {
+ 0.0
+ };
+ (next - 1, t, dt)
+ };
+ Some(Self {
+ interpolation,
+ index,
+ t,
+ dt,
+ })
+ }
+
+ /// The value at this key. `get(i)` reads the stored value `i` of the channel, and `mix`
+ /// interpolates in a straight line (lerp or slerp).
+ fn sample<T>(&self, get: impl Fn(usize) -> Option<T>, mix: fn(T, T, f32) -> T) -> Option<T>
+ where
+ T: Copy + Mul<f32, Output = T> + Add<Output = T>,
+ {
+ let (k, t, dt) = (self.index, self.t, self.dt);
+ match self.interpolation {
+ Interpolation::Step => get(k),
+ Interpolation::Linear => {
+ let a = get(k)?;
+ Some(mix(a, get(k + 1).unwrap_or(a), t))
+ }
+ Interpolation::CubicSpline => {
+ // The values are triplets: in tangent, value, out tangent.
+ let v0 = get(k * 3 + 1)?;
+ match (get(k * 3 + 2), get(k * 3 + 4), get(k * 3 + 3)) {
+ (Some(out0), Some(v1), Some(in1)) => {
+ Some(hermite(v0, out0 * dt, v1, in1 * dt, t))
+ }
+ _ => Some(v0),
+ }
+ }
+ }
+ }
+}
+
+/// The cubic Hermite spline from `v0` with tangent `m0` to `v1` with tangent `m1`, at `t`
+/// in `0..1`.
+fn hermite<T>(v0: T, m0: T, v1: T, m1: T, t: f32) -> T
+where
+ T: Mul<f32, Output = T> + Add<Output = T>,
+{
+ let t2 = t * t;
+ let t3 = t2 * t;
+ v0 * (2.0 * t3 - 3.0 * t2 + 1.0)
+ + m0 * (t3 - 2.0 * t2 + t)
+ + v1 * (-2.0 * t3 + 3.0 * t2)
+ + m1 * (t3 - t2)
+}
diff --git a/fframes-three-d/src/camera.rs b/fframes-three-d/src/camera.rs
new file mode 100644
index 00000000..8782af7e
--- /dev/null
+++ b/fframes-three-d/src/camera.rs
@@ -0,0 +1,219 @@
+use glam::{Mat4, Quat, Vec2, Vec3};
+
+use crate::math::deg;
+
+/// A perspective or orthographic camera, three.js `PerspectiveCamera` with `lookAt`.
+///
+/// A camera is a plain value. Build a new one for each frame:
+///
+/// ```rust
+/// use fframes::three_d::{Camera, vec3};
+///
+/// let t = 1.5;
+/// let camera = Camera::perspective(35.0).orbit(vec3(0.0, 1.0, 0.0), 6.0, 30.0 + t * 20.0, 12.0);
+/// ```
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct Camera {
+ /// The position in meters.
+ pub position: Vec3,
+ /// The point that the camera looks at.
+ pub target: Vec3,
+ /// The up direction before roll. Default +Y.
+ pub up: Vec3,
+ /// The rotation around the view direction in radians.
+ pub roll: f32,
+ /// The vertical field of view in degrees.
+ pub fov: f32,
+ /// The distance of the near clip plane in meters. Default 0.05.
+ pub near: f32,
+ /// The distance of the far clip plane in meters. Default 500.
+ pub far: f32,
+ /// `Some(height)` makes the camera orthographic. It then shows `height` meters
+ /// vertically.
+ pub ortho_height: Option<f32>,
+ /// The image shift in normalized device units, as with a shift lens. `1.0` is half the
+ /// frame. It frames a subject off center without a turn of the camera.
+ pub shift: Vec2,
+ /// The depth of field. Default `None`: everything is sharp.
+ pub focus: Option<Focus>,
+}
+
+/// The depth of field: the distance that is sharp and the blur of everything else.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct Focus {
+ /// The distance from the camera that is sharp, in meters.
+ pub distance: f32,
+ /// The blur radius in pixels at 1080 lines, for things infinitely far behind the focus.
+ /// Things in front blur by `blur * (focus / depth - 1)`.
+ pub blur: f32,
+}
+
+impl Default for Camera {
+ fn default() -> Self {
+ Self::perspective(50.0)
+ }
+}
+
+impl Camera {
+ /// A perspective camera at `(0, 0, 5)` that looks at the origin. `fov_degrees` is the
+ /// vertical field of view.
+ pub fn perspective(fov_degrees: f32) -> Self {
+ Self {
+ position: Vec3::new(0.0, 0.0, 5.0),
+ target: Vec3::ZERO,
+ up: Vec3::Y,
+ roll: 0.0,
+ fov: fov_degrees,
+ near: 0.05,
+ far: 500.0,
+ ortho_height: None,
+ shift: Vec2::ZERO,
+ focus: None,
+ }
+ }
+
+ /// An orthographic camera at `(0, 0, 5)` that shows `height` meters vertically.
+ pub fn orthographic(height: f32) -> Self {
+ Self {
+ ortho_height: Some(height),
+ ..Self::default()
+ }
+ }
+
+ /// Sets the position in meters.
+ pub fn at(self, x: f32, y: f32, z: f32) -> Self {
+ self.position(Vec3::new(x, y, z))
+ }
+
+ /// Sets the position in meters.
+ pub fn position(mut self, position: Vec3) -> Self {
+ self.position = position;
+ self
+ }
+
+ /// Sets the point that the camera looks at.
+ pub fn look_at(mut self, target: Vec3) -> Self {
+ self.target = target;
+ self
+ }
+
+ /// Sets the vertical field of view in degrees.
+ pub fn fov(mut self, fov_degrees: f32) -> Self {
+ self.fov = fov_degrees;
+ self
+ }
+
+ /// Adds depth of field with the focus at `distance` meters.
+ ///
+ /// `blur` is the blur radius of the far background in pixels at 1080p. 6 is subtle, 16
+ /// looks like a macro lens.
+ pub fn focus(mut self, distance: f32, blur: f32) -> Self {
+ self.focus = Some(Focus { distance, blur });
+ self
+ }
+
+ /// Adds depth of field with the focus on `point`, see [`Camera::focus`].
+ pub fn focus_on(self, point: Vec3, blur: f32) -> Self {
+ let distance = (point - self.position).dot(self.forward()).max(0.05);
+ self.focus(distance, blur)
+ }
+
+ /// Sets the rotation around the view direction in radians.
+ pub fn roll(mut self, radians: f32) -> Self {
+ self.roll = radians;
+ self
+ }
+
+ /// Sets the distances of the near and far clip planes in meters.
+ pub fn clip(mut self, near: f32, far: f32) -> Self {
+ self.near = near;
+ self.far = far;
+ self
+ }
+
+ /// Puts the camera on a sphere around `target` and looks at the target.
+ ///
+ /// `distance` is the radius in meters. `azimuth` is the angle around Y in degrees: 0
+ /// looks from +Z, 90 from +X. `elevation` is the angle above the horizon in degrees.
+ pub fn orbit(mut self, target: Vec3, distance: f32, azimuth: f32, elevation: f32) -> Self {
+ let (az, el) = (deg(azimuth), deg(elevation));
+ self.target = target;
+ self.position =
+ target + Vec3::new(az.sin() * el.cos(), el.sin(), az.cos() * el.cos()) * distance;
+ self
+ }
+
+ /// The unit view direction.
+ pub fn forward(&self) -> Vec3 {
+ (self.target - self.position).normalize_or(Vec3::NEG_Z)
+ }
+
+ /// The unit direction to the right of the image.
+ pub fn right(&self) -> Vec3 {
+ self.forward().cross(self.up).normalize_or(Vec3::X)
+ }
+
+ /// The unit up direction of the image, after roll.
+ pub fn up_vector(&self) -> Vec3 {
+ let forward = self.forward();
+ let up = self.right().cross(forward);
+ Quat::from_axis_angle(forward, self.roll) * up
+ }
+
+ /// The transform from world space to camera space. A camera at its target looks down
+ /// -Z.
+ pub fn view_matrix(&self) -> Mat4 {
+ Mat4::look_to_rh(self.position, self.forward(), self.up_vector())
+ }
+
+ /// The projection for an image with the width to height ratio `aspect`.
+ pub fn projection_matrix(&self, aspect: f32) -> Mat4 {
+ let projection = match self.ortho_height {
+ Some(height) => {
+ let h = height * 0.5;
+ let w = h * aspect;
+ Mat4::orthographic_rh(-w, w, -h, h, self.near, self.far)
+ }
+ None => Mat4::perspective_rh(deg(self.fov), aspect, self.near, self.far),
+ };
+ if self.shift == Vec2::ZERO {
+ projection
+ } else {
+ Mat4::from_translation(self.shift.extend(0.0)) * projection
+ }
+ }
+
+ /// The transform from world space to clip space.
+ pub fn view_projection(&self, aspect: f32) -> Mat4 {
+ self.projection_matrix(aspect) * self.view_matrix()
+ }
+
+ /// The position of a world point on a `width` x `height` image.
+ ///
+ /// `x` and `y` are pixels, `z` is the distance in front of the camera in meters. `None`
+ /// when the point is behind the camera. Use it to put SVG labels, lines and particles
+ /// on 3D objects: `camera.project(scene.world_position(head), 1920.0, 1080.0)`.
+ pub fn project(&self, world: Vec3, width: f32, height: f32) -> Option<Vec3> {
+ let clip = self.view_projection(width / height) * world.extend(1.0);
+ if clip.w <= 1e-6 {
+ return None;
+ }
+ let ndc = clip / clip.w;
+ Some(Vec3::new(
+ (ndc.x * 0.5 + 0.5) * width,
+ (0.5 - ndc.y * 0.5) * height,
+ -(self.view_matrix() * world.extend(1.0)).z,
+ ))
+ }
+
+ /// The size in pixels of an object `world_size` meters across at `world`, on an image
+ /// `height` pixels high.
+ pub fn pixel_size(&self, world: Vec3, world_size: f32, height: f32) -> f32 {
+ if let Some(h) = self.ortho_height {
+ world_size / h * height
+ } else {
+ let depth = (self.view_matrix() * world.extend(1.0)).z.abs().max(1e-4);
+ world_size / (2.0 * depth * (deg(self.fov) * 0.5).tan()) * height
+ }
+ }
+}
diff --git a/fframes-three-d/src/color.rs b/fframes-three-d/src/color.rs
new file mode 100644
index 00000000..6995f5aa
--- /dev/null
+++ b/fframes-three-d/src/color.rs
@@ -0,0 +1,203 @@
+use std::ops::{Add, AddAssign, Mul};
+
+use glam::Vec3;
+
+/// A linear RGB color. Values above 1 are brighter than white. Emissive parts, lights and
+/// sparks use them, and bloom makes them glow.
+///
+/// Constructors that take 8-bit or hex values read them as sRGB and convert them to linear.
+/// three.js uses the same color management, so `0xff8800` looks the same in both.
+///
+/// ```rust
+/// use fframes::three_d::Rgb;
+///
+/// let orange = Rgb::hex(0xff8800);
+/// let also_orange: Rgb = "#ff8800".into();
+/// let hot = Rgb::hex(0x66ccff) * 8.0; // HDR, glows with bloom
+/// ```
+#[derive(Debug, Clone, Copy, PartialEq, Default)]
+pub struct Rgb(pub Vec3);
+
+impl Rgb {
+ pub const BLACK: Rgb = Rgb(Vec3::ZERO);
+ pub const WHITE: Rgb = Rgb(Vec3::ONE);
+
+ /// A color from linear components, without conversion.
+ pub const fn linear(r: f32, g: f32, b: f32) -> Self {
+ Rgb(Vec3::new(r, g, b))
+ }
+
+ /// A color from sRGB `0xRRGGBB`, like three.js `new Color(0xff8800)`.
+ pub fn hex(hex: u32) -> Self {
+ let [_, r, g, b] = hex.to_be_bytes();
+ Self::srgb8(r, g, b)
+ }
+
+ /// A color from 8-bit sRGB components.
+ pub fn srgb8(r: u8, g: u8, b: u8) -> Self {
+ Self::srgb(
+ f32::from(r) / 255.0,
+ f32::from(g) / 255.0,
+ f32::from(b) / 255.0,
+ )
+ }
+
+ /// A color from sRGB components in `0..1`.
+ pub fn srgb(r: f32, g: f32, b: f32) -> Self {
+ Rgb(Vec3::new(r, g, b).map(srgb_to_linear))
+ }
+
+ /// A color from sRGB hue in degrees, and saturation and lightness in `0..1`, like CSS
+ /// `hsl()`.
+ pub fn hsl(hue: f32, saturation: f32, lightness: f32) -> Self {
+ let h = hue.rem_euclid(360.0) / 60.0;
+ let c = (1.0 - (2.0 * lightness - 1.0).abs()) * saturation;
+ let x = c * (1.0 - (h % 2.0 - 1.0).abs());
+ let (r, g, b) = match h as u32 {
+ 0 => (c, x, 0.0),
+ 1 => (x, c, 0.0),
+ 2 => (0.0, c, x),
+ 3 => (0.0, x, c),
+ 4 => (x, 0.0, c),
+ _ => (c, 0.0, x),
+ };
+ let m = lightness - c / 2.0;
+ Self::srgb(r + m, g + m, b + m)
+ }
+
+ /// Parses an sRGB CSS color `#rgb` or `#rrggbb`. Returns black for other text.
+ pub fn parse(css: &str) -> Self {
+ let hex = css.trim().trim_start_matches('#');
+ match hex.len() {
+ 6 => u32::from_str_radix(hex, 16).map_or(Self::BLACK, Self::hex),
+ 3 => u32::from_str_radix(hex, 16).map_or(Self::BLACK, |v| {
+ // `#fa0` is `#ffaa00`: 17 * 0xf = 0xff.
+ let digit = |shift: u32| ((v >> shift) & 0xf) as u8 * 17;
+ Self::srgb8(digit(8), digit(4), digit(0))
+ }),
+ _ => Self::BLACK,
+ }
+ }
+
+ pub fn r(self) -> f32 {
+ self.0.x
+ }
+
+ pub fn g(self) -> f32 {
+ self.0.y
+ }
+
+ pub fn b(self) -> f32 {
+ self.0.z
+ }
+
+ /// Linear interpolation from `self` (at `t` = 0) to `other` (at `t` = 1).
+ pub fn lerp(self, other: Rgb, t: f32) -> Rgb {
+ Rgb(self.0.lerp(other.0, t))
+ }
+
+ /// Relative luminance of the linear color.
+ pub fn luminance(self) -> f32 {
+ self.0.dot(Vec3::new(0.2126, 0.7152, 0.0722))
+ }
+
+ /// The 8-bit sRGB components, clamped to `0..1`. `fframes::Color::from(rgb)` gives SVG
+ /// overlays the color of a material.
+ pub fn to_srgb8(self) -> [u8; 3] {
+ self.0
+ .clamp(Vec3::ZERO, Vec3::ONE)
+ .to_array()
+ .map(|c| (linear_to_srgb(c) * 255.0 + 0.5) as u8)
+ }
+}
+
+impl From<u32> for Rgb {
+ fn from(hex: u32) -> Self {
+ Rgb::hex(hex)
+ }
+}
+
+impl From<&str> for Rgb {
+ fn from(css: &str) -> Self {
+ Rgb::parse(css)
+ }
+}
+
+/// Linear components.
+impl From<[f32; 3]> for Rgb {
+ fn from(c: [f32; 3]) -> Self {
+ Rgb(Vec3::from(c))
+ }
+}
+
+/// Linear components.
+impl From<Vec3> for Rgb {
+ fn from(c: Vec3) -> Self {
+ Rgb(c)
+ }
+}
+
+impl Mul<f32> for Rgb {
+ type Output = Rgb;
+
+ fn mul(self, rhs: f32) -> Rgb {
+ Rgb(self.0 * rhs)
+ }
+}
+
+impl Mul<Rgb> for Rgb {
+ type Output = Rgb;
+
+ fn mul(self, rhs: Rgb) -> Rgb {
+ Rgb(self.0 * rhs.0)
+ }
+}
+
+impl Add for Rgb {
+ type Output = Rgb;
+
+ fn add(self, rhs: Rgb) -> Rgb {
+ Rgb(self.0 + rhs.0)
+ }
+}
+
+impl AddAssign for Rgb {
+ fn add_assign(&mut self, rhs: Rgb) {
+ self.0 += rhs.0;
+ }
+}
+
+/// Converts one sRGB component in `0..1` to linear.
+pub fn srgb_to_linear(c: f32) -> f32 {
+ if c <= 0.04045 {
+ c / 12.92
+ } else {
+ ((c + 0.055) / 1.055).powf(2.4)
+ }
+}
+
+/// Converts one linear component in `0..1` to sRGB.
+pub fn linear_to_srgb(c: f32) -> f32 {
+ if c <= 0.003_130_8 {
+ c * 12.92
+ } else {
+ 1.055 * c.powf(1.0 / 2.4) - 0.055
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn hex_and_css_agree() {
+ assert_eq!(Rgb::hex(0xff8800), Rgb::parse("#ff8800"));
+ assert_eq!(Rgb::hex(0xffaa00), Rgb::parse("#fa0"));
+ assert!((Rgb::hex(0x808080).r() - 0.2158).abs() < 1e-3);
+ }
+
+ #[test]
+ fn round_trips_through_srgb8() {
+ assert_eq!(Rgb::hex(0x3366cc).to_srgb8(), [0x33, 0x66, 0xcc]);
+ }
+}
diff --git a/fframes-three-d/src/environment.rs b/fframes-three-d/src/environment.rs
new file mode 100644
index 00000000..0ffb3e9a
--- /dev/null
+++ b/fframes-three-d/src/environment.rs
@@ -0,0 +1,499 @@
+use std::f32::consts::{FRAC_PI_2, PI, TAU};
+use std::hash::{DefaultHasher, Hash, Hasher};
+use std::sync::{Arc, Mutex, PoisonError};
+
+use glam::{Mat3, Vec2, Vec3, vec3};
+use rayon::prelude::*;
+
+use crate::Rgb;
+use crate::color::srgb_to_linear;
+use crate::math::smoothstep;
+
+/// The light that surrounds the scene, three.js `scene.environment`.
+///
+/// Metals reflect the environment, and it lights the shadows. Without it, metal looks black.
+#[derive(Debug, Clone, Default)]
+pub enum Environment {
+ /// No light from the environment. The default.
+ #[default]
+ None,
+ /// A procedural photo studio: a gradient backdrop with rectangular softboxes, like the
+ /// three.js `RoomEnvironment`. Metal shows clean highlights in it. Without softboxes it
+ /// is a plain sky to ground gradient.
+ Studio(Studio),
+ /// An equirectangular panorama (`.hdr`, `.jpg`, `.png`), three.js `RGBELoader` with
+ /// `EquirectangularReflectionMapping`.
+ Map {
+ map: Arc<EnvironmentMap>,
+ intensity: f32,
+ /// The rotation around Y in radians.
+ rotation: f32,
+ },
+}
+
+/// A procedural photo studio, see [`Environment::Studio`] and [`Environment::studio`].
+#[derive(Debug, Clone, PartialEq)]
+pub struct Studio {
+ /// The linear radiance of the backdrop straight up.
+ pub sky: Rgb,
+ /// The linear radiance of the backdrop at the horizon.
+ pub horizon: Rgb,
+ /// The linear radiance of the backdrop straight down.
+ pub ground: Rgb,
+ pub softboxes: Vec<SoftBox>,
+ /// The multiplier for all light of the studio. Default 1.
+ pub intensity: f32,
+ /// The rotation around Y in radians. Turn it to move the reflections over a surface.
+ pub rotation: f32,
+}
+
+/// A rectangular light in a [`Studio`], as seen from the center of the scene.
+#[derive(Debug, Clone, PartialEq)]
+pub struct SoftBox {
+ /// The unit direction from the scene to the center of the box.
+ pub direction: Vec3,
+ /// Half the width and half the height of the box, as angles in radians.
+ pub half_size: Vec2,
+ /// The linear radiance. It is usually well above 1.
+ pub color: Rgb,
+}
+
+impl SoftBox {
+ /// A box in `direction`, `width_degrees` wide and `height_degrees` high. The width runs
+ /// parallel to the horizon.
+ pub fn new(
+ direction: Vec3,
+ width_degrees: f32,
+ height_degrees: f32,
+ color: impl Into<Rgb>,
+ ) -> Self {
+ Self {
+ direction: direction.normalize_or(Vec3::Y),
+ half_size: Vec2::new(width_degrees, height_degrees).map(f32::to_radians) * 0.5,
+ color: color.into(),
+ }
+ }
+
+ /// The unit axes of the box: across its width and across its height.
+ pub(crate) fn axes(&self) -> (Vec3, Vec3) {
+ let u = self.direction.cross(Vec3::Y).normalize_or(Vec3::X);
+ (u, u.cross(self.direction))
+ }
+}
+
+impl Environment {
+ /// A neutral dark studio for products.
+ ///
+ /// It has four softboxes. A large key light is above at the front left, and a strip
+ /// light is on the right. A rim strip is behind, and a soft light is straight above.
+ pub fn studio() -> Self {
+ Environment::Studio(Studio {
+ sky: Rgb::linear(0.05, 0.055, 0.065),
+ horizon: Rgb::linear(0.12, 0.12, 0.13),
+ ground: Rgb::linear(0.02, 0.02, 0.022),
+ softboxes: vec![
+ SoftBox::new(
+ vec3(-0.6, 0.75, 0.6),
+ 50.0,
+ 30.0,
+ Rgb::linear(3.2, 3.2, 3.3),
+ ),
+ SoftBox::new(
+ vec3(1.0, 0.2, 0.15),
+ 14.0,
+ 70.0,
+ Rgb::linear(2.4, 2.45, 2.6),
+ ),
+ SoftBox::new(
+ vec3(-0.3, 0.35, -1.0),
+ 70.0,
+ 8.0,
+ Rgb::linear(1.8, 1.9, 2.1),
+ ),
+ SoftBox::new(Vec3::Y, 40.0, 40.0, Rgb::linear(0.9, 0.9, 0.95)),
+ ],
+ intensity: 1.0,
+ rotation: 0.0,
+ })
+ }
+
+ /// A panorama without rotation, see [`EnvironmentMap::decode`].
+ pub fn map(map: Arc<EnvironmentMap>, intensity: f32) -> Self {
+ Environment::Map {
+ map,
+ intensity,
+ rotation: 0.0,
+ }
+ }
+
+ /// Sets the brightness multiplier.
+ pub fn intensity(mut self, value: f32) -> Self {
+ match &mut self {
+ Environment::None => {}
+ Environment::Studio(Studio { intensity, .. }) | Environment::Map { intensity, .. } => {
+ *intensity = value;
+ }
+ }
+ self
+ }
+
+ /// Sets the rotation around Y in radians.
+ pub fn rotated(mut self, radians: f32) -> Self {
+ match &mut self {
+ Environment::Studio(Studio { rotation, .. }) | Environment::Map { rotation, .. } => {
+ *rotation = radians;
+ }
+ Environment::None => {}
+ }
+ self
+ }
+
+ /// The light that arrives from `dir`, blurred as a surface of `roughness` reflects it.
+ pub fn radiance(&self, dir: Vec3, roughness: f32) -> Vec3 {
+ match self {
+ Environment::None => Vec3::ZERO,
+ Environment::Studio(studio) => studio.radiance(dir, roughness),
+ Environment::Map {
+ map,
+ intensity,
+ rotation,
+ } => map.sample(rotate_y(dir, -*rotation), roughness) * *intensity,
+ }
+ }
+
+ /// The baked panorama of a studio, see [`Studio::baked`]. `None` for the other kinds: a
+ /// map is a panorama already.
+ pub(crate) fn baked(&self) -> Option<Arc<EnvironmentMap>> {
+ match self {
+ Environment::Studio(studio) => Some(studio.baked()),
+ _ => None,
+ }
+ }
+
+ /// The diffuse light on a surface that faces `normal`. It is the cosine weighted mean of
+ /// the incoming light, divided by π.
+ pub fn irradiance(&self, normal: Vec3) -> Vec3 {
+ match self {
+ Environment::None => Vec3::ZERO,
+ Environment::Studio(studio) => studio.irradiance(normal),
+ Environment::Map {
+ map,
+ intensity,
+ rotation,
+ } => map.irradiance(rotate_y(normal, -*rotation)) * *intensity,
+ }
+ }
+}
+
+/// Rotates `v` by `angle` radians around the Y axis.
+pub(crate) fn rotate_y(v: Vec3, angle: f32) -> Vec3 {
+ if angle == 0.0 {
+ v
+ } else {
+ Mat3::from_rotation_y(angle) * v
+ }
+}
+
+/// The color of a gradient for a unit direction with height `y`. A larger `softness` gives a
+/// wider blend at the horizon.
+fn gradient(y: f32, sky: Rgb, horizon: Rgb, ground: Rgb, softness: f32) -> Vec3 {
+ let width = 0.08 + softness * 0.6;
+ if y >= 0.0 {
+ horizon.0.lerp(sky.0, smoothstep(0.0, width + 0.35, y))
+ } else {
+ horizon.0.lerp(ground.0, smoothstep(0.0, width, -y))
+ }
+}
+
+/// Returns `true` when a direction is outside a softbox, where the mask of the box is 0.
+///
+/// `cos_angle` is the cosine of the angle to the center of the box. `a` and `b` are the half
+/// angles of the box plus its soft edge. The test is exact: tan²(angle) is
+/// tan²(across) + tan²(along), and tan² is convex. Thus beyond the angle √(a² + b²), one of
+/// the two angles is past its edge.
+fn outside_box(cos_angle: f32, a: f32, b: f32) -> bool {
+ a.max(b) < FRAC_PI_2 && cos_angle <= (a * a + b * b).sqrt().cos().max(0.0)
+}
+
+/// The number of levels of a baked [`Studio`]. Level `k` shows the studio through the
+/// roughness `(k / (BAKED_LEVELS - 1))²`, the level that [`EnvironmentMap::sample`] picks.
+const BAKED_LEVELS: usize = 8;
+/// The width of the first baked level in texels: 0.35° for each texel. The softest box edge
+/// is 0.86° wide.
+const BAKED_WIDTH: usize = 1024;
+
+/// The 8 most recent baked studios, keyed by `Studio::bake_key`.
+static BAKED: Mutex<Vec<(u64, Arc<EnvironmentMap>)>> = Mutex::new(Vec::new());
+
+impl Studio {
+ /// The light of the studio for all directions and roughness values, as a prefiltered
+ /// panorama.
+ ///
+ /// The first call for a distinct studio bakes the panorama. Later calls get it from a
+ /// cache. Rotation and intensity apply at sampling time, so they do not cause a new bake.
+ /// A reflection then costs one texture lookup instead of the softbox math. The panorama
+ /// matches [`Studio::radiance`] to within its texels.
+ pub(crate) fn baked(&self) -> Arc<EnvironmentMap> {
+ let key = self.bake_key();
+ let cached = || {
+ let cache = BAKED.lock().unwrap_or_else(PoisonError::into_inner);
+ let map = cache
+ .iter()
+ .find(|(k, _)| *k == key)
+ .map(|(_, map)| Arc::clone(map));
+ (cache, map)
+ };
+ if let (_, Some(map)) = cached() {
+ return map;
+ }
+ // The bake runs without the lock. It runs on rayon, and while a thread waits for
+ // its part of the bake, rayon can give it another render that needs the panorama.
+ // Threads that start at the same time can bake the same studio, the first map stays.
+ let map = Arc::new(self.bake());
+ let (mut cache, existing) = cached();
+ if let Some(existing) = existing {
+ return existing;
+ }
+ if cache.len() >= 8 {
+ cache.remove(0);
+ }
+ cache.push((key, Arc::clone(&map)));
+ map
+ }
+
+ /// A hash of the fields that change the bake. Rotation and intensity do not change it.
+ fn bake_key(&self) -> u64 {
+ let mut hasher = DefaultHasher::new();
+ let mut add = |values: &[f32]| values.iter().for_each(|v| v.to_bits().hash(&mut hasher));
+ for color in [self.sky, self.horizon, self.ground] {
+ add(&color.0.to_array());
+ }
+ for b in &self.softboxes {
+ add(&b.direction.to_array());
+ add(&b.half_size.to_array());
+ add(&b.color.0.to_array());
+ }
+ hasher.finish()
+ }
+
+ fn bake(&self) -> EnvironmentMap {
+ let plain = Studio {
+ rotation: 0.0,
+ intensity: 1.0,
+ ..self.clone()
+ };
+ let levels = (0..BAKED_LEVELS)
+ .map(|k| {
+ let width = BAKED_WIDTH >> k;
+ let height = width / 2;
+ let roughness = (k as f32 / (BAKED_LEVELS - 1) as f32).powi(2);
+ let mut data = vec![Vec3::ZERO; width * height];
+ data.par_chunks_mut(width).enumerate().for_each(|(y, row)| {
+ for (x, out) in row.iter_mut().enumerate() {
+ let uv = Vec2::new(
+ (x as f32 + 0.5) / width as f32,
+ (y as f32 + 0.5) / height as f32,
+ );
+ *out = plain.radiance(EnvironmentMap::dir(uv), roughness);
+ }
+ });
+ Level {
+ width,
+ height,
+ data,
+ }
+ })
+ .collect();
+ EnvironmentMap { levels }
+ }
+
+ /// The light that arrives from `dir`, blurred as a surface of `roughness` reflects it.
+ fn radiance(&self, dir: Vec3, roughness: f32) -> Vec3 {
+ let dir = rotate_y(dir, -self.rotation);
+ let blur = roughness * roughness * 1.4;
+ let soft = blur + 0.015;
+ let mut color = gradient(dir.y, self.sky, self.horizon, self.ground, blur);
+ for b in &self.softboxes {
+ let d = dir.dot(b.direction);
+ let half = b.half_size;
+ if d <= -0.2 || outside_box(d, half.x + soft, half.y + soft) {
+ continue;
+ }
+ let (u, v) = b.axes();
+ let inside =
+ |angle: f32, half: f32| 1.0 - smoothstep(half - soft * 0.5, half + soft, angle);
+ let mask = inside(dir.dot(u).atan2(d).abs(), half.x)
+ * inside(dir.dot(v).atan2(d).abs(), half.y);
+ if mask > 0.0 {
+ // The soft edge spreads the light over a larger area. This keeps the total
+ // energy of the box.
+ let energy = (half.x * half.y) / ((half.x + soft * 0.75) * (half.y + soft * 0.75));
+ color += b.color.0 * mask * energy;
+ }
+ }
+ color * self.intensity
+ }
+
+ /// The diffuse light on a surface that faces `normal`, see [`Environment::irradiance`].
+ fn irradiance(&self, normal: Vec3) -> Vec3 {
+ let normal = rotate_y(normal, -self.rotation);
+ let mut color = gradient(normal.y, self.sky, self.horizon, self.ground, 1.0);
+ for b in &self.softboxes {
+ let solid_angle = 4.0 * b.half_size.x.sin() * b.half_size.y.sin();
+ color += b.color.0 * (solid_angle * normal.dot(b.direction).max(0.0) / PI);
+ }
+ color * self.intensity
+ }
+}
+
+/// A prefiltered equirectangular panorama: a chain of levels, each one blurrier and half
+/// the size of the one before. Rough surfaces read the blurry levels.
+pub struct EnvironmentMap {
+ levels: Vec<Level>,
+}
+
+impl std::fmt::Debug for EnvironmentMap {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("EnvironmentMap")
+ .field("levels", &self.levels.len())
+ .finish()
+ }
+}
+
+/// One level of an [`EnvironmentMap`]: linear RGB texels, row by row from the top.
+struct Level {
+ width: usize,
+ height: usize,
+ data: Vec<Vec3>,
+}
+
+impl Level {
+ /// The bilinear sample at `uv`. U wraps around, v stops at the poles.
+ fn sample(&self, uv: Vec2) -> Vec3 {
+ let x = uv.x * self.width as f32 - 0.5;
+ let y = (uv.y * self.height as f32 - 0.5).clamp(0.0, self.height as f32 - 1.0);
+ let x0 = x.floor();
+ let y0 = y.floor();
+ let (fx, fy) = (x - x0, y - y0);
+ let xi = (x0 as i64).rem_euclid(self.width as i64) as usize;
+ let xi1 = (xi + 1) % self.width;
+ let yi = y0 as usize;
+ let yi1 = (yi + 1).min(self.height - 1);
+ let at = |x: usize, y: usize| self.data[y * self.width + x];
+ at(xi, yi)
+ .lerp(at(xi1, yi), fx)
+ .lerp(at(xi, yi1).lerp(at(xi1, yi1), fx), fy)
+ }
+
+ /// The level at half the size, filtered with a 4x4 tent.
+ fn downsample(&self) -> Level {
+ const TENT: [f32; 4] = [1.0, 3.0, 3.0, 1.0];
+ let width = (self.width / 2).max(2);
+ let height = (self.height / 2).max(1);
+ let mut data = vec![Vec3::ZERO; width * height];
+ for y in 0..height {
+ for x in 0..width {
+ let mut sum = Vec3::ZERO;
+ for (dy, wy) in (-1i64..=2).zip(TENT) {
+ for (dx, wx) in (-1i64..=2).zip(TENT) {
+ let sx = (x as i64 * 2 + dx).rem_euclid(self.width as i64) as usize;
+ let sy = (y as i64 * 2 + dy).clamp(0, self.height as i64 - 1) as usize;
+ sum += self.data[sy * self.width + sx] * (wx * wy);
+ }
+ }
+ // The 16 weights add up to 64.
+ data[y * width + x] = sum / 64.0;
+ }
+ }
+ Level {
+ width,
+ height,
+ data,
+ }
+ }
+}
+
+impl EnvironmentMap {
+ /// Decodes an equirectangular panorama. A Radiance `.hdr` file is linear, an 8-bit
+ /// image is sRGB.
+ pub fn decode(bytes: &[u8]) -> Result<Self, image::ImageError> {
+ let image = image::load_from_memory(bytes)?;
+ let is_float = matches!(
+ image,
+ image::DynamicImage::ImageRgb32F(_) | image::DynamicImage::ImageRgba32F(_)
+ );
+ let to_linear = |c: f32| if is_float { c } else { srgb_to_linear(c) };
+ let rgb = image.to_rgb32f();
+ let data = rgb
+ .pixels()
+ .map(|p| Vec3::from(p.0.map(to_linear)))
+ .collect();
+ Ok(Self::from_linear(
+ rgb.width() as usize,
+ rgb.height() as usize,
+ data,
+ ))
+ }
+
+ /// A panorama from linear RGB texels, row by row from the top. Levels wider than 1024
+ /// texels are halved until they fit. The smallest level is 8 texels wide or less.
+ pub fn from_linear(width: usize, height: usize, data: Vec<Vec3>) -> Self {
+ let mut level = Level {
+ width,
+ height,
+ data,
+ };
+ while level.width > 1024 {
+ level = level.downsample();
+ }
+ let mut levels = vec![level];
+ while let Some(last) = levels.last().filter(|l| l.width > 8) {
+ levels.push(last.downsample());
+ }
+ Self { levels }
+ }
+
+ /// The prefiltered levels as width, height and linear RGB texels, sharpest first.
+ #[cfg(all(feature = "gpu", not(target_arch = "wasm32")))]
+ pub(crate) fn levels(&self) -> impl Iterator<Item = (usize, usize, &[Vec3])> {
+ self.levels
+ .iter()
+ .map(|l| (l.width, l.height, l.data.as_slice()))
+ }
+
+ /// The panorama position of a direction.
+ fn uv(dir: Vec3) -> Vec2 {
+ let dir = dir.normalize_or(Vec3::Y);
+ Vec2::new(
+ dir.z.atan2(dir.x) / TAU + 0.5,
+ 0.5 - dir.y.clamp(-1.0, 1.0).asin() / PI,
+ )
+ }
+
+ /// The unit direction of a panorama position, the inverse of [`Self::uv`].
+ fn dir(uv: Vec2) -> Vec3 {
+ let azimuth = (uv.x - 0.5) * TAU;
+ let elevation = (0.5 - uv.y) * PI;
+ let (sin_e, cos_e) = elevation.sin_cos();
+ let (sin_a, cos_a) = azimuth.sin_cos();
+ Vec3::new(cos_e * cos_a, sin_e, cos_e * sin_a)
+ }
+
+ /// The light from `dir`, blurred as a surface of `roughness` reflects it. A mirror
+ /// reads level 0, a rough surface the smallest levels.
+ pub(crate) fn sample(&self, dir: Vec3, roughness: f32) -> Vec3 {
+ let uv = Self::uv(dir);
+ let last = self.levels.len() - 1;
+ let lod = (roughness.clamp(0.0, 1.0).sqrt() * last as f32).min(last as f32);
+ let l0 = lod.floor() as usize;
+ let l1 = (l0 + 1).min(last);
+ self.levels[l0]
+ .sample(uv)
+ .lerp(self.levels[l1].sample(uv), lod - l0 as f32)
+ }
+
+ /// The diffuse light on a surface that faces `normal`, from the smallest level.
+ fn irradiance(&self, normal: Vec3) -> Vec3 {
+ self.levels[self.levels.len() - 1].sample(Self::uv(normal))
+ }
+}
diff --git a/fframes-three-d/src/geometry.rs b/fframes-three-d/src/geometry.rs
new file mode 100644
index 00000000..17fb5566
--- /dev/null
+++ b/fframes-three-d/src/geometry.rs
@@ -0,0 +1,1908 @@
+use std::collections::HashMap;
+use std::f32::consts::{FRAC_PI_2, FRAC_PI_4, PI, TAU};
+
+use glam::{IVec2, IVec3, Mat3, Mat4, Quat, Vec2, Vec3, Vec4};
+
+use crate::Rgb;
+use crate::math::Aabb;
+
+/// Joint indices and weights of the skinned vertices, one entry per vertex. See
+/// [`Geometry::skin`].
+#[derive(Debug, Clone, Default)]
+pub struct SkinWeights {
+ pub joints: Vec<[u16; 4]>,
+ pub weights: Vec<[f32; 4]>,
+}
+
+/// One morph target (blend shape): position and normal offsets, one per vertex.
+#[derive(Debug, Clone, Default)]
+pub struct MorphTarget {
+ pub name: Option<String>,
+ pub positions: Vec<Vec3>,
+ pub normals: Vec<Vec3>,
+}
+
+/// Indexed triangles with vertex attributes, like three.js `BufferGeometry`.
+///
+/// Build a geometry once, in the video constructor, and share it. [`crate::Node::mesh`]
+/// keeps it in an `Arc<Geometry>`, so a scene clone in each frame does not copy vertices.
+///
+/// A triangle is counter-clockwise when you look at the side that its normal points to.
+/// All primitives have their center at the origin, as in three.js.
+#[derive(Debug, Clone, Default)]
+pub struct Geometry {
+ pub positions: Vec<Vec3>,
+ pub normals: Vec<Vec3>,
+ /// Texture coordinates: empty, or one per vertex.
+ pub uvs: Vec<Vec2>,
+ /// Linear RGBA colors: empty, or one per vertex. The material color multiplies them.
+ pub colors: Vec<Vec4>,
+ /// Three vertex indices for each triangle.
+ pub indices: Vec<u32>,
+ pub skin: Option<SkinWeights>,
+ pub morph_targets: Vec<MorphTarget>,
+ bounds: Aabb,
+}
+
+impl Geometry {
+ /// Makes a geometry from vertex buffers and triangle indices. When `normals` does not
+ /// have one normal per position (for example, when it is empty), this function
+ /// calculates smooth normals. Triangles with an index out of range are left out.
+ pub fn new(
+ positions: Vec<Vec3>,
+ normals: Vec<Vec3>,
+ uvs: Vec<Vec2>,
+ indices: Vec<u32>,
+ ) -> Self {
+ let count = positions.len();
+ let indices = indices
+ .as_chunks::<3>()
+ .0
+ .iter()
+ .filter(|t| t.iter().all(|&i| (i as usize) < count))
+ .flatten()
+ .copied()
+ .collect();
+ let mut geometry = Geometry {
+ positions,
+ normals,
+ uvs,
+ indices,
+ ..Default::default()
+ };
+ if geometry.normals.len() != geometry.positions.len() {
+ geometry.compute_vertex_normals();
+ }
+ geometry.update_bounds();
+ geometry
+ }
+
+ /// Makes a flat-shaded geometry from a triangle soup, where each three positions are
+ /// one triangle. The triangles share no vertices, and all UVs are zero.
+ pub fn from_triangles(positions: &[Vec3]) -> Self {
+ let mut b = Builder::default();
+ for &tri in positions.as_chunks::<3>().0 {
+ b.flat_triangle(tri, face_normal(tri).normalize_or_zero());
+ }
+ b.build()
+ }
+
+ /// Loads a binary or ASCII STL model, like three.js `STLLoader`.
+ ///
+ /// The result is flat shaded, with one vertex for each triangle corner and no UVs. STL
+ /// has only triangles. It has no materials, and its normals are not good enough to
+ /// keep. The [`crate::Material`] gives the finish, and [`Geometry::smooth`] rounds the
+ /// curved parts. When the winding of a triangle disagrees with its normal in the file,
+ /// the normal sets the front side.
+ ///
+ /// STL has no unit and no up axis. Most files use millimeters with Z up.
+ /// `.scale(0.001, 0.001, 0.001).rotate_x(-FRAC_PI_2)` changes them to meters with Y up.
+ pub fn from_stl(bytes: &[u8]) -> Result<Self, StlError> {
+ let triangles = match binary_stl(bytes) {
+ Some(triangles) => triangles,
+ None => ascii_stl(bytes)?,
+ };
+ let mut b = Builder::default();
+ for (normal, [p0, p1, p2]) in triangles {
+ let n = face_normal([p0, p1, p2]);
+ if !n.is_finite() || n.length_squared() < 1e-24 {
+ continue;
+ }
+ if normal.length_squared() > 1e-12 && n.dot(normal) < 0.0 {
+ b.flat_triangle([p0, p2, p1], -n.normalize());
+ } else {
+ b.flat_triangle([p0, p1, p2], n.normalize());
+ }
+ }
+ if b.positions.is_empty() {
+ return Err(StlError::Empty);
+ }
+ let mut geometry = b.build();
+ geometry.uvs.clear();
+ Ok(geometry)
+ }
+
+ /// Welds the vertices at the same position and smooths the normals, like three.js
+ /// `toCreasedNormals`. Only faces that meet at less than `crease_degrees` share a
+ /// normal, so sharp edges stay sharp. Vertices with different UVs stay apart, so
+ /// texture seams stay. Use it on triangle soups, for example from
+ /// [`Geometry::from_stl`] or [`Geometry::flat`]. The result has no skin and no morph
+ /// targets.
+ pub fn smooth(self, crease_degrees: f32) -> Self {
+ let cos_crease = crease_degrees.to_radians().cos();
+ let triangles: Vec<[u32; 3]> = self.triangles().collect();
+ // The length of a face normal is two times the face area. Large faces thus have
+ // more weight in the sums below.
+ let faces: Vec<Vec3> = triangles
+ .iter()
+ .map(|t| face_normal(t.map(|i| self.positions[i as usize])))
+ .collect();
+ // Positions that round to the same point on a 1e-5 grid are one position.
+ let key = |p: Vec3| (p * 1e5).round().as_ivec3();
+ let mut faces_at: HashMap<IVec3, Vec<usize>> = HashMap::new();
+ for (f, t) in triangles.iter().enumerate() {
+ for &i in t {
+ faces_at
+ .entry(key(self.positions[i as usize]))
+ .or_default()
+ .push(f);
+ }
+ }
+ // One vertex for each position, normal and UV.
+ let uv_key = |i: usize| {
+ self.uvs
+ .get(i)
+ .map_or(IVec2::ZERO, |uv| (*uv * 1e5).round().as_ivec2())
+ };
+ let mut welded: HashMap<(IVec3, IVec3, IVec2), u32> = HashMap::new();
+ let mut b = Builder::default();
+ for (t, face) in triangles.iter().zip(&faces) {
+ let own = face.normalize_or(Vec3::Y);
+ let [i0, i1, i2] = t.map(|i| {
+ let i = i as usize;
+ let position = key(self.positions[i]);
+ let n = faces_at[&position]
+ .iter()
+ .map(|&f| faces[f])
+ .filter(|other| other.normalize_or(Vec3::Y).dot(own) >= cos_crease)
+ .sum::<Vec3>()
+ .normalize_or(own);
+ *welded
+ .entry((position, key(n), uv_key(i)))
+ .or_insert_with(|| b.copy_vertex(&self, i, n))
+ });
+ b.tri(i0, i1, i2);
+ }
+ b.build()
+ }
+
+ /// The triangles whose indices are all in range.
+ fn triangles(&self) -> impl Iterator<Item = [u32; 3]> + '_ {
+ let count = self.positions.len();
+ self.indices
+ .as_chunks::<3>()
+ .0
+ .iter()
+ .copied()
+ .filter(move |t| t.iter().all(|&i| (i as usize) < count))
+ }
+
+ pub fn vertex_count(&self) -> usize {
+ self.positions.len()
+ }
+
+ pub fn triangle_count(&self) -> usize {
+ self.indices.len() / 3
+ }
+
+ /// The bounds of the positions, without skinning or morph targets.
+ pub fn bounds(&self) -> Aabb {
+ self.bounds
+ }
+
+ /// Calculates [`Geometry::bounds`] again. Call it after you change `positions`.
+ pub fn update_bounds(&mut self) {
+ self.bounds = Aabb::from_points(self.positions.iter().copied());
+ }
+
+ /// Calculates smooth normals from the triangles, weighted by triangle area, like
+ /// three.js `computeVertexNormals`.
+ pub fn compute_vertex_normals(&mut self) {
+ let mut normals = vec![Vec3::ZERO; self.positions.len()];
+ for tri in self.triangles() {
+ let corners = tri.map(|i| i as usize);
+ let n = face_normal(corners.map(|i| self.positions[i]));
+ for i in corners {
+ normals[i] += n;
+ }
+ }
+ for n in &mut normals {
+ *n = n.normalize_or(Vec3::Y);
+ }
+ self.normals = normals;
+ }
+
+ /// A box, like three.js `BoxGeometry(width, height, depth)`.
+ pub fn cuboid(width: f32, height: f32, depth: f32) -> Self {
+ Self::rounded_box(width, height, depth, 0.0, 1)
+ }
+
+ /// A box with rounded edges and corners, like three.js `RoundedBoxGeometry`. `radius` is
+ /// the radius of the edges. `segments` is the number of steps on each rounded edge; 3
+ /// or 4 look smooth. Rounded edges catch highlights, so use them for machined parts.
+ /// A negative size gives the same box as its absolute value.
+ pub fn rounded_box(width: f32, height: f32, depth: f32, radius: f32, segments: u32) -> Self {
+ let half = Vec3::new(width, height, depth).abs() * 0.5;
+ let radius = radius.min(half.min_element()).max(0.0);
+ let inner = half - Vec3::splat(radius);
+ let segments = segments.max(1);
+ // Grid lines along a face axis with the half size `h`. A line at `radius * tan(a)`
+ // past the flat part moves to the angle `a` on the rounded edge. Each of the two
+ // faces at an edge thus covers 45 degrees of it in equal steps.
+ let axis_coords = |h: f32| -> Vec<f32> {
+ if radius <= 0.0 {
+ return vec![-h, h];
+ }
+ let inner = h - radius;
+ let step = |k: u32| radius * (k as f32 / segments as f32 * FRAC_PI_4).tan();
+ let mut coords: Vec<f32> = (1..=segments).rev().map(|k| -inner - step(k)).collect();
+ coords.push(-inner);
+ if inner > 1e-6 {
+ coords.push(inner);
+ }
+ coords.extend((1..=segments).map(|k| inner + step(k)));
+ coords
+ };
+
+ // The normal of each face, then its U and V directions.
+ let faces = [
+ (Vec3::X, Vec3::NEG_Z, Vec3::Y),
+ (Vec3::NEG_X, Vec3::Z, Vec3::Y),
+ (Vec3::Y, Vec3::X, Vec3::NEG_Z),
+ (Vec3::NEG_Y, Vec3::X, Vec3::Z),
+ (Vec3::Z, Vec3::X, Vec3::Y),
+ (Vec3::NEG_Z, Vec3::NEG_X, Vec3::Y),
+ ];
+
+ let mut b = Builder::default();
+ for (n, u, v) in faces {
+ let [hn, hu, hv] = [n, u, v].map(|axis| axis.abs().dot(half));
+ let (us, vs) = (axis_coords(hu), axis_coords(hv));
+ let base = b.positions.len() as u32;
+ for &cv in &vs {
+ for &cu in &us {
+ let p = n * hn + u * cu + v * cv;
+ let (p, normal) = if radius > 0.0 {
+ // Move the point from the inner box out to the rounded surface.
+ let c = p.clamp(-inner, inner);
+ let normal = (p - c).normalize_or(n);
+ (c + normal * radius, normal)
+ } else {
+ (p, n)
+ };
+ // a side of zero length gets UV 0 instead of 0 / 0
+ let (su, sv) = (
+ (2.0 * hu).max(f32::MIN_POSITIVE),
+ (2.0 * hv).max(f32::MIN_POSITIVE),
+ );
+ let uv = Vec2::new((cu + hu) / su, 1.0 - (cv + hv) / sv);
+ b.vertex(p, normal, uv);
+ }
+ }
+ b.grid(base, us.len() as u32, vs.len() as u32);
+ }
+ b.build()
+ }
+
+ /// A UV sphere, like three.js `SphereGeometry(radius, widthSegments, heightSegments)`.
+ pub fn sphere(radius: f32, width_segments: u32, height_segments: u32) -> Self {
+ Self::sphere_partial(radius, width_segments, height_segments, 0.0, PI)
+ }
+
+ /// The part of a sphere between the polar angles `theta_start` and
+ /// `theta_start + theta_length`, in radians. The angle 0 is the top.
+ /// `sphere_partial(r, 32, 16, 0.0, PI / 2.0)` is a dome.
+ pub fn sphere_partial(
+ radius: f32,
+ width_segments: u32,
+ height_segments: u32,
+ theta_start: f32,
+ theta_length: f32,
+ ) -> Self {
+ let ws = width_segments.max(3);
+ let hs = height_segments.max(2);
+ let theta_end = (theta_start + theta_length).min(PI);
+ let mut b = Builder::default();
+ for iy in 0..=hs {
+ let v = iy as f32 / hs as f32;
+ let theta = theta_start + v * theta_length;
+ for ix in 0..=ws {
+ let u = ix as f32 / ws as f32;
+ let phi = u * TAU;
+ let n = Vec3::new(
+ -phi.cos() * theta.sin(),
+ theta.cos(),
+ phi.sin() * theta.sin(),
+ );
+ // V runs down the image, so the top of a panorama is at the north pole
+ b.vertex(n * radius, n, Vec2::new(u, v));
+ }
+ }
+ let row = ws + 1;
+ for iy in 0..hs {
+ for ix in 0..ws {
+ let a = iy * row + ix;
+ // At a pole one triangle of each quad has no area, so skip it.
+ if iy != 0 || theta_start > 0.0 {
+ b.tri(a + 1, a, a + row + 1);
+ }
+ if iy != hs - 1 || theta_end < PI {
+ b.tri(a, a + row, a + row + 1);
+ }
+ }
+ }
+ b.build()
+ }
+
+ /// A closed cylinder along Y, like three.js `CylinderGeometry(radiusTop, radiusBottom,
+ /// height, radialSegments)`. A radius of 0 makes a cone. The side has V from 0 at the
+ /// top to 1 at the bottom, and the caps have planar UVs.
+ pub fn cylinder(
+ radius_top: f32,
+ radius_bottom: f32,
+ height: f32,
+ radial_segments: u32,
+ ) -> Self {
+ let h = height * 0.5;
+ let side = Self::cylinder_open(radius_top, radius_bottom, height, radial_segments);
+ let caps = [(radius_top, h, true), (radius_bottom, -h, false)]
+ .into_iter()
+ .filter(|(radius, _, _)| *radius > 0.0)
+ .map(|(radius, y, top)| cap(radius, y, top, radial_segments));
+ Self::merge(std::iter::once(side).chain(caps))
+ }
+
+ /// A cylinder along Y without caps. The parameters are the same as for
+ /// [`Geometry::cylinder`].
+ pub fn cylinder_open(
+ radius_top: f32,
+ radius_bottom: f32,
+ height: f32,
+ radial_segments: u32,
+ ) -> Self {
+ let h = height * 0.5;
+ Self::lathe(
+ &[Vec2::new(radius_bottom, -h), Vec2::new(radius_top, h)],
+ radial_segments,
+ )
+ }
+
+ /// A cone along Y with its tip up, like three.js `ConeGeometry`.
+ pub fn cone(radius: f32, height: f32, radial_segments: u32) -> Self {
+ Self::cylinder(0.0, radius, height, radial_segments)
+ }
+
+ /// A capsule along Y, like three.js `CapsuleGeometry(radius, length)`. `length` is the
+ /// straight part between the two half spheres.
+ pub fn capsule(radius: f32, length: f32, cap_segments: u32, radial_segments: u32) -> Self {
+ let cap_segments = cap_segments.max(2);
+ let h = length * 0.5;
+ let angle = |i: u32| i as f32 / cap_segments as f32 * FRAC_PI_2;
+ let point = |a: f32, y: f32| Vec2::new(radius * a.cos(), y + radius * a.sin());
+ let bottom = (0..=cap_segments).map(|i| point(-FRAC_PI_2 + angle(i), -h));
+ let top = (0..=cap_segments).map(|i| point(angle(i), h));
+ Self::lathe(&bottom.chain(top).collect::<Vec<_>>(), radial_segments)
+ }
+
+ /// A torus around the Z axis, like three.js `TorusGeometry(radius, tube)`.
+ pub fn torus(radius: f32, tube: f32, radial_segments: u32, tubular_segments: u32) -> Self {
+ Self::torus_arc(radius, tube, radial_segments, tubular_segments, TAU)
+ }
+
+ /// The part of a torus from angle 0 to `arc` radians.
+ pub fn torus_arc(
+ radius: f32,
+ tube: f32,
+ radial_segments: u32,
+ tubular_segments: u32,
+ arc: f32,
+ ) -> Self {
+ let rs = radial_segments.max(3);
+ let ts = tubular_segments.max(3);
+ let mut b = Builder::default();
+ for j in 0..=rs {
+ let v = j as f32 / rs as f32 * TAU;
+ for i in 0..=ts {
+ let u = i as f32 / ts as f32 * arc;
+ let center = Vec3::new(radius * u.cos(), radius * u.sin(), 0.0);
+ let p = Vec3::new(
+ (radius + tube * v.cos()) * u.cos(),
+ (radius + tube * v.cos()) * u.sin(),
+ tube * v.sin(),
+ );
+ let uv = Vec2::new(i as f32 / ts as f32, 1.0 - j as f32 / rs as f32);
+ b.vertex(p, (p - center).normalize_or_zero(), uv);
+ }
+ }
+ let row = ts + 1;
+ for j in 0..rs {
+ for i in 0..ts {
+ let a = j * row + i;
+ b.tri(a + row, a, a + row + 1);
+ b.tri(a, a + 1, a + row + 1);
+ }
+ }
+ b.build()
+ }
+
+ /// A rectangle in the XY plane that faces +Z, like three.js `PlaneGeometry`.
+ pub fn plane(width: f32, height: f32) -> Self {
+ let (w, h) = (width * 0.5, height * 0.5);
+ let mut b = Builder::default();
+ b.vertex(Vec3::new(-w, -h, 0.0), Vec3::Z, Vec2::new(0.0, 1.0));
+ b.vertex(Vec3::new(w, -h, 0.0), Vec3::Z, Vec2::new(1.0, 1.0));
+ b.vertex(Vec3::new(w, h, 0.0), Vec3::Z, Vec2::new(1.0, 0.0));
+ b.vertex(Vec3::new(-w, h, 0.0), Vec3::Z, Vec2::new(0.0, 0.0));
+ b.quad(0, 1, 2, 3);
+ b.build()
+ }
+
+ /// A floor: a rectangle in the XZ plane that faces up (+Y). The UVs are in world
+ /// units, so textures and grid patterns repeat once per unit.
+ pub fn floor(width: f32, depth: f32) -> Self {
+ Self::floor_segments(width, depth, 1, 1)
+ }
+
+ /// A [`Geometry::floor`] made of a grid of quads, for vertex colors or deformation.
+ pub fn floor_segments(
+ width: f32,
+ depth: f32,
+ width_segments: u32,
+ depth_segments: u32,
+ ) -> Self {
+ let (ws, ds) = (width_segments.max(1), depth_segments.max(1));
+ let mut b = Builder::default();
+ for j in 0..=ds {
+ let z = depth * 0.5 - depth * j as f32 / ds as f32;
+ for i in 0..=ws {
+ let x = -width * 0.5 + width * i as f32 / ws as f32;
+ b.vertex(Vec3::new(x, 0.0, z), Vec3::Y, Vec2::new(x, z));
+ }
+ }
+ b.grid(0, ws + 1, ds + 1);
+ b.build()
+ }
+
+ /// A disc in the XY plane that faces +Z, like three.js `CircleGeometry`.
+ pub fn circle(radius: f32, segments: u32) -> Self {
+ Self::ring(0.0, radius, segments)
+ }
+
+ /// A flat ring in the XY plane that faces +Z, like three.js `RingGeometry`.
+ pub fn ring(inner: f32, outer: f32, segments: u32) -> Self {
+ let segments = segments.max(3);
+ let mut b = Builder::default();
+ for i in 0..=segments {
+ let a = i as f32 / segments as f32 * TAU;
+ let dir = Vec3::new(a.cos(), a.sin(), 0.0);
+ let ratio = inner / outer.max(f32::MIN_POSITIVE);
+ let inner_uv = Vec2::new(0.5 + 0.5 * dir.x * ratio, 0.5 - 0.5 * dir.y * ratio);
+ b.vertex(dir * inner, Vec3::Z, inner_uv);
+ let outer_uv = Vec2::new(0.5 + 0.5 * dir.x, 0.5 - 0.5 * dir.y);
+ b.vertex(dir * outer, Vec3::Z, outer_uv);
+ }
+ for i in 0..segments {
+ let a = i * 2;
+ b.quad(a, a + 1, a + 3, a + 2);
+ }
+ b.build()
+ }
+
+ /// Turns a profile around the Y axis, like three.js `LatheGeometry`. The points are
+ /// `(radius, y)` from bottom to top. Corners sharper than 35 degrees get a separate
+ /// normal on each side. Thus the profile `[(0, 0), (1, 0), (1, 1), (0, 1)]` is a
+ /// cylinder with sharp edges. V goes along the profile, from 1 at the first point to 0
+ /// at the last, in proportion to the length. Fewer than two points give an empty
+ /// geometry.
+ pub fn lathe(points: &[Vec2], segments: u32) -> Self {
+ let segments = segments.max(3);
+ let profile = split_sharp_profile(points, 35f32.to_radians());
+ if profile.len() < 2 {
+ return Geometry::default();
+ }
+ let n = profile.len() as u32;
+ let mut along = vec![0.0f32; profile.len()];
+ for j in 1..profile.len() {
+ along[j] = along[j - 1] + profile[j].0.distance(profile[j - 1].0);
+ }
+ let length = along[profile.len() - 1].max(f32::MIN_POSITIVE);
+ let mut b = Builder::default();
+ for i in 0..=segments {
+ let phi = i as f32 / segments as f32 * TAU;
+ let (sin, cos) = phi.sin_cos();
+ for (j, (p, normal)) in profile.iter().enumerate() {
+ let position = Vec3::new(p.x * sin, p.y, p.x * cos);
+ let normal =
+ Vec3::new(normal.x * sin, normal.y, normal.x * cos).normalize_or(Vec3::Y);
+ let uv = Vec2::new(i as f32 / segments as f32, 1.0 - along[j] / length);
+ b.vertex(position, normal, uv);
+ }
+ }
+ for i in 0..segments {
+ for j in 0..n - 1 {
+ // A split corner has two points at the same place. The quad between them
+ // has no area, so skip it.
+ if profile[j as usize].0 == profile[j as usize + 1].0 {
+ continue;
+ }
+ let a = j + i * n;
+ b.tri(a, a + n, a + 1);
+ b.tri(a + n + 1, a + 1, a + n);
+ }
+ }
+ b.build()
+ }
+
+ /// Extrudes a 2D shape along Z, like three.js `ExtrudeGeometry`. The shape is a list of
+ /// counter-clockwise points in the XY plane, and it can be concave. `depth` is the
+ /// thickness, centered on Z = 0. `bevel` is the radius of the rounded front and back
+ /// edges, which make plates and panels look machined.
+ pub fn extrude(shape: &[Vec2], depth: f32, bevel: f32) -> Self {
+ Self::extrude_segments(shape, depth, bevel, 3)
+ }
+
+ /// A [`Geometry::extrude`] with `bevel_segments` steps on each bevel. 1 step makes a
+ /// chamfer.
+ pub fn extrude_segments(shape: &[Vec2], depth: f32, bevel: f32, bevel_segments: u32) -> Self {
+ let shape = Shape {
+ outer: shape.to_vec(),
+ holes: Vec::new(),
+ };
+ Self::extrude_shape(&shape, depth, bevel, bevel_segments)
+ }
+
+ /// Extrudes a [`Shape`] with holes along Z, centered on Z = 0. The bevel has
+ /// `bevel_segments` rounded steps. [`Geometry::text`] makes letters with it.
+ pub fn extrude_shape(shape: &Shape, depth: f32, bevel: f32, bevel_segments: u32) -> Self {
+ // The outer contour goes counter-clockwise and the holes go clockwise. The solid is
+ // thus always on the left side of an edge.
+ let mut contours = Vec::with_capacity(1 + shape.holes.len());
+ for (i, contour) in std::iter::once(&shape.outer)
+ .chain(&shape.holes)
+ .enumerate()
+ {
+ let mut c = contour.clone();
+ c.dedup_by(|a, b| a.distance_squared(*b) < 1e-12);
+ if let [first, .., last] = c.as_slice()
+ && first.distance_squared(*last) < 1e-12
+ {
+ c.pop();
+ }
+ if c.len() < 3 {
+ if i == 0 {
+ return Geometry::default();
+ }
+ continue;
+ }
+ if (signed_area(&c) > 0.0) != (i == 0) {
+ c.reverse();
+ }
+ contours.push(c);
+ }
+ let half = depth.abs() * 0.5;
+ let bevel = bevel.min(half).max(0.0);
+ let bevel_segments = if bevel > 0.0 {
+ bevel_segments.max(1)
+ } else {
+ 0
+ };
+
+ // The side wall has rings of points from the front (+Z) to the back. On the bevel,
+ // ring `k` is at the angle `a` from the cap plane.
+ let ring = |k: u32, back: bool| {
+ let a = if bevel_segments == 0 {
+ FRAC_PI_2
+ } else {
+ k as f32 / bevel_segments as f32 * FRAC_PI_2
+ };
+ let (sin, cos) = a.sin_cos();
+ WallRing {
+ inset: bevel * (1.0 - sin),
+ z: if back {
+ -half + bevel - bevel * cos
+ } else {
+ half - bevel + bevel * cos
+ },
+ normal_z: if back { -cos } else { cos },
+ normal_xy: sin,
+ }
+ };
+ let rings: Vec<WallRing> = (0..=bevel_segments)
+ .map(|k| ring(k, false))
+ .chain((0..=bevel_segments).rev().map(|k| ring(k, true)))
+ .collect();
+
+ // Moves corner `i` of contour `c` into the solid by `amount`, along the miter of
+ // its two edges.
+ let inset = |c: &[Vec2], i: usize, amount: f32| -> Vec2 {
+ if amount == 0.0 {
+ return c[i];
+ }
+ let n = c.len();
+ let n0 = (c[i] - c[(i + n - 1) % n]).perp().normalize_or_zero();
+ let n1 = (c[(i + 1) % n] - c[i]).perp().normalize_or_zero();
+ let miter = (n0 + n1).normalize_or(n1);
+ // The limit keeps sharp corners from going too far.
+ c[i] + miter * (amount / miter.dot(n1).max(0.25))
+ };
+
+ let mut b = Builder::default();
+ // Side walls: flat along each edge, smooth across the bevel.
+ for c in &contours {
+ let perimeter = closed_edges(c)
+ .map(|(p, q)| p.distance(q))
+ .sum::<f32>()
+ .max(1e-6);
+ let mut along = 0.0;
+ for i in 0..c.len() {
+ let j = (i + 1) % c.len();
+ let outward = -(c[j] - c[i]).perp().normalize_or_zero();
+ let edge_len = c[i].distance(c[j]);
+ let base = b.positions.len() as u32;
+ for (r, ring) in rings.iter().enumerate() {
+ let normal = (outward * ring.normal_xy)
+ .extend(ring.normal_z)
+ .normalize_or(Vec3::Z);
+ let v = r as f32 / (rings.len() - 1) as f32;
+ let p0 = inset(c, i, ring.inset);
+ let p1 = inset(c, j, ring.inset);
+ b.vertex(p0.extend(ring.z), normal, Vec2::new(along / perimeter, v));
+ b.vertex(
+ p1.extend(ring.z),
+ normal,
+ Vec2::new((along + edge_len) / perimeter, v),
+ );
+ }
+ along += edge_len;
+ for r in 0..rings.len() as u32 - 1 {
+ // Ring `r` is in front of ring `r + 1`, which sets the winding.
+ let a = base + r * 2;
+ b.quad(a + 2, a + 3, a + 1, a);
+ }
+ }
+ }
+
+ // Caps: the inset contours, filled with the non-zero winding rule because font
+ // contours can overlap.
+ let insets: Vec<Vec<Vec2>> = contours
+ .iter()
+ .map(|c| (0..c.len()).map(|i| inset(c, i, bevel)).collect())
+ .collect();
+ let triangles = fill_nonzero(&insets);
+ let bounds = Aabb::from_points(insets.iter().flatten().map(|p| p.extend(0.0)));
+ let min = bounds.min.truncate();
+ let size = bounds.size().truncate().max(Vec2::splat(1e-6));
+ for (z, normal) in [(half, Vec3::Z), (-half, Vec3::NEG_Z)] {
+ for tri in &triangles {
+ let base = b.positions.len() as u32;
+ for p in tri {
+ let uv = (*p - min) / size;
+ b.vertex(p.extend(z), normal, Vec2::new(uv.x, 1.0 - uv.y));
+ }
+ // The back cap faces -Z, so it has the opposite winding.
+ if normal.z > 0.0 {
+ b.tri(base, base + 1, base + 2);
+ } else {
+ b.tri(base, base + 2, base + 1);
+ }
+ }
+ }
+ b.build()
+ }
+
+ /// The outlines of `text` in a TrueType or OpenType font, as [`Shape`]s for each glyph.
+ /// `size` is the font size (one em) in world units, and `letter_spacing` is extra space
+ /// after each glyph. Each glyph has an origin: the pen position on the baseline. This
+ /// function does not apply kerning.
+ pub fn text_shapes(
+ font: &[u8],
+ text: &str,
+ size: f32,
+ letter_spacing: f32,
+ ) -> Result<Vec<GlyphShapes>, TextError> {
+ let face = ttf_parser::Face::parse(font, 0).map_err(|_| TextError::InvalidFont)?;
+ let scale = size / f32::from(face.units_per_em());
+ let mut pen = 0.0;
+ text.chars()
+ .map(|ch| {
+ let id = face.glyph_index(ch).ok_or(TextError::MissingGlyph(ch))?;
+ let mut outline = OutlineCollector {
+ scale,
+ ..Default::default()
+ };
+ face.outline_glyph(id, &mut outline);
+ outline.finish();
+ let advance = f32::from(face.glyph_hor_advance(id).unwrap_or(0)) * scale;
+ let glyph = GlyphShapes {
+ ch,
+ origin: Vec2::new(pen, 0.0),
+ advance,
+ shapes: shapes_from_contours(outline.contours),
+ };
+ pen += advance + letter_spacing;
+ Ok(glyph)
+ })
+ .collect()
+ }
+
+ /// Extruded 3D text, like three.js `TextGeometry`. `size` is the em size, `depth` the
+ /// thickness, and `bevel` the radius of the rounded edges. The text starts at X = 0 on
+ /// the baseline (Y = 0) and faces +Z. For one geometry per letter, use
+ /// [`Geometry::text_glyphs`].
+ pub fn text(
+ font: &[u8],
+ text: &str,
+ size: f32,
+ depth: f32,
+ bevel: f32,
+ ) -> Result<Self, TextError> {
+ Ok(Self::merge(
+ Self::text_glyphs(font, text, size, depth, bevel)?
+ .into_iter()
+ .map(|g| g.geometry.translate(g.origin.x, g.origin.y, 0.0)),
+ ))
+ }
+
+ /// Each letter of `text` as a separate extruded geometry, with its position in the line.
+ /// The parameters are the same as for [`Geometry::text`].
+ pub fn text_glyphs(
+ font: &[u8],
+ text: &str,
+ size: f32,
+ depth: f32,
+ bevel: f32,
+ ) -> Result<Vec<Glyph>, TextError> {
+ Ok(Self::text_shapes(font, text, size, 0.0)?
+ .into_iter()
+ .map(|g| Glyph {
+ ch: g.ch,
+ origin: g.origin,
+ advance: g.advance,
+ geometry: Self::merge(
+ g.shapes
+ .iter()
+ .map(|s| Self::extrude_shape(s, depth, bevel, 2)),
+ ),
+ })
+ .collect())
+ }
+
+ /// A regular polygon in the XY plane for [`Geometry::extrude`], with `sides` corners at
+ /// the distance `radius` from the center. The first corner points up.
+ pub fn polygon(radius: f32, sides: u32) -> Vec<Vec2> {
+ let sides = sides.max(3);
+ (0..sides)
+ .map(|i| {
+ let a = FRAC_PI_2 + i as f32 / sides as f32 * TAU;
+ Vec2::new(a.cos(), a.sin()) * radius
+ })
+ .collect()
+ }
+
+ /// An icosphere, like three.js `IcosahedronGeometry(radius, detail)`. Each face splits
+ /// into `(detail + 1)²` triangles. Detail 0 is faceted, higher details have smooth
+ /// normals; [`crate::Material::flat`] makes them faceted too.
+ pub fn icosahedron(radius: f32, detail: u32) -> Self {
+ let t = f32::midpoint(1.0, 5f32.sqrt());
+ let corners: Vec<Vec3> = [
+ (-1.0, t, 0.0),
+ (1.0, t, 0.0),
+ (-1.0, -t, 0.0),
+ (1.0, -t, 0.0),
+ (0.0, -1.0, t),
+ (0.0, 1.0, t),
+ (0.0, -1.0, -t),
+ (0.0, 1.0, -t),
+ (t, 0.0, -1.0),
+ (t, 0.0, 1.0),
+ (-t, 0.0, -1.0),
+ (-t, 0.0, 1.0),
+ ]
+ .iter()
+ .map(|&(x, y, z)| Vec3::new(x, y, z).normalize())
+ .collect();
+ const FACES: [[usize; 3]; 20] = [
+ [0, 11, 5],
+ [0, 5, 1],
+ [0, 1, 7],
+ [0, 7, 10],
+ [0, 10, 11],
+ [1, 5, 9],
+ [5, 11, 4],
+ [11, 10, 2],
+ [10, 7, 6],
+ [7, 1, 8],
+ [3, 9, 4],
+ [3, 4, 2],
+ [3, 2, 6],
+ [3, 6, 8],
+ [3, 8, 9],
+ [4, 9, 5],
+ [2, 4, 11],
+ [6, 2, 10],
+ [8, 6, 7],
+ [9, 8, 1],
+ ];
+ // three.js `PolyhedronGeometry`: a triangular grid on each face, with its own
+ // vertices, so the UV seam of each triangle can be fixed
+ let cols = detail as usize + 1;
+ let mut triangles: Vec<[Vec3; 3]> = Vec::with_capacity(20 * cols * cols);
+ for [a, b, c] in FACES {
+ let (a, b, c) = (corners[a], corners[b], corners[c]);
+ let grid: Vec<Vec<Vec3>> = (0..=cols)
+ .map(|i| {
+ let aj = a.lerp(c, i as f32 / cols as f32);
+ let bj = b.lerp(c, i as f32 / cols as f32);
+ let rows = cols - i;
+ (0..=rows)
+ .map(|j| {
+ if rows == 0 {
+ aj
+ } else {
+ aj.lerp(bj, j as f32 / rows as f32)
+ }
+ })
+ .collect()
+ })
+ .collect();
+ for i in 0..cols {
+ for j in 0..2 * (cols - i) - 1 {
+ let k = j / 2;
+ triangles.push(if j % 2 == 0 {
+ [grid[i][k + 1], grid[i + 1][k], grid[i][k]]
+ } else {
+ [grid[i][k + 1], grid[i + 1][k + 1], grid[i + 1][k]]
+ });
+ }
+ }
+ }
+ let azimuth = |v: Vec3| v.z.atan2(-v.x);
+ let mut b = Builder::default();
+ for tri in triangles {
+ let tri = tri.map(Vec3::normalize);
+ let mut uvs = tri.map(|v| Vec2::new(azimuth(v) / TAU + 0.5, 0.5 - v.y.asin() / PI));
+ // a vertex on a pole takes the azimuth of the triangle center
+ let center = (tri[0] + tri[1] + tri[2]) / 3.0;
+ for (uv, v) in uvs.iter_mut().zip(tri) {
+ if v.x.abs() < 1e-6 && v.z.abs() < 1e-6 {
+ uv.x = azimuth(center) / TAU + 0.5;
+ }
+ }
+ // a triangle across the seam at U 0 and 1 wraps its small Us
+ let (min, max) = uvs.iter().fold((f32::MAX, f32::MIN), |(lo, hi), uv| {
+ (lo.min(uv.x), hi.max(uv.x))
+ });
+ if max > 0.9 && min < 0.1 {
+ for uv in &mut uvs {
+ if uv.x < 0.2 {
+ uv.x += 1.0;
+ }
+ }
+ }
+ // three.js: flat normals without subdivision, sphere normals with it
+ let flat = face_normal(tri).normalize_or(center);
+ let i = b.positions.len() as u32;
+ for (v, uv) in tri.iter().zip(uvs) {
+ b.vertex(*v * radius, if detail == 0 { flat } else { *v }, uv);
+ }
+ b.tri(i, i + 1, i + 2);
+ }
+ b.build()
+ }
+
+ /// A round tube with `radius` along `path`, like three.js `TubeGeometry`. Use it for
+ /// cables and hoses. The tube goes straight from point to point, so give enough points
+ /// for a smooth curve. A path with less than two points gives an empty geometry.
+ pub fn tube(path: &[Vec3], radius: f32, radial_segments: u32) -> Self {
+ let rs = radial_segments.max(3);
+ if path.len() < 2 {
+ return Geometry::default();
+ }
+ let tangents: Vec<Vec3> = (0..path.len())
+ .map(|i| {
+ let a = path[i.saturating_sub(1)];
+ let b = path[(i + 1).min(path.len() - 1)];
+ (b - a).normalize_or(Vec3::Y)
+ })
+ .collect();
+ // Parallel transport: the normal turns with the tangent from one point to the next,
+ // so the tube does not twist.
+ let mut normal = tangents[0].any_orthonormal_vector();
+ let mut b = Builder::default();
+ for (i, p) in path.iter().enumerate() {
+ if i > 0 {
+ let axis = tangents[i - 1].cross(tangents[i]);
+ if axis.length_squared() > 1e-10 {
+ let angle = tangents[i - 1].dot(tangents[i]).clamp(-1.0, 1.0).acos();
+ normal = Quat::from_axis_angle(axis.normalize(), angle) * normal;
+ }
+ }
+ let binormal = tangents[i].cross(normal);
+ for j in 0..=rs {
+ let a = j as f32 / rs as f32 * TAU;
+ let n = (normal * a.cos() + binormal * a.sin()).normalize();
+ let uv = Vec2::new(
+ i as f32 / (path.len() - 1) as f32,
+ 1.0 - j as f32 / rs as f32,
+ );
+ b.vertex(*p + n * radius, n, uv);
+ }
+ }
+ b.grid(0, rs + 1, path.len() as u32);
+ b.build()
+ }
+
+ /// Applies the matrix `m` to the positions, the normals and the morph targets. When `m`
+ /// mirrors the geometry, this function also reverses the winding, so the triangles
+ /// still face out.
+ pub fn transform(mut self, m: Mat4) -> Self {
+ let linear = Mat3::from_mat4(m);
+ let normal_matrix = linear.inverse().transpose();
+ for p in &mut self.positions {
+ *p = m.transform_point3(*p);
+ }
+ for n in &mut self.normals {
+ *n = (normal_matrix * *n).normalize_or_zero();
+ }
+ // the targets hold offsets: no translation, and normal offsets stay unnormalized
+ for target in &mut self.morph_targets {
+ for d in &mut target.positions {
+ *d = linear * *d;
+ }
+ for d in &mut target.normals {
+ *d = normal_matrix * *d;
+ }
+ }
+ if m.determinant() < 0.0 {
+ for tri in self.indices.as_chunks_mut::<3>().0 {
+ tri.swap(1, 2);
+ }
+ }
+ self.update_bounds();
+ self
+ }
+
+ /// Moves the geometry by `(x, y, z)`.
+ pub fn translate(self, x: f32, y: f32, z: f32) -> Self {
+ self.transform(Mat4::from_translation(Vec3::new(x, y, z)))
+ }
+
+ /// Rotates the geometry around the origin.
+ pub fn rotate(self, rotation: Quat) -> Self {
+ self.transform(Mat4::from_quat(rotation))
+ }
+
+ /// Rotates the geometry around the X axis by `angle` radians.
+ pub fn rotate_x(self, angle: f32) -> Self {
+ self.transform(Mat4::from_rotation_x(angle))
+ }
+
+ /// Rotates the geometry around the Y axis by `angle` radians.
+ pub fn rotate_y(self, angle: f32) -> Self {
+ self.transform(Mat4::from_rotation_y(angle))
+ }
+
+ /// Rotates the geometry around the Z axis by `angle` radians.
+ pub fn rotate_z(self, angle: f32) -> Self {
+ self.transform(Mat4::from_rotation_z(angle))
+ }
+
+ /// Scales the geometry along each axis. A negative factor mirrors it.
+ pub fn scale(self, x: f32, y: f32, z: f32) -> Self {
+ self.transform(Mat4::from_scale(Vec3::new(x, y, z)))
+ }
+
+ /// Sets all vertex colors to `color`. Then you can merge parts of different colors
+ /// into one mesh with one material. The material color multiplies the vertex color.
+ pub fn with_color(mut self, color: impl Into<Rgb>) -> Self {
+ let c = color.into().0.extend(1.0);
+ self.colors = vec![c; self.positions.len()];
+ self
+ }
+
+ /// Joins geometries into one. When only some parts have UVs or vertex colors, the
+ /// other parts get zero UVs and white vertex colors. The result has no skin and no
+ /// morph targets.
+ pub fn merge(parts: impl IntoIterator<Item = Geometry>) -> Self {
+ let parts: Vec<Geometry> = parts.into_iter().collect();
+ let any_uvs = parts.iter().any(|p| !p.uvs.is_empty());
+ let any_colors = parts.iter().any(|p| !p.colors.is_empty());
+ let mut out = Geometry::default();
+ for part in parts {
+ let offset = out.positions.len() as u32;
+ let count = part.positions.len();
+ out.positions.extend(part.positions);
+ out.normals.extend(part.normals);
+ if any_uvs {
+ if part.uvs.is_empty() {
+ out.uvs.extend(std::iter::repeat_n(Vec2::ZERO, count));
+ } else {
+ out.uvs.extend(part.uvs);
+ }
+ }
+ if any_colors {
+ if part.colors.is_empty() {
+ out.colors.extend(std::iter::repeat_n(Vec4::ONE, count));
+ } else {
+ out.colors.extend(part.colors);
+ }
+ }
+ out.indices.extend(part.indices.iter().map(|i| i + offset));
+ }
+ out.update_bounds();
+ out
+ }
+
+ /// Gives each triangle its own vertices with the face normal. The result looks faceted
+ /// with any material. It has no skin and no morph targets.
+ pub fn flat(self) -> Self {
+ let mut b = Builder::default();
+ for tri in self.triangles() {
+ let n = face_normal(tri.map(|i| self.positions[i as usize])).normalize_or_zero();
+ let [i0, i1, i2] = tri.map(|i| b.copy_vertex(&self, i as usize, n));
+ b.tri(i0, i1, i2);
+ }
+ b.build()
+ }
+}
+
+/// Collects vertices and triangles for a new [`Geometry`].
+#[derive(Default)]
+struct Builder {
+ positions: Vec<Vec3>,
+ normals: Vec<Vec3>,
+ uvs: Vec<Vec2>,
+ colors: Vec<Vec4>,
+ indices: Vec<u32>,
+}
+
+impl Builder {
+ /// Adds a vertex and returns its index.
+ fn vertex(&mut self, p: Vec3, n: Vec3, uv: Vec2) -> u32 {
+ self.positions.push(p);
+ self.normals.push(n);
+ self.uvs.push(uv);
+ self.positions.len() as u32 - 1
+ }
+
+ /// Adds a copy of vertex `i` of `source` with the normal `n`, and returns its index.
+ /// The copy has a UV and a color only when `source` has them.
+ fn copy_vertex(&mut self, source: &Geometry, i: usize, n: Vec3) -> u32 {
+ self.positions.push(source.positions[i]);
+ self.normals.push(n);
+ if !source.uvs.is_empty() {
+ self.uvs
+ .push(source.uvs.get(i).copied().unwrap_or_default());
+ }
+ if let Some(&color) = source.colors.get(i) {
+ self.colors.push(color);
+ }
+ self.positions.len() as u32 - 1
+ }
+
+ /// Adds a triangle with three new vertices. All of them have the normal `n` and a zero
+ /// UV.
+ fn flat_triangle(&mut self, [a, b, c]: [Vec3; 3], n: Vec3) {
+ let i = self.vertex(a, n, Vec2::ZERO);
+ self.vertex(b, n, Vec2::ZERO);
+ self.vertex(c, n, Vec2::ZERO);
+ self.tri(i, i + 1, i + 2);
+ }
+
+ fn tri(&mut self, a: u32, b: u32, c: u32) {
+ self.indices.extend([a, b, c]);
+ }
+
+ /// Adds the counter-clockwise quad `a b c d` as two triangles.
+ fn quad(&mut self, a: u32, b: u32, c: u32, d: u32) {
+ self.indices.extend([a, b, c, a, c, d]);
+ }
+
+ /// Adds two triangles for each cell of a vertex grid. The grid starts at index `base`
+ /// and has `rows` rows of `columns` vertices.
+ fn grid(&mut self, base: u32, columns: u32, rows: u32) {
+ for j in 0..rows - 1 {
+ for i in 0..columns - 1 {
+ let a = base + j * columns + i;
+ self.quad(a, a + 1, a + columns + 1, a + columns);
+ }
+ }
+ }
+
+ fn build(self) -> Geometry {
+ let mut geometry = Geometry::new(self.positions, self.normals, self.uvs, self.indices);
+ geometry.colors = self.colors;
+ geometry
+ }
+}
+
+/// A cap of [`Geometry::cylinder`]: a disc of `radius` at the height `y` that faces up
+/// (`top`) or down. Its rim has the vertices of the side, so the two meet without a gap.
+fn cap(radius: f32, y: f32, top: bool, segments: u32) -> Geometry {
+ let segments = segments.max(3);
+ let normal = if top { Vec3::Y } else { Vec3::NEG_Y };
+ let mut b = Builder::default();
+ let center = b.vertex(Vec3::new(0.0, y, 0.0), normal, Vec2::splat(0.5));
+ for i in 0..=segments {
+ let (sin, cos) = (i as f32 / segments as f32 * TAU).sin_cos();
+ // seen from outside, U goes to +X and V to the far side of the bottom cap
+ let v = if top {
+ 0.5 + 0.5 * cos
+ } else {
+ 0.5 - 0.5 * cos
+ };
+ b.vertex(
+ Vec3::new(radius * sin, y, radius * cos),
+ normal,
+ Vec2::new(0.5 + 0.5 * sin, v),
+ );
+ }
+ for i in 1..=segments {
+ if top {
+ b.tri(center, i, i + 1);
+ } else {
+ b.tri(center, i + 1, i);
+ }
+ }
+ b.build()
+}
+
+/// A ring of points on the side wall of an extrusion, see [`Geometry::extrude_shape`].
+struct WallRing {
+ /// The distance that the contour moves into the solid.
+ inset: f32,
+ z: f32,
+ /// The Z part of the normal before normalization.
+ normal_z: f32,
+ /// The weight of the outward edge normal in the normal.
+ normal_xy: f32,
+}
+
+/// The cross product of two triangle edges. It points to the counter-clockwise side, and
+/// its length is two times the triangle area.
+fn face_normal([a, b, c]: [Vec3; 3]) -> Vec3 {
+ (b - a).cross(c - a)
+}
+
+/// The edges of a closed contour: each point with the next point, and the last point with
+/// the first.
+fn closed_edges(contour: &[Vec2]) -> impl Iterator<Item = (Vec2, Vec2)> {
+ let points = contour.iter().copied();
+ points.clone().zip(points.cycle().skip(1))
+}
+
+/// The area of a polygon. It is positive when the points go counter-clockwise.
+fn signed_area(points: &[Vec2]) -> f32 {
+ closed_edges(points)
+ .map(|(a, b)| a.perp_dot(b))
+ .sum::<f32>()
+ * 0.5
+}
+
+/// Pairs each point of a lathe profile with its 2D normal. A corner sharper than
+/// `max_angle` occurs two times, once with the normal of each segment.
+fn split_sharp_profile(points: &[Vec2], max_angle: f32) -> Vec<(Vec2, Vec2)> {
+ let n = points.len();
+ if n < 2 {
+ return Vec::new();
+ }
+ // The normal on the right side of segment `i`. It points away from the axis when the
+ // profile goes up.
+ let seg_normal = |i: usize| -> Vec2 {
+ let d = points[i + 1] - points[i];
+ Vec2::new(d.y, -d.x).normalize_or_zero()
+ };
+ let mut out = Vec::with_capacity(n + 4);
+ out.push((points[0], seg_normal(0)));
+ for i in 1..n - 1 {
+ let a = seg_normal(i - 1);
+ let b = seg_normal(i);
+ if a == Vec2::ZERO || b == Vec2::ZERO || a.angle_to(b).abs() > max_angle {
+ out.push((points[i], if a == Vec2::ZERO { b } else { a }));
+ out.push((points[i], if b == Vec2::ZERO { a } else { b }));
+ } else {
+ out.push((points[i], (a + b).normalize_or(a)));
+ }
+ }
+ out.push((points[n - 1], seg_normal(n - 2)));
+ out
+}
+
+/// A filled outline with holes, for [`Geometry::extrude_shape`].
+#[derive(Debug, Clone, Default, PartialEq)]
+pub struct Shape {
+ pub outer: Vec<Vec2>,
+ pub holes: Vec<Vec<Vec2>>,
+}
+
+/// The outlines of one letter from [`Geometry::text_shapes`].
+#[derive(Debug, Clone)]
+pub struct GlyphShapes {
+ pub ch: char,
+ /// The pen position of the glyph on the baseline.
+ pub origin: Vec2,
+ /// The horizontal distance from this glyph to the next, without letter spacing.
+ pub advance: f32,
+ pub shapes: Vec<Shape>,
+}
+
+/// One extruded letter from [`Geometry::text_glyphs`].
+#[derive(Debug, Clone)]
+pub struct Glyph {
+ pub ch: char,
+ /// The pen position of the glyph on the baseline.
+ pub origin: Vec2,
+ /// The horizontal distance from this glyph to the next.
+ pub advance: f32,
+ /// The letter in glyph space. The pen position is at the origin, the baseline is at
+ /// Y = 0, and the letter faces +Z.
+ pub geometry: Geometry,
+}
+
+/// The reason that an STL file cannot be read.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum StlError {
+ /// The bytes are not a binary STL of the announced size, and not ASCII `facet` blocks.
+ Invalid,
+ /// The file has no triangles with an area.
+ Empty,
+}
+
+impl std::fmt::Display for StlError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ StlError::Invalid => write!(f, "not a binary or ASCII STL file"),
+ StlError::Empty => write!(f, "the STL file has no triangles"),
+ }
+ }
+}
+
+impl std::error::Error for StlError {}
+
+/// Reads the normal and the corners of each triangle of a binary STL. A binary STL has an
+/// 80 byte header, a triangle count, and 50 bytes for each triangle. Returns `None` when
+/// the size does not agree with the count. An ASCII file can have the correct size only by
+/// chance.
+fn binary_stl(bytes: &[u8]) -> Option<Vec<(Vec3, [Vec3; 3])>> {
+ let (count, records) = bytes.get(80..)?.split_first_chunk::<4>()?;
+ let (records, rest) = records.as_chunks::<50>();
+ if records.len() != u32::from_le_bytes(*count) as usize || !rest.is_empty() {
+ return None;
+ }
+ let triangles = records.iter().map(|record| {
+ // Twelve floats (the normal and three corners), then a 2 byte attribute.
+ let floats = record.as_chunks::<4>().0;
+ let v = |k: usize| {
+ Vec3::from_array(std::array::from_fn(|i| {
+ f32::from_le_bytes(floats[k * 3 + i])
+ }))
+ };
+ (v(0), [v(1), v(2), v(3)])
+ });
+ Some(triangles.collect())
+}
+
+/// Reads the normal and the corners of each triangle of an ASCII STL.
+fn ascii_stl(bytes: &[u8]) -> Result<Vec<(Vec3, [Vec3; 3])>, StlError> {
+ let text = std::str::from_utf8(bytes).map_err(|_| StlError::Invalid)?;
+ if !text.trim_start().starts_with("solid") {
+ return Err(StlError::Invalid);
+ }
+ let mut triangles = Vec::new();
+ let mut normal = Vec3::ZERO;
+ let mut corners = Vec::new();
+ for line in text.lines() {
+ let mut words = line.split_whitespace();
+ match words.next() {
+ Some("facet") => {
+ // `facet normal x y z`. A missing or bad number reads as 0.
+ normal = Vec3::from_array(three_numbers(words.skip(1)).map(|c| c.unwrap_or(0.0)));
+ corners.clear();
+ }
+ Some("vertex") => {
+ let [Some(x), Some(y), Some(z)] = three_numbers(words) else {
+ return Err(StlError::Invalid);
+ };
+ corners.push(Vec3::new(x, y, z));
+ }
+ Some("endfacet") => {
+ let tri = corners
+ .as_slice()
+ .try_into()
+ .map_err(|_| StlError::Invalid)?;
+ triangles.push((normal, tri));
+ }
+ _ => {}
+ }
+ }
+ Ok(triangles)
+}
+
+/// The next three words as numbers. A word that is not a number gives `None`.
+fn three_numbers<'a>(mut words: impl Iterator<Item = &'a str>) -> [Option<f32>; 3] {
+ let mut number = || words.next().and_then(|w| w.parse().ok());
+ [number(), number(), number()]
+}
+
+/// The reason that text cannot be made.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum TextError {
+ /// The bytes are not a TrueType or OpenType font.
+ InvalidFont,
+ /// The font has no glyph for this character.
+ MissingGlyph(char),
+}
+
+impl std::fmt::Display for TextError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ TextError::InvalidFont => write!(f, "not a TrueType/OpenType font"),
+ TextError::MissingGlyph(c) => write!(f, "the font has no glyph for {c:?}"),
+ }
+ }
+}
+
+impl std::error::Error for TextError {}
+
+/// Collects the outline of a glyph as closed polygons. Curves become line segments.
+#[derive(Default)]
+struct OutlineCollector {
+ /// World units per font unit.
+ scale: f32,
+ contours: Vec<Vec<Vec2>>,
+ current: Vec<Vec2>,
+ last: Vec2,
+}
+
+impl OutlineCollector {
+ fn point(&self, x: f32, y: f32) -> Vec2 {
+ Vec2::new(x, y) * self.scale
+ }
+
+ /// Ends the current contour. It keeps the contour only when it has three points or more,
+ /// because a smaller contour has no area.
+ fn finish(&mut self) {
+ if self.current.len() >= 3 {
+ self.contours.push(std::mem::take(&mut self.current));
+ }
+ self.current.clear();
+ }
+}
+
+impl ttf_parser::OutlineBuilder for OutlineCollector {
+ fn move_to(&mut self, x: f32, y: f32) {
+ self.finish();
+ self.line_to(x, y);
+ }
+
+ fn line_to(&mut self, x: f32, y: f32) {
+ self.last = self.point(x, y);
+ self.current.push(self.last);
+ }
+
+ fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
+ let (p0, c, p1) = (self.last, self.point(x1, y1), self.point(x, y));
+ let steps = 8;
+ self.current.extend((1..=steps).map(|i| {
+ let t = i as f32 / steps as f32;
+ let u = 1.0 - t;
+ p0 * (u * u) + c * (2.0 * u * t) + p1 * (t * t)
+ }));
+ self.last = p1;
+ }
+
+ fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
+ let (p0, c0, c1, p1) = (
+ self.last,
+ self.point(x1, y1),
+ self.point(x2, y2),
+ self.point(x, y),
+ );
+ let steps = 12;
+ self.current.extend((1..=steps).map(|i| {
+ let t = i as f32 / steps as f32;
+ let u = 1.0 - t;
+ p0 * (u * u * u) + c0 * (3.0 * u * u * t) + c1 * (3.0 * u * t * t) + p1 * (t * t * t)
+ }));
+ self.last = p1;
+ }
+
+ fn close(&mut self) {
+ self.finish();
+ }
+}
+
+/// True when `p` is inside `polygon` by the even-odd rule.
+fn point_in_polygon(p: Vec2, polygon: &[Vec2]) -> bool {
+ let mut inside = false;
+ let mut j = polygon.len() - 1;
+ for i in 0..polygon.len() {
+ let (a, b) = (polygon[i], polygon[j]);
+ if (a.y > p.y) != (b.y > p.y) && p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x {
+ inside = !inside;
+ }
+ j = i;
+ }
+ inside
+}
+
+/// Sorts the contours of a glyph into outlines and holes by their winding. Fonts do not
+/// agree on the direction (TrueType outlines go clockwise, CFF outlines counter-clockwise),
+/// but the largest contour is always an outline. Contours that wind like it are outlines,
+/// also where they overlap (variable fonts keep overlaps), the others are holes. A hole
+/// goes into the smallest outline that contains it.
+fn shapes_from_contours(contours: Vec<Vec<Vec2>>) -> Vec<Shape> {
+ let areas: Vec<f32> = contours.iter().map(|c| signed_area(c)).collect();
+ let Some(largest) = areas
+ .iter()
+ .copied()
+ .max_by(|a, b| a.abs().total_cmp(&b.abs()))
+ else {
+ return Vec::new();
+ };
+ let mut shapes: Vec<(f32, Shape)> = Vec::new();
+ let mut holes = Vec::new();
+ for (contour, area) in contours.into_iter().zip(areas) {
+ if (area > 0.0) == (largest > 0.0) {
+ let shape = Shape {
+ outer: contour,
+ holes: Vec::new(),
+ };
+ shapes.push((area.abs(), shape));
+ } else {
+ holes.push(contour);
+ }
+ }
+ for hole in holes {
+ if let Some((_, shape)) = shapes
+ .iter_mut()
+ .filter(|(_, s)| point_in_polygon(hole[0], &s.outer))
+ .min_by(|(a, _), (b, _)| a.total_cmp(b))
+ {
+ shape.holes.push(hole);
+ }
+ }
+ shapes.into_iter().map(|(_, shape)| shape).collect()
+}
+
+/// Triangles that cover the area where the winding number of `contours` is not zero.
+///
+/// This is a scanline decomposition. Horizontal lines through each vertex and each edge
+/// crossing cut the plane into slabs. In each slab, each span between edges with a winding
+/// number that is not zero becomes a trapezoid. Ear clipping fails on holes, overlaps and
+/// contours that cross themselves, which are frequent in fonts. This method does not.
+fn fill_nonzero(contours: &[Vec<Vec2>]) -> Vec<[Vec2; 3]> {
+ let edges: Vec<(Vec2, Vec2)> = contours
+ .iter()
+ .flat_map(|c| closed_edges(c))
+ .filter(|(a, b)| (a.y - b.y).abs() > 1e-9)
+ .collect();
+ let mut ys: Vec<f32> = edges.iter().flat_map(|(a, b)| [a.y, b.y]).collect();
+ for i in 0..edges.len() {
+ for j in i + 1..edges.len() {
+ if let Some(y) = crossing_y(edges[i], edges[j]) {
+ ys.push(y);
+ }
+ }
+ }
+ ys.sort_by(f32::total_cmp);
+ ys.dedup_by(|a, b| (*a - *b).abs() < 1e-7);
+
+ let x_at = |(a, b): (Vec2, Vec2), y: f32| a.x + (y - a.y) * (b.x - a.x) / (b.y - a.y);
+ let mut out = Vec::new();
+ // The edges in the current slab: X at the middle, bottom and top, and the winding.
+ let mut active: Vec<(f32, f32, f32, i32)> = Vec::new();
+ for slab in ys.windows(2) {
+ let (y0, y1) = (slab[0], slab[1]);
+ let ym = f32::midpoint(y0, y1);
+ active.clear();
+ for &edge in &edges {
+ let (a, b) = edge;
+ if (a.y.min(b.y)..a.y.max(b.y)).contains(&ym) {
+ let winding = if b.y > a.y { 1 } else { -1 };
+ active.push((x_at(edge, ym), x_at(edge, y0), x_at(edge, y1), winding));
+ }
+ }
+ active.sort_by(|a, b| a.0.total_cmp(&b.0));
+ let mut winding = 0;
+ let mut left: Option<(f32, f32)> = None;
+ for &(_, x0, x1, w) in &active {
+ let before = winding;
+ winding += w;
+ if before == 0 && winding != 0 {
+ left = Some((x0, x1));
+ } else if before != 0
+ && winding == 0
+ && let Some((l0, l1)) = left.take()
+ {
+ let (bl, br, tr, tl) = (
+ Vec2::new(l0, y0),
+ Vec2::new(x0, y0),
+ Vec2::new(x1, y1),
+ Vec2::new(l1, y1),
+ );
+ if (br.x - bl.x) > 1e-9 {
+ out.push([bl, br, tr]);
+ }
+ if (tr.x - tl.x) > 1e-9 {
+ out.push([bl, tr, tl]);
+ }
+ }
+ }
+ }
+ out
+}
+
+/// The height where two segments cross, or `None` when they do not cross.
+fn crossing_y((p1, p2): (Vec2, Vec2), (q1, q2): (Vec2, Vec2)) -> Option<f32> {
+ let r = p2 - p1;
+ let s = q2 - q1;
+ let denom = r.perp_dot(s);
+ if denom.abs() < 1e-12 {
+ return None;
+ }
+ let t = (q1 - p1).perp_dot(s) / denom;
+ let u = (q1 - p1).perp_dot(r) / denom;
+ (t > 1e-6 && t < 1.0 - 1e-6 && u > 1e-6 && u < 1.0 - 1e-6).then_some(p1.y + r.y * t)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Checks that each triangle winds counter-clockwise around its vertex normals.
+ fn assert_outward(geometry: &Geometry) {
+ let mut agree = 0;
+ let mut total = 0;
+ for tri in geometry.indices.as_chunks::<3>().0 {
+ let [a, b, c] = tri.map(|i| i as usize);
+ let face = face_normal([a, b, c].map(|i| geometry.positions[i]));
+ if face.length_squared() < 1e-12 {
+ continue;
+ }
+ total += 1;
+ let n = geometry.normals[a] + geometry.normals[b] + geometry.normals[c];
+ if face.dot(n) > 0.0 {
+ agree += 1;
+ }
+ }
+ assert!(total > 0);
+ assert_eq!(
+ agree, total,
+ "{agree} of {total} triangles face their normals"
+ );
+ }
+
+ fn cube_soup() -> Vec<[Vec3; 3]> {
+ let cube = Geometry::cuboid(2.0, 2.0, 2.0);
+ cube.indices
+ .as_chunks::<3>()
+ .0
+ .iter()
+ .map(|t| t.map(|i| cube.positions[i as usize]))
+ .collect()
+ }
+
+ #[test]
+ fn reads_binary_and_ascii_stl() {
+ let soup = cube_soup();
+ let mut binary = vec![0u8; 80];
+ binary.extend_from_slice(&(soup.len() as u32).to_le_bytes());
+ let mut ascii = String::from("solid cube\n");
+ for (i, tri) in soup.iter().enumerate() {
+ let n = face_normal(*tri).normalize();
+ // Half of the triangles have the wrong winding. The normal must correct them.
+ let tri = if i % 2 == 0 {
+ *tri
+ } else {
+ [tri[0], tri[2], tri[1]]
+ };
+ for v in [n, tri[0], tri[1], tri[2]] {
+ for c in v.to_array() {
+ binary.extend_from_slice(&c.to_le_bytes());
+ }
+ }
+ binary.extend_from_slice(&[0, 0]);
+ use std::fmt::Write;
+ writeln!(
+ ascii,
+ " facet normal {} {} {}\n outer loop",
+ n.x, n.y, n.z
+ )
+ .unwrap();
+ for v in tri {
+ writeln!(ascii, " vertex {} {} {}", v.x, v.y, v.z).unwrap();
+ }
+ ascii += " endloop\n endfacet\n";
+ }
+ ascii += "endsolid cube\n";
+ for geometry in [
+ Geometry::from_stl(&binary).unwrap(),
+ Geometry::from_stl(ascii.as_bytes()).unwrap(),
+ ] {
+ assert_eq!(geometry.triangle_count(), 12);
+ assert_eq!(geometry.vertex_count(), 36);
+ assert_eq!(geometry.uvs, Vec::<Vec2>::new());
+ assert_outward(&geometry);
+ assert_eq!(geometry.bounds().max, Vec3::splat(1.0));
+ // A cube stays faceted: 24 vertices at 8 positions.
+ let smoothed = geometry.smooth(30.0);
+ assert_eq!(smoothed.vertex_count(), 24);
+ assert_outward(&smoothed);
+ }
+ assert_eq!(
+ Geometry::from_stl(b"not a model").err(),
+ Some(StlError::Invalid)
+ );
+ assert_eq!(
+ Geometry::from_stl(b"solid x\nendsolid x\n").err(),
+ Some(StlError::Empty)
+ );
+ }
+
+ #[test]
+ fn smooth_rounds_a_faceted_sphere() {
+ let sphere = Geometry::sphere(1.0, 24, 16).flat();
+ let faceted = sphere.vertex_count();
+ let smoothed = sphere.smooth(60.0);
+ assert!(smoothed.vertex_count() < faceted / 4);
+ for (p, n) in smoothed.positions.iter().zip(&smoothed.normals) {
+ assert!(p.normalize().dot(*n) > 0.98, "{p} {n}");
+ }
+ }
+
+ #[test]
+ fn primitives_wind_outward() {
+ assert_outward(&Geometry::cuboid(1.0, 2.0, 3.0));
+ assert_outward(&Geometry::rounded_box(1.0, 2.0, 3.0, 0.2, 3));
+ assert_outward(&Geometry::sphere(1.0, 16, 8));
+ assert_outward(&Geometry::cylinder(0.5, 1.0, 2.0, 16));
+ assert_outward(&Geometry::cone(1.0, 2.0, 16));
+ assert_outward(&Geometry::capsule(0.5, 1.0, 4, 16));
+ assert_outward(&Geometry::torus(1.0, 0.3, 8, 16));
+ assert_outward(&Geometry::plane(1.0, 1.0));
+ assert_outward(&Geometry::floor(1.0, 1.0));
+ assert_outward(&Geometry::icosahedron(1.0, 1));
+ assert_outward(&Geometry::extrude(&Geometry::polygon(1.0, 6), 0.5, 0.1));
+ assert_outward(&Geometry::extrude(
+ &[
+ Vec2::new(-1.0, -0.5),
+ Vec2::new(1.0, -0.5),
+ Vec2::new(1.0, 0.5),
+ Vec2::new(-1.0, 0.5),
+ ],
+ 0.3,
+ 0.0,
+ ));
+ assert_outward(&Geometry::tube(
+ &[Vec3::ZERO, Vec3::X, Vec3::new(1.0, 1.0, 0.0)],
+ 0.1,
+ 8,
+ ));
+ assert_outward(&Geometry::cuboid(1.0, 1.0, 1.0).scale(-1.0, 1.0, 1.0));
+ }
+
+ #[test]
+ fn rounded_box_keeps_its_size() {
+ let b = Geometry::rounded_box(2.0, 1.0, 0.5, 0.1, 4).bounds();
+ assert!((b.size() - Vec3::new(2.0, 1.0, 0.5)).abs().max_element() < 1e-4);
+ }
+
+ /// A size that an animation drives below zero must not panic in a frame.
+ #[test]
+ fn negative_sizes_do_not_panic() {
+ let b = Geometry::cuboid(-1.0, 0.5, 0.25).bounds();
+ assert!((b.size() - Vec3::new(1.0, 0.5, 0.25)).abs().max_element() < 1e-4);
+ let _ = Geometry::extrude(&Geometry::polygon(-1.0, 6), -0.2, 0.05);
+ }
+
+ #[test]
+ fn concave_shapes_fill() {
+ let l_shape = vec![
+ Vec2::new(0.0, 0.0),
+ Vec2::new(2.0, 0.0),
+ Vec2::new(2.0, 1.0),
+ Vec2::new(1.0, 1.0),
+ Vec2::new(1.0, 2.0),
+ Vec2::new(0.0, 2.0),
+ ];
+ let area: f32 = fill_nonzero(&[l_shape])
+ .iter()
+ .map(|[a, b, c]| (*b - *a).perp_dot(*c - *a) * 0.5)
+ .sum();
+ assert!((area - 3.0).abs() < 1e-5);
+ }
+
+ /// The front cap of each glyph covers the outline once. No triangles overlap, and the
+ /// holes stay open.
+ #[test]
+ fn caps_cover_exactly_the_outline() {
+ let Ok(font) = std::fs::read(concat!(
+ env!("CARGO_MANIFEST_DIR"),
+ "/../examples/conference-splash-screen/media/Inter_18pt-ExtraBold.ttf"
+ )) else {
+ return;
+ };
+ for g in Geometry::text_shapes(&font, "fframes aeo8B@%&gQR", 1.0, 0.0).unwrap() {
+ for shape in &g.shapes {
+ let expected = signed_area(&shape.outer).abs()
+ - shape
+ .holes
+ .iter()
+ .map(|h| signed_area(h).abs())
+ .sum::<f32>();
+ let geometry = Geometry::extrude_shape(shape, 0.2, 0.0, 1);
+ let (mut signed, mut abs) = (0.0, 0.0);
+ for t in geometry.indices.as_chunks::<3>().0 {
+ let [a, b, c] = t.map(|i| i as usize);
+ if [a, b, c].iter().all(|&i| geometry.normals[i] == Vec3::Z) {
+ let z = face_normal([a, b, c].map(|i| geometry.positions[i])).z * 0.5;
+ signed += z;
+ abs += z.abs();
+ }
+ }
+ // No triangle overlaps another or faces the wrong way. The plain polygon
+ // area counts overlaps of font contours two times, so it is only a limit.
+ assert!(
+ (signed - abs).abs() < 1e-4,
+ "{:?}: signed {signed}, abs {abs}",
+ g.ch
+ );
+ assert!(
+ signed <= expected + 1e-3 && signed > expected * 0.8,
+ "{:?}: expected {expected}, got {signed}",
+ g.ch
+ );
+ }
+ }
+ }
+
+ /// Profiles without a segment give an empty geometry, not a panic.
+ #[test]
+ fn short_lathe_profiles_are_empty() {
+ assert_eq!(Geometry::lathe(&[], 16).vertex_count(), 0);
+ assert_eq!(Geometry::lathe(&[Vec2::ONE], 16).vertex_count(), 0);
+ }
+
+ /// The subdivision of three.js: `(detail + 1)²` triangles per face, and no triangle
+ /// samples across the U seam.
+ #[test]
+ fn icosahedron_subdivides_like_three_js() {
+ for detail in [0, 1, 2, 5] {
+ let g = Geometry::icosahedron(1.0, detail);
+ assert_eq!(g.triangle_count(), 20 * (detail as usize + 1).pow(2));
+ assert_outward(&g);
+ // Faces near the poles cover a wide azimuth, and so do the large faces of
+ // detail 0 and 1, as in three.js. The others must not reach across the seam.
+ let away_from_poles =
+ |t: &&[u32; 3]| t.iter().all(|&i| g.positions[i as usize].y.abs() < 0.8);
+ for t in (g.indices.as_chunks::<3>().0.iter())
+ .filter(away_from_poles)
+ .filter(|_| detail >= 2)
+ {
+ let us = t.map(|i| g.uvs[i as usize].x);
+ let span = us.iter().fold(f32::MIN, |a, &b| a.max(b))
+ - us.iter().fold(f32::MAX, |a, &b| a.min(b));
+ assert!(span < 0.25, "detail {detail}: U span {span}");
+ }
+ for p in &g.positions {
+ assert!((p.length() - 1.0).abs() < 1e-5);
+ }
+ }
+ }
+
+ /// V runs down the image: the top of a texture is at the top of a sphere, a cylinder
+ /// and a lathe, as in three.js.
+ #[test]
+ fn textures_are_upright() {
+ let top_v = |g: &Geometry| {
+ let i = (0..g.vertex_count())
+ .filter(|&i| g.normals[i].y.abs() < 0.9)
+ .max_by(|&a, &b| g.positions[a].y.total_cmp(&g.positions[b].y))
+ .unwrap();
+ g.uvs[i].y
+ };
+ // the highest ring with a sideways normal is 2 of 8 rows down
+ assert!(top_v(&Geometry::sphere(1.0, 16, 8)) <= 0.25 + 1e-6);
+ assert!(top_v(&Geometry::cylinder(1.0, 1.0, 2.0, 16)) < 1e-6);
+ assert!(
+ top_v(&Geometry::lathe(
+ &[Vec2::new(1.0, 0.0), Vec2::new(1.0, 1.0)],
+ 16
+ )) < 1e-6
+ );
+ // the side of a cylinder uses the whole texture
+ let side = Geometry::cylinder(1.0, 1.0, 2.0, 16);
+ let vs: Vec<f32> = (0..side.vertex_count())
+ .filter(|&i| side.normals[i].y.abs() < 0.5)
+ .map(|i| side.uvs[i].y)
+ .collect();
+ assert_eq!(vs.iter().fold(f32::MAX, |a, &b| a.min(b)), 0.0);
+ assert_eq!(vs.iter().fold(f32::MIN, |a, &b| a.max(b)), 1.0);
+ }
+
+ #[test]
+ fn out_of_range_indices_are_dropped() {
+ let g = Geometry::new(
+ vec![Vec3::ZERO, Vec3::X, Vec3::Y],
+ Vec::new(),
+ Vec::new(),
+ vec![0, 1, 2, 0, 1, 7, 2],
+ );
+ assert_eq!(g.indices, vec![0, 1, 2]);
+ let _ = g.clone().flat().smooth(30.0);
+ }
+
+ /// Variable fonts keep overlapping contours. Both directions of font outlines must
+ /// fill their union, without turning the overlap into a hole.
+ #[test]
+ fn overlapping_contours_stay_solid() {
+ let square = |o: f32| {
+ vec![
+ Vec2::new(o, o),
+ Vec2::new(o + 2.0, o),
+ Vec2::new(o + 2.0, o + 2.0),
+ Vec2::new(o, o + 2.0),
+ ]
+ };
+ let hole = vec![
+ Vec2::new(0.5, 0.5),
+ Vec2::new(0.5, 0.8),
+ Vec2::new(0.8, 0.8),
+ Vec2::new(0.8, 0.5),
+ ];
+ for flip in [false, true] {
+ let mut contours = vec![square(0.0), square(1.0), hole.clone()];
+ if flip {
+ for c in &mut contours {
+ c.reverse();
+ }
+ }
+ let shapes = shapes_from_contours(contours);
+ assert_eq!(shapes.len(), 2, "flip {flip}");
+ assert_eq!(shapes.iter().map(|s| s.holes.len()).sum::<usize>(), 1);
+ }
+ }
+
+ /// Welding keeps the U seam of a sphere: no triangle samples across it.
+ #[test]
+ fn smooth_keeps_uv_seams() {
+ let g = Geometry::sphere(1.0, 16, 8).flat().smooth(60.0);
+ for t in g.indices.as_chunks::<3>().0 {
+ let us = t.map(|i| g.uvs[i as usize].x);
+ let span = us.iter().fold(f32::MIN, |a, &b| a.max(b))
+ - us.iter().fold(f32::MAX, |a, &b| a.min(b));
+ assert!(span < 0.5, "U span {span}");
+ }
+ }
+
+ #[test]
+ fn transform_moves_morph_targets() {
+ let mut g = Geometry::plane(1.0, 1.0);
+ g.morph_targets.push(MorphTarget {
+ name: None,
+ positions: vec![Vec3::X; 4],
+ normals: Vec::new(),
+ });
+ let g = g.rotate_z(FRAC_PI_2).translate(5.0, 0.0, 0.0);
+ let d = g.morph_targets[0].positions[0];
+ assert!((d - Vec3::Y).length() < 1e-5, "{d}");
+ }
+
+ #[test]
+ fn degenerate_sizes_give_finite_uvs() {
+ for g in [Geometry::cuboid(0.0, 1.0, 1.0), Geometry::circle(0.0, 8)] {
+ assert!(g.uvs.iter().all(|uv| uv.is_finite()));
+ }
+ }
+}
diff --git a/fframes-three-d/src/gltf.rs b/fframes-three-d/src/gltf.rs
new file mode 100644
index 00000000..e9fbc7d7
--- /dev/null
+++ b/fframes-three-d/src/gltf.rs
@@ -0,0 +1,540 @@
+//! glTF 2.0 models, the format that three.js loads with `GLTFLoader`.
+//!
+//! The loader reads `.glb` files and `.gltf` files with embedded buffers. It reads meshes,
+//! PBR materials and textures, node hierarchies, skins, morph targets, animations and
+//! punctual lights.
+//!
+//! Not supported: cameras, the texture coordinates of sets other than 0, sampler wrap modes
+//! (textures repeat), `KHR_texture_transform` and the other material extensions. A
+//! `MASK` material blends instead of cutting at `alphaCutoff`.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use base64::Engine;
+use glam::{Mat4, Quat, Vec2, Vec3, Vec4};
+use gltf::animation::util::ReadOutputs;
+
+use crate::animation::{AnimationClip, Channel, Interpolation, Keyframes};
+use crate::geometry::{MorphTarget, SkinWeights};
+use crate::math::Aabb;
+use crate::scene::Skin;
+use crate::{Geometry, Light, Material, Node, NodeId, Rgb, Scene, Shading, Side, Texture};
+
+/// The reason why a model does not load.
+#[derive(Debug)]
+pub enum ModelError {
+ /// The file is not valid glTF.
+ Gltf(gltf::Error),
+ /// A buffer or an image refers to a file that is not available, or its data URI does
+ /// not decode.
+ MissingFile(String),
+ /// A texture image does not decode.
+ Image(image::ImageError),
+}
+
+impl std::fmt::Display for ModelError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ ModelError::Gltf(e) => write!(f, "invalid glTF: {e}"),
+ ModelError::MissingFile(uri) => {
+ write!(f, "glTF refers to a file that was not provided: {uri}")
+ }
+ ModelError::Image(e) => write!(f, "cannot decode a glTF texture: {e}"),
+ }
+ }
+}
+
+impl std::error::Error for ModelError {}
+
+impl From<gltf::Error> for ModelError {
+ fn from(e: gltf::Error) -> Self {
+ ModelError::Gltf(e)
+ }
+}
+
+impl From<image::ImageError> for ModelError {
+ fn from(e: image::ImageError) -> Self {
+ ModelError::Image(e)
+ }
+}
+
+/// A glTF model: its nodes as a [`Scene`] and its animations.
+///
+/// Load the model once, and add it to the scene of each frame with [`Model::add_to`].
+///
+/// ```rust,ignore
+/// let robot = Model::from_gltf(include_bytes!("RobotExpressive.glb"))?;
+/// let dance = robot.animation("Dance").unwrap();
+///
+/// // in render_frame
+/// let mut scene = self.stage.clone();
+/// let instance = self.robot.add_to(&mut scene, None);
+/// scene[instance.root].scale = Vec3::splat(0.5);
+/// instance.play(&mut scene, dance, frame.seconds());
+/// ```
+#[derive(Debug, Clone)]
+pub struct Model {
+ pub scene: Scene,
+ pub animations: Vec<AnimationClip>,
+}
+
+/// A model in a scene. Model node `NodeId(i)` is `NodeId(i + offset)` in the scene.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct ModelInstance {
+ /// The group that holds the model. Move, turn and scale the whole model with it.
+ pub root: NodeId,
+ /// The difference between the scene ids and the model ids.
+ pub offset: u32,
+ /// The number of model nodes.
+ pub len: u32,
+}
+
+impl ModelInstance {
+ /// The scene id of a model node.
+ pub fn node(&self, model_node: NodeId) -> NodeId {
+ NodeId(model_node.0 + self.offset)
+ }
+
+ /// The scene id of the first node of this instance with this name.
+ pub fn find(&self, scene: &Scene, name: &str) -> Option<NodeId> {
+ (self.offset..self.offset + self.len)
+ .map(NodeId)
+ .find(|id| scene.get(*id).and_then(|n| n.name.as_deref()) == Some(name))
+ }
+
+ /// Plays `clip` at `time` seconds, looped.
+ pub fn play(&self, scene: &mut Scene, clip: &AnimationClip, time: f32) {
+ self.blend(scene, clip, time, 1.0);
+ }
+
+ /// Blends `clip` at `time` seconds, looped, over the current pose. `weight` is `0..1`.
+ pub fn blend(&self, scene: &mut Scene, clip: &AnimationClip, time: f32, weight: f32) {
+ clip.apply_looped(scene, self.offset, time, weight);
+ }
+}
+
+impl Model {
+ /// Loads a `.glb` file, or a `.gltf` file with its buffers and images embedded as data
+ /// URIs.
+ pub fn from_gltf(bytes: &[u8]) -> Result<Self, ModelError> {
+ Self::from_gltf_with(bytes, |_| None)
+ }
+
+ /// Loads a glTF file and reads external buffers and images with `resolve`. `resolve`
+ /// gets each `uri` relative to the `.gltf` file.
+ pub fn from_gltf_with(
+ bytes: &[u8],
+ resolve: impl Fn(&str) -> Option<Vec<u8>>,
+ ) -> Result<Self, ModelError> {
+ let gltf = gltf::Gltf::from_slice(bytes)?;
+ let load_uri = |uri: &str| {
+ let missing = || ModelError::MissingFile(uri.to_owned());
+ match uri.strip_prefix("data:") {
+ Some(data) => {
+ let base64 = data.split_once(";base64,").map_or("", |(_, d)| d);
+ base64::engine::general_purpose::STANDARD
+ .decode(base64)
+ .map_err(|_| missing())
+ }
+ None => resolve(uri).ok_or_else(missing),
+ }
+ };
+
+ let buffers = gltf
+ .buffers()
+ .map(|buffer| match buffer.source() {
+ gltf::buffer::Source::Bin => Ok(gltf.blob.clone().unwrap_or_default()),
+ gltf::buffer::Source::Uri(uri) => load_uri(uri),
+ })
+ .collect::<Result<Vec<_>, _>>()?;
+
+ let decode = |bytes: &[u8]| -> Result<_, ModelError> {
+ Ok(Arc::new(image::load_from_memory(bytes)?.to_rgba8()))
+ };
+ let images = gltf
+ .images()
+ .map(|image| match image.source() {
+ gltf::image::Source::View { view, .. } => buffers[view.buffer().index()]
+ .get(view.offset()..view.offset() + view.length())
+ .map(decode)
+ .transpose(),
+ // An image file that is not available leaves its textures out.
+ gltf::image::Source::Uri { uri, .. } => {
+ load_uri(uri).ok().map(|bytes| decode(&bytes)).transpose()
+ }
+ })
+ .collect::<Result<Vec<_>, _>>()?;
+
+ let mut loader = Loader {
+ buffers: &buffers,
+ images: &images,
+ textures: HashMap::new(),
+ scene: Scene::new(),
+ node_ids: HashMap::new(),
+ mesh_nodes: Vec::new(),
+ };
+ let roots: Vec<gltf::Node> =
+ if let Some(scene) = gltf.default_scene().or_else(|| gltf.scenes().next()) {
+ scene.nodes().collect()
+ } else {
+ // without scenes, the nodes that are nobody's child
+ let children: std::collections::HashSet<usize> = gltf
+ .nodes()
+ .flat_map(|n| n.children().map(|c| c.index()))
+ .collect();
+ gltf.nodes()
+ .filter(|n| !children.contains(&n.index()))
+ .collect()
+ };
+ for root in roots {
+ loader.add_node(&root, None);
+ }
+ loader.add_skins();
+ let animations = gltf.animations().map(|a| loader.animation(&a)).collect();
+ Ok(Model {
+ scene: loader.scene,
+ animations,
+ })
+ }
+
+ /// The animation clip with this name.
+ pub fn animation(&self, name: &str) -> Option<&AnimationClip> {
+ self.animations.iter().find(|a| a.name == name)
+ }
+
+ /// Adds the model below `parent`, or at the root for `None`. A new group node holds the
+ /// model and is the root of the instance.
+ pub fn add_to(&self, scene: &mut Scene, parent: Option<NodeId>) -> ModelInstance {
+ let root = scene.insert(parent, Node::group());
+ let offset = scene.append(Some(root), &self.scene);
+ ModelInstance {
+ root,
+ offset,
+ len: self.scene.len() as u32,
+ }
+ }
+
+ /// The bounds of the model in its rest pose.
+ pub fn bounds(&self) -> Aabb {
+ self.scene
+ .nodes()
+ .filter(|(_, node)| node.parent().is_none())
+ .fold(Aabb::EMPTY, |aabb, (id, _)| {
+ aabb.union(self.scene.bounds(id))
+ })
+ }
+}
+
+/// Builds the [`Scene`] of a model from the glTF nodes.
+struct Loader<'a, 'g> {
+ buffers: &'a [Vec<u8>],
+ images: &'a [Option<Arc<image::RgbaImage>>],
+ /// The textures by image index and color space (`true` for sRGB).
+ textures: HashMap<(usize, bool), Arc<Texture>>,
+ scene: Scene,
+ /// The scene ids of the glTF nodes, by glTF node index.
+ node_ids: HashMap<usize, NodeId>,
+ /// The glTF nodes with meshes, for [`Loader::add_skins`].
+ mesh_nodes: Vec<(NodeId, gltf::Node<'g>)>,
+}
+
+impl<'g> Loader<'_, 'g> {
+ /// Adds a glTF node and its subtree below `parent`. As in three.js, a node with one
+ /// mesh primitive is the mesh. A node with several primitives is a group with one mesh
+ /// child for each. A light is a child node.
+ fn add_node(&mut self, gltf_node: &gltf::Node<'g>, parent: Option<NodeId>) {
+ // A node is in the tree once. A broken file whose node is its own descendant would
+ // recurse forever.
+ if self.node_ids.contains_key(&gltf_node.index()) {
+ return;
+ }
+ let (t, r, s) = gltf_node.transform().decomposed();
+ let meshes: Vec<Node> = gltf_node.mesh().map_or_else(Vec::new, |mesh| {
+ // the node overrides the default weights of the mesh
+ let weights = gltf_node.weights().or(mesh.weights()).unwrap_or_default();
+ mesh.primitives()
+ .filter(|p| p.mode() == gltf::mesh::Mode::Triangles)
+ .map(|primitive| {
+ let mut node = self.mesh_node(&primitive);
+ if let Some(mesh) = node.mesh_mut() {
+ mesh.morph_weights = weights.to_vec();
+ }
+ node
+ })
+ .collect()
+ });
+ let (base, meshes) = match <[Node; 1]>::try_from(meshes) {
+ Ok([mesh]) => (mesh, Vec::new()),
+ Err(meshes) => (Node::group(), meshes),
+ };
+ let node = Node {
+ name: gltf_node.name().map(Into::into),
+ position: Vec3::from(t),
+ rotation: Quat::from_array(r).normalize(),
+ scale: Vec3::from(s),
+ ..base
+ };
+ let id = self.scene.insert(parent, node);
+ self.node_ids.insert(gltf_node.index(), id);
+
+ if let Some(light) = gltf_node.light() {
+ self.scene.add_to(id, Node::light(convert_light(&light)));
+ }
+ for mesh in meshes {
+ self.scene.add_to(id, mesh);
+ }
+ if gltf_node.mesh().is_some() {
+ self.mesh_nodes.push((id, gltf_node.clone()));
+ }
+
+ for child in gltf_node.children() {
+ self.add_node(&child, Some(id));
+ }
+ }
+
+ /// Gives the skinned meshes their skins. It runs after all nodes have ids, because a
+ /// skin refers to its joints by id.
+ fn add_skins(&mut self) {
+ let buffers = self.buffers;
+ for (id, gltf_node) in std::mem::take(&mut self.mesh_nodes) {
+ let Some(skin) = gltf_node.skin() else {
+ continue;
+ };
+ let reader = skin.reader(|b| buffers.get(b.index()).map(Vec::as_slice));
+ let inverse_bind_matrices = reader
+ .read_inverse_bind_matrices()
+ .map(|m| m.map(|m| Mat4::from_cols_array_2d(&m)).collect())
+ .unwrap_or_default();
+ let joints = skin
+ .joints()
+ .map(|j| self.node_ids.get(&j.index()).copied().unwrap_or(NodeId(0)))
+ .collect();
+ let skin = Skin {
+ joints,
+ inverse_bind_matrices: Arc::new(inverse_bind_matrices),
+ };
+ for target in self.scene.descendants(id) {
+ if let Some(mesh) = self.scene[target].mesh_mut()
+ && mesh.geometry.skin.is_some()
+ {
+ mesh.skin = Some(skin.clone());
+ }
+ }
+ }
+ }
+
+ /// Reads an animation. It leaves out the channels of nodes outside the scene.
+ fn animation(&self, animation: &gltf::Animation) -> AnimationClip {
+ let buffers = self.buffers;
+ let mut channels = Vec::new();
+ let mut duration: f32 = 0.0;
+ for channel in animation.channels() {
+ let Some(&node) = self.node_ids.get(&channel.target().node().index()) else {
+ continue;
+ };
+ let reader = channel.reader(|b| buffers.get(b.index()).map(Vec::as_slice));
+ let Some(times) = reader.read_inputs().map(Iterator::collect::<Vec<f32>>) else {
+ continue;
+ };
+ duration = duration.max(times.last().copied().unwrap_or(0.0));
+ let Some(outputs) = reader.read_outputs() else {
+ continue;
+ };
+ let interpolation = match channel.sampler().interpolation() {
+ gltf::animation::Interpolation::Step => Interpolation::Step,
+ gltf::animation::Interpolation::Linear => Interpolation::Linear,
+ gltf::animation::Interpolation::CubicSpline => Interpolation::CubicSpline,
+ };
+ let keyframes = match outputs {
+ ReadOutputs::Translations(t) => Keyframes::Translation(t.map(Vec3::from).collect()),
+ ReadOutputs::Scales(s) => Keyframes::Scale(s.map(Vec3::from).collect()),
+ ReadOutputs::Rotations(r) => {
+ Keyframes::Rotation(r.into_f32().map(Quat::from_array).collect())
+ }
+ ReadOutputs::MorphTargetWeights(w) => {
+ let values: Vec<f32> = w.into_f32().collect();
+ let per_keyframe = values.len().checked_div(times.len()).unwrap_or(0);
+ // A cubic spline stores an in tangent, a value and an out tangent.
+ let targets = match interpolation {
+ Interpolation::CubicSpline => per_keyframe / 3,
+ _ => per_keyframe,
+ };
+ Keyframes::Weights { targets, values }
+ }
+ };
+ channels.push(Channel {
+ node,
+ interpolation,
+ times,
+ keyframes,
+ });
+ }
+ AnimationClip {
+ name: animation.name().unwrap_or_default().to_owned(),
+ duration,
+ channels,
+ }
+ }
+
+ /// A mesh node of a primitive. A primitive without normals is flat shaded, as the
+ /// glTF specification asks.
+ fn mesh_node(&mut self, primitive: &gltf::Primitive) -> Node {
+ let geometry = self.geometry(primitive);
+ let mut material = self.material(&primitive.material());
+ material.flat_shading |= primitive.get(&gltf::Semantic::Normals).is_none();
+ Node::mesh(geometry, material)
+ }
+
+ fn geometry(&self, primitive: &gltf::Primitive) -> Geometry {
+ let reader = primitive.reader(|b| self.buffers.get(b.index()).map(Vec::as_slice));
+ let positions = vec3s(reader.read_positions());
+ let indices: Vec<u32> = reader.read_indices().map_or_else(
+ || (0..positions.len() as u32).collect(),
+ |i| i.into_u32().collect(),
+ );
+ let normals = vec3s(reader.read_normals());
+ let uvs: Vec<Vec2> = reader
+ .read_tex_coords(0)
+ .map(|uv| uv.into_f32().map(Vec2::from).collect())
+ .unwrap_or_default();
+ let mut geometry = Geometry::new(positions, normals, uvs, indices);
+ if let Some(colors) = reader.read_colors(0) {
+ geometry.colors = colors.into_rgba_f32().map(Vec4::from).collect();
+ }
+ if let (Some(joints), Some(weights)) = (reader.read_joints(0), reader.read_weights(0)) {
+ // The weights of each vertex add up to 1.
+ let normalize = |w: [f32; 4]| {
+ let sum: f32 = w.iter().sum();
+ if sum > 0.0 {
+ w.map(|x| x / sum)
+ } else {
+ [1.0, 0.0, 0.0, 0.0]
+ }
+ };
+ geometry.skin = Some(SkinWeights {
+ joints: joints.into_u16().collect(),
+ weights: weights.into_f32().map(normalize).collect(),
+ });
+ }
+ geometry
+ .morph_targets
+ .extend(
+ reader
+ .read_morph_targets()
+ .map(|(positions, normals, _)| MorphTarget {
+ name: None,
+ positions: vec3s(positions),
+ normals: vec3s(normals),
+ }),
+ );
+ geometry
+ }
+
+ /// The texture of a glTF image in a color space. Each pair decodes once.
+ fn texture(&mut self, texture: &gltf::Texture, srgb: bool) -> Option<Arc<Texture>> {
+ let index = texture.source().index();
+ if let Some(texture) = self.textures.get(&(index, srgb)) {
+ return Some(Arc::clone(texture));
+ }
+ let image = self.images.get(index)?.as_ref()?;
+ let texture = Arc::new(Texture::from_rgba8(
+ image.width(),
+ image.height(),
+ image.as_raw(),
+ srgb,
+ ));
+ self.textures.insert((index, srgb), Arc::clone(&texture));
+ Some(texture)
+ }
+
+ fn material(&mut self, material: &gltf::Material) -> Material {
+ use gltf::material::AlphaMode;
+
+ let pbr = material.pbr_metallic_roughness();
+ let [r, g, b, a] = pbr.base_color_factor();
+ let [er, eg, eb] = material.emissive_factor();
+ let alpha_mode = material.alpha_mode();
+ let normal = material.normal_texture();
+ Material {
+ shading: if material.unlit() {
+ Shading::Unlit
+ } else {
+ Shading::Standard
+ },
+ color: Rgb::linear(r, g, b),
+ // an OPAQUE material ignores alpha
+ opacity: if alpha_mode == AlphaMode::Opaque {
+ 1.0
+ } else {
+ a
+ },
+ metalness: pbr.metallic_factor(),
+ roughness: pbr.roughness_factor(),
+ emissive: Rgb::linear(er, eg, eb),
+ emissive_intensity: material.emissive_strength().unwrap_or(1.0),
+ side: if material.double_sided() {
+ Side::Double
+ } else {
+ Side::Front
+ },
+ transparent: alpha_mode != AlphaMode::Opaque,
+ // the cut out parts of a MASK material hide what is behind them
+ depth_write: alpha_mode == AlphaMode::Mask,
+ map: pbr
+ .base_color_texture()
+ .and_then(|info| self.texture(&info.texture(), true)),
+ metal_rough_map: pbr
+ .metallic_roughness_texture()
+ .and_then(|info| self.texture(&info.texture(), false)),
+ emissive_map: material
+ .emissive_texture()
+ .and_then(|info| self.texture(&info.texture(), true)),
+ normal_scale: normal
+ .as_ref()
+ .map_or(1.0, gltf::material::NormalTexture::scale),
+ normal_map: normal.and_then(|info| self.texture(&info.texture(), false)),
+ ao_map: material
+ .occlusion_texture()
+ .and_then(|info| self.texture(&info.texture(), false)),
+ ..Default::default()
+ }
+ }
+}
+
+/// Reads a glTF vector attribute. A missing attribute gives no values.
+fn vec3s(values: Option<impl Iterator<Item = [f32; 3]>>) -> Vec<Vec3> {
+ values
+ .map(|v| v.map(Vec3::from).collect())
+ .unwrap_or_default()
+}
+
+/// Converts a `KHR_lights_punctual` light. glTF lights shine down -Z of their node.
+fn convert_light(light: &gltf::khr_lights_punctual::Light) -> Light {
+ let color = Rgb::from(light.color());
+ let intensity = light.intensity();
+ let light_range = light.range();
+ match light.kind() {
+ gltf::khr_lights_punctual::Kind::Directional => {
+ Light::directional(color, intensity, Vec3::Z)
+ }
+ gltf::khr_lights_punctual::Kind::Point => {
+ Light::point(color, intensity, light.range().unwrap_or(0.0))
+ }
+ gltf::khr_lights_punctual::Kind::Spot {
+ outer_cone_angle,
+ inner_cone_angle,
+ } => {
+ let penumbra = if outer_cone_angle > 0.0 {
+ 1.0 - inner_cone_angle / outer_cone_angle
+ } else {
+ 0.0
+ };
+ let mut spot = Light::spot(color, intensity, outer_cone_angle, penumbra);
+ if let Light::Spot(light) = &mut spot {
+ light.distance = light_range.unwrap_or(0.0);
+ }
+ spot.pointing(Vec3::NEG_Z)
+ }
+ }
+}
diff --git a/fframes-three-d/src/gpu/mod.rs b/fframes-three-d/src/gpu/mod.rs
new file mode 100644
index 00000000..e5ead9c2
--- /dev/null
+++ b/fframes-three-d/src/gpu/mod.rs
@@ -0,0 +1,2732 @@
+//! The GPU renderer (feature `gpu`). It draws the same scenes, materials and lights as the
+//! software rasterizer, with wgpu on Vulkan, Metal or DX12.
+//!
+//! The rendering backend can share its GPU (`fframes::shared_gpu`). The Skia Vulkan backend
+//! does this with its `wgpu` feature. Then a frame renders on that device into a texture.
+//! The backend samples this texture in place (`fframes::wgpu_layer`). The renderer reads
+//! nothing back. The frame stays on the GPU through Skia to the encoder. Without a shared
+//! GPU, frames render on a device of their own. Then the renderer reads the pixels back.
+//!
+//! The renderer uploads rigid meshes once and draws them with their world matrix. It deforms
+//! skinned and morphed meshes on the CPU and streams their vertices every frame.
+//!
+//! The passes of one moment:
+//! 1. the shadow maps,
+//! 2. the reflection, when a material reflects the scene,
+//! 3. a 4x multisampled geometry pass into an HDR target and a depth key: the background,
+//! the opaque meshes, the blended meshes from back to front, the particles,
+//! 4. the depth of field,
+//! 5. the motion blur accumulation.
+//!
+//! After the moments, the frame gets bloom and tone mapping. The last pass encodes
+//! premultiplied sRGB pixels.
+
+use std::collections::HashMap;
+use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, PoisonError, Weak};
+
+use bytemuck::{Pod, Zeroable};
+use fframes_media::wgpu_layer::{self, SharedGpu};
+use glam::{Mat3, Mat4, Vec3, Vec4};
+use wgpu::util::DeviceExt;
+
+use crate::material::Shading;
+use crate::render::prepare::{self, LightInfo, LightKind, Lights};
+use crate::render::shadow::fit;
+use crate::render::{Pixels, Renderer, ToneMapping};
+use crate::scene::{Background, Fog, Object};
+use crate::{Blending, Camera, Environment, Geometry, Material, Mesh, Scene, Side, Texture};
+
+const MSAA: u32 = 4;
+const HDR: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
+/// The format of the depth key (1 / view distance) that the depth of field reads.
+const KEY: wgpu::TextureFormat = wgpu::TextureFormat::R16Float;
+const DEPTH: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;
+const OUTPUT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
+const MAX_LIGHTS: usize = 16;
+const MAX_SOFTBOXES: usize = 8;
+const MAX_SHADOWS: usize = 2;
+/// The alignment of uniform buffer offsets that all devices support.
+const UNIFORM_ALIGNMENT: u64 = 256;
+/// The distance between two draw uniforms in the draw buffer.
+const DRAW_STRIDE: u64 = (size_of::<DrawUniform>() as u64).next_multiple_of(UNIFORM_ALIGNMENT);
+/// The number of uniform slots in the post buffer. Slot 0 belongs to the passes of a moment.
+const POST_SLOTS: u64 = 32;
+/// The first post slot of the reflection levels. The frame passes use the slots below it.
+const REFLECTION_SLOT: u64 = 24;
+/// The size of a depth of field tile in pixels.
+const DOF_TILE: u32 = 16;
+const BLOOM_LEVELS: usize = 6;
+/// The maximum number of frame contexts (render targets) in use at the same time.
+const CONTEXTS: usize = 3;
+/// Rigid meshes with this many indices or fewer that share a material become one batch.
+/// A draw costs the same with six triangles or six thousand.
+const BATCH_MAX_INDICES: u32 = 4096;
+
+/// Adds the color and keeps the alpha of the target, for glows and additive particles.
+const ADD_LIGHT: wgpu::BlendState = wgpu::BlendState {
+ color: wgpu::BlendComponent {
+ src_factor: wgpu::BlendFactor::One,
+ dst_factor: wgpu::BlendFactor::One,
+ operation: wgpu::BlendOperation::Add,
+ },
+ alpha: wgpu::BlendComponent {
+ src_factor: wgpu::BlendFactor::Zero,
+ dst_factor: wgpu::BlendFactor::One,
+ operation: wgpu::BlendOperation::Add,
+ },
+};
+
+/// Maps clip space z to `w - z`: near is 1 and far is 0. This keeps the depth precise in 32
+/// bit floats.
+const REVERSED_Z: Mat4 = Mat4::from_cols(
+ Vec4::X,
+ Vec4::Y,
+ Vec4::new(0.0, 0.0, -1.0, 0.0),
+ Vec4::new(0.0, 0.0, 1.0, 1.0),
+);
+
+// The uniform layouts. Each one matches a struct in the WGSL files, which describe the fields.
+
+/// `Light` in `scene.wgsl`.
+#[repr(C)]
+#[derive(Clone, Copy, Pod, Zeroable)]
+struct GpuLight {
+ color: [f32; 4],
+ position: [f32; 4],
+ direction: [f32; 4],
+ params: [f32; 4],
+}
+
+/// `SoftBox` in `scene.wgsl`.
+#[repr(C)]
+#[derive(Clone, Copy, Pod, Zeroable)]
+struct GpuSoftBox {
+ direction: [f32; 4],
+ color: [f32; 4],
+}
+
+/// `Shadow` in `scene.wgsl`.
+#[repr(C)]
+#[derive(Clone, Copy, Pod, Zeroable)]
+struct GpuShadow {
+ view_proj: [f32; 16],
+ params: [f32; 4],
+ params2: [f32; 4],
+}
+
+/// `Frame` in `scene.wgsl`.
+#[repr(C)]
+#[derive(Clone, Copy, Pod, Zeroable)]
+struct FrameUniform {
+ view_proj: [f32; 16],
+ inv_view_proj: [f32; 16],
+ view_proj_rel: [f32; 16],
+ camera: [f32; 4],
+ forward: [f32; 4],
+ viewport: [f32; 4],
+ ambient: [f32; 4],
+ hemi_sky: [f32; 4],
+ hemi_ground: [f32; 4],
+ fog: [f32; 4],
+ fog_params: [f32; 4],
+ env: [f32; 4],
+ env_sky: [f32; 4],
+ env_horizon: [f32; 4],
+ env_ground: [f32; 4],
+ background: [f32; 4],
+ background_color: [f32; 4],
+ counts: [f32; 4],
+ clip_plane: [f32; 4],
+ lights: [GpuLight; MAX_LIGHTS],
+ softboxes: [GpuSoftBox; MAX_SOFTBOXES],
+ shadows: [GpuShadow; MAX_SHADOWS],
+}
+
+/// `Draw` in `scene.wgsl`.
+#[repr(C)]
+#[derive(Clone, Copy, Pod, Zeroable)]
+struct DrawUniform {
+ model: [f32; 16],
+ normal_matrix: [f32; 16],
+ color: [f32; 4],
+ emissive: [f32; 4],
+ pbr: [f32; 4],
+ flags: [f32; 4],
+ maps: [f32; 4],
+ attrs: [f32; 4],
+ /// The repeat and offset of each map: color, emissive, metal-rough, normal, occlusion.
+ uv_transforms: [[f32; 4]; 5],
+ detail: [f32; 4],
+}
+
+/// `Post` in `post.wgsl`.
+#[repr(C)]
+#[derive(Clone, Copy, Pod, Zeroable, Default)]
+struct PostUniform {
+ dof: [f32; 4],
+ bloom: [f32; 4],
+ encode: [f32; 4],
+ texel: [f32; 4],
+}
+
+/// `VertexIn` in `scene.wgsl`.
+#[repr(C)]
+#[derive(Clone, Copy, Pod, Zeroable)]
+struct Vertex {
+ position: [f32; 3],
+ normal: [f32; 3],
+ uv: [f32; 2],
+ color: [f32; 4],
+}
+
+/// One copy of a mesh, `InstanceIn` in `scene.wgsl`. Entry 0 of the instance buffer is the
+/// identity, which every mesh without copies uses.
+#[repr(C)]
+#[derive(Clone, Copy, Pod, Zeroable)]
+struct InstanceData {
+ model: [f32; 16],
+ /// The normal matrix, as three columns padded to four floats.
+ normal: [f32; 12],
+ color: [f32; 4],
+}
+
+impl InstanceData {
+ fn new(model: Mat4, color: Vec4) -> Self {
+ let n = Mat3::from_mat4(model).inverse().transpose();
+ Self {
+ model: model.to_cols_array(),
+ normal: [n.x_axis, n.y_axis, n.z_axis]
+ .map(|c| c.extend(0.0).to_array())
+ .concat()
+ .try_into()
+ .unwrap_or([0.0; 12]),
+ color: color.to_array(),
+ }
+ }
+}
+
+/// The per copy attributes of the geometry pipelines, at locations 4 to 11.
+const INSTANCE_ATTRIBUTES: [wgpu::VertexAttribute; 8] = wgpu::vertex_attr_array![
+ 4 => Float32x4, 5 => Float32x4, 6 => Float32x4, 7 => Float32x4,
+ 8 => Float32x4, 9 => Float32x4, 10 => Float32x4, 11 => Float32x4,
+];
+
+/// The model matrix of a copy, for the shadow pipeline, at locations 1 to 4.
+const SHADOW_INSTANCE_ATTRIBUTES: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![
+ 1 => Float32x4, 2 => Float32x4, 3 => Float32x4, 4 => Float32x4,
+];
+
+fn instance_layout(attributes: &[wgpu::VertexAttribute]) -> wgpu::VertexBufferLayout<'_> {
+ wgpu::VertexBufferLayout {
+ array_stride: size_of::<InstanceData>() as u64,
+ step_mode: wgpu::VertexStepMode::Instance,
+ attributes,
+ }
+}
+
+/// `ParticleIn` in `scene.wgsl`.
+#[repr(C)]
+#[derive(Clone, Copy, Pod, Zeroable)]
+struct ParticleInstance {
+ position: [f32; 4],
+ color: [f32; 4],
+}
+
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
+enum Blend {
+ Opaque,
+ Normal,
+ Additive,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
+struct PipelineKey {
+ cull: Option<wgpu::Face>,
+ blend: Blend,
+ depth_write: bool,
+ variant: Variant,
+ /// Draws into the reflection: one sample, and nothing behind the plane of the reflector.
+ reflection_pass: bool,
+}
+
+/// The pipeline constants of a material (the `override`s of `scene.wgsl`). One shader for
+/// all materials is too large to run at full SIMD width.
+///
+/// The field order sets the draw order of the opaque meshes (see [`draw_order`]).
+#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
+struct Variant {
+ shading: u8,
+ environment: u8,
+ clearcoat: bool,
+ textured: bool,
+ fog: bool,
+ lights: u8,
+ reflection: bool,
+ normal_map: bool,
+}
+
+impl Variant {
+ /// The variant of a material. The light count stays 0, because it is known only after
+ /// all nodes.
+ fn new(m: &Material, has_uv: bool, scene: &Scene) -> Self {
+ Self {
+ lights: 0,
+ shading: match m.shading {
+ Shading::Standard => 0,
+ Shading::Unlit => 1,
+ Shading::ShadowCatcher => 2,
+ Shading::Normals => 3,
+ },
+ environment: match scene.environment {
+ Environment::None => 0,
+ Environment::Studio(_) => 1,
+ Environment::Map { .. } => 2,
+ },
+ clearcoat: m.clearcoat > 0.0,
+ textured: has_uv
+ && (m.map.is_some()
+ || m.emissive_map.is_some()
+ || m.metal_rough_map.is_some()
+ || m.ao_map.is_some()),
+ fog: m.fog && scene.fog.is_some(),
+ reflection: m.reflection > 0.0 && scene.reflector.is_some(),
+ normal_map: has_uv && m.normal_map.is_some(),
+ }
+ }
+
+ fn constants(self, reflection_pass: bool) -> [(&'static str, f64); 9] {
+ [
+ ("LIGHTS", f64::from(self.lights)),
+ ("REFLECTION", f64::from(self.reflection && !reflection_pass)),
+ ("REFLECTION_PASS", f64::from(reflection_pass)),
+ ("SHADING", f64::from(self.shading)),
+ ("ENVIRONMENT", f64::from(self.environment)),
+ ("CLEARCOAT", f64::from(self.clearcoat)),
+ ("TEXTURED", f64::from(self.textured)),
+ ("FOG", f64::from(self.fog)),
+ ("NORMAL_MAP", f64::from(self.normal_map)),
+ ]
+ }
+}
+
+struct GpuMesh {
+ geometry: Weak<Geometry>,
+ vertices: wgpu::Buffer,
+ indices: wgpu::Buffer,
+ index_count: u32,
+}
+
+struct GpuTexture {
+ source: Weak<Texture>,
+ view: wgpu::TextureView,
+}
+
+struct EnvMapTexture {
+ source: Weak<crate::EnvironmentMap>,
+ view: wgpu::TextureView,
+ levels: u32,
+}
+
+/// The free frame contexts and the number of contexts made so far.
+struct ContextPool {
+ free: Vec<FrameContext>,
+ created: usize,
+}
+
+pub(crate) struct Gpu {
+ device: wgpu::Device,
+ queue: wgpu::Queue,
+ /// The queue lock of the backend, when the backend shares the device.
+ queue_lock: Option<Arc<Mutex<()>>>,
+ scene_module: wgpu::ShaderModule,
+ frame_layout: wgpu::BindGroupLayout,
+ draw_layout: wgpu::BindGroupLayout,
+ shadow_layout: wgpu::BindGroupLayout,
+ shadow_draw_layout: wgpu::BindGroupLayout,
+ post_layout: wgpu::BindGroupLayout,
+ scene_pipeline_layout: wgpu::PipelineLayout,
+ pipelines: Mutex<HashMap<PipelineKey, wgpu::RenderPipeline>>,
+ shadow_pipeline: wgpu::RenderPipeline,
+ background_pipeline: wgpu::RenderPipeline,
+ /// The background pipeline of the reflection (one sample).
+ background_1x: wgpu::RenderPipeline,
+ particle_additive: wgpu::RenderPipeline,
+ particle_normal: wgpu::RenderPipeline,
+ post: PostPipelines,
+ linear_repeat: wgpu::Sampler,
+ linear_clamp: wgpu::Sampler,
+ env_sampler: wgpu::Sampler,
+ shadow_sampler: wgpu::Sampler,
+ white: wgpu::TextureView,
+ black_hdr: wgpu::TextureView,
+ // The uploaded meshes, textures and panoramas, by the address of their `Arc`. Each entry
+ // holds a weak reference, so no other value gets this address while the entry exists.
+ meshes: Mutex<HashMap<usize, GpuMesh>>,
+ textures: Mutex<HashMap<(usize, bool), GpuTexture>>,
+ env_maps: Mutex<HashMap<usize, EnvMapTexture>>,
+ contexts: Mutex<ContextPool>,
+ /// Signals that a frame context is free again.
+ available: Condvar,
+ /// The textures that frames render into as layers of the backend's frames.
+ layers: Mutex<Vec<LayerTarget>>,
+}
+
+/// A texture that a frame renders into for `fframes::wgpu_layer`. It is free again when
+/// the image of the frame is dropped. At that time the backend has submitted the frame that
+/// samples it.
+struct LayerTarget {
+ texture: wgpu::Texture,
+ view: wgpu::TextureView,
+ image: Weak<usvgr::PreloadedImageData>,
+ reserved: bool,
+}
+
+struct PostPipelines {
+ tile: wgpu::RenderPipeline,
+ near: wgpu::RenderPipeline,
+ half: wgpu::RenderPipeline,
+ dof: wgpu::RenderPipeline,
+ accumulate: wgpu::RenderPipeline,
+ bright: wgpu::RenderPipeline,
+ down: wgpu::RenderPipeline,
+ /// `down` that keeps the coverage, for the reflection levels.
+ down_rgba: wgpu::RenderPipeline,
+ up: wgpu::RenderPipeline,
+ encode: wgpu::RenderPipeline,
+}
+
+/// The texture that holds the finished HDR frame. A single moment needs no accumulation, so
+/// the frame uses its target as it is.
+#[derive(Clone, Copy)]
+enum Accumulated {
+ Accum,
+ Hdr,
+ Dof,
+}
+
+/// What the meshes of one batch share: the draw uniform without the matrices, the textures,
+/// the variant, the side, the mirroring and the shadow casting.
+type BatchKey = (Vec<u8>, Variant, u8, bool, bool);
+
+/// A mesh of the frame, ready to draw.
+struct DrawItem<'s> {
+ material: &'s Material,
+ geometry: Arc<Geometry>,
+ uniform: DrawUniform,
+ /// `None` for vertices in the stream buffer.
+ vertices: Option<wgpu::Buffer>,
+ vertex_offset: u64,
+ /// `None` for indices in the stream index buffer (a batch).
+ indices: Option<wgpu::Buffer>,
+ index_offset: u64,
+ index_count: u32,
+ /// The copies in the instance buffer: entry 0 alone for a mesh without copies.
+ first_instance: u32,
+ instance_count: u32,
+ /// Part of a batch. The batch draws it.
+ batched: bool,
+ cast_shadow: bool,
+ mirrored: bool,
+ depth: f32,
+ bounds: crate::Aabb,
+ variant: Variant,
+}
+
+impl DrawItem<'_> {
+ /// Items of one rank use the same pipeline.
+ fn pipeline_rank(&self) -> (Variant, u8, bool) {
+ let cull = match cull_face(self.material.side, self.mirrored) {
+ None => 0,
+ Some(wgpu::Face::Back) => 1,
+ Some(wgpu::Face::Front) => 2,
+ };
+ (self.variant, cull, self.material.depth_write)
+ }
+
+ /// Binds the vertices and indices of the item and draws them.
+ fn draw(&self, pass: &mut wgpu::RenderPass<'_>, cx: &FrameContext) {
+ // wgpu cannot bind an empty index buffer.
+ if self.index_count == 0 {
+ return;
+ }
+ let vertices = self.vertices.as_ref().unwrap_or(&cx.stream_buffer);
+ let indices = self.indices.as_ref().unwrap_or(&cx.stream_index_buffer);
+ pass.set_vertex_buffer(0, vertices.slice(self.vertex_offset..));
+ pass.set_vertex_buffer(1, cx.instance_buffer.slice(..));
+ pass.set_index_buffer(
+ indices.slice(self.index_offset..),
+ wgpu::IndexFormat::Uint32,
+ );
+ let instances = self.first_instance..self.first_instance + self.instance_count;
+ pass.draw_indexed(0..self.index_count, 0, instances);
+ }
+}
+
+/// The render targets and buffers of one frame in progress.
+struct FrameContext {
+ width: u32,
+ height: u32,
+ msaa_color: wgpu::TextureView,
+ msaa_key: wgpu::TextureView,
+ depth: wgpu::TextureView,
+ hdr: wgpu::TextureView,
+ key: wgpu::TextureView,
+ tiles: wgpu::TextureView,
+ /// The largest blur around each tile.
+ near: wgpu::TextureView,
+ /// The frame and its keys at half resolution, for the outer samples of the depth of field.
+ half_hdr: wgpu::TextureView,
+ half_key: wgpu::TextureView,
+ dof: wgpu::TextureView,
+ accum: wgpu::TextureView,
+ /// The bloom levels with their sizes, each half the size of the one before.
+ bloom: Vec<(wgpu::TextureView, u32, u32)>,
+ output: wgpu::Texture,
+ output_view: wgpu::TextureView,
+ readback: wgpu::Buffer,
+ padded_row: u32,
+ shadow_size: u32,
+ shadow_array: wgpu::TextureView,
+ shadow_layers: Vec<wgpu::TextureView>,
+ /// The average of the moments. Bloom and tone mapping read it.
+ result: Accumulated,
+ /// The scene as the reflector mirrors it, when the scene has a reflector.
+ reflection: Option<ReflectionTargets>,
+ frame_buffer: wgpu::Buffer,
+ shadow_pass_buffer: wgpu::Buffer,
+ post_buffer: wgpu::Buffer,
+ draw_buffer: wgpu::Buffer,
+ /// The vertices of the deformed meshes and of the batches.
+ stream_buffer: wgpu::Buffer,
+ /// The copies of the meshes, see [`InstanceData`].
+ instance_buffer: wgpu::Buffer,
+ /// The indices of the batches.
+ stream_index_buffer: wgpu::Buffer,
+ particle_buffer: wgpu::Buffer,
+}
+
+static OWN_GPU: OnceLock<Option<Arc<Gpu>>> = OnceLock::new();
+
+/// The renderer on a device of its own. It is made on first use. `None` when no adapter is
+/// usable.
+fn own_gpu() -> Option<Arc<Gpu>> {
+ OWN_GPU
+ .get_or_init(|| match pollster::block_on(Gpu::new()) {
+ Ok(gpu) => Some(Arc::new(gpu)),
+ Err(e) => {
+ eprintln!("fframes_three_d: no GPU available ({e}), rendering on the CPU");
+ None
+ }
+ })
+ .clone()
+}
+
+/// The renderer on the GPU of the backend, when the backend shares it.
+fn shared_gpu() -> Option<(SharedGpu, Arc<Gpu>)> {
+ let shared = wgpu_layer::shared_gpu()?;
+ let gpu = shared.state(|shared| {
+ Gpu::with_device(
+ shared.device().clone(),
+ shared.queue().clone(),
+ Some(shared.queue_lock()),
+ )
+ });
+ Some((shared, gpu))
+}
+
+/// The renderer for frames that are read back as pixels. It uses the GPU of the backend when
+/// the backend shares it, so that there is only one device. Otherwise it uses its own device.
+pub(crate) fn gpu() -> Option<Arc<Gpu>> {
+ shared_gpu().map(|(_, gpu)| gpu).or_else(own_gpu)
+}
+
+/// Renders the moments (one, or more for motion blur) as a layer of the backend's frame.
+/// `None` when the backend does not share its GPU.
+pub(crate) fn layer(
+ renderer: &Renderer,
+ moments: &[(&Scene, &Camera)],
+) -> Option<fframes_media::ImageData<'static>> {
+ let (shared, gpu) = shared_gpu()?;
+ Some(gpu.render_layer(renderer, moments, &shared))
+}
+
+/// Locks `mutex`. The data stays usable after a panic on another thread that held the lock.
+fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
+ mutex.lock().unwrap_or_else(PoisonError::into_inner)
+}
+
+/// Converts a finite `f32` to the bits of an `f16`, clamped to the `f16` range. This is
+/// enough for HDR panoramas.
+fn to_f16(value: f32) -> u16 {
+ let value = value.clamp(-65504.0, 65504.0);
+ let bits = value.to_bits();
+ let sign = ((bits >> 16) & 0x8000) as u16;
+ let exponent = ((bits >> 23) & 0xff) as i32 - 127 + 15;
+ let mantissa = bits & 0x007f_ffff;
+ if exponent <= 0 {
+ if exponent < -10 {
+ return sign;
+ }
+ let m = (mantissa | 0x0080_0000) >> (1 - exponent);
+ return sign | ((m + 0x1000) >> 13) as u16;
+ }
+ if exponent >= 31 {
+ return sign | 0x7bff;
+ }
+
+ sign | ((exponent as u16) << 10) | ((mantissa + 0x1000) >> 13) as u16
+}
+
+impl Gpu {
+ async fn new() -> Result<Gpu, String> {
+ let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle();
+ descriptor.backends = wgpu::Backends::PRIMARY;
+ let instance = wgpu::Instance::new(descriptor);
+ let adapter = instance
+ .request_adapter(&wgpu::RequestAdapterOptions {
+ power_preference: wgpu::PowerPreference::HighPerformance,
+ force_fallback_adapter: false,
+ compatible_surface: None,
+ apply_limit_buckets: false,
+ })
+ .await
+ .map_err(|e| e.to_string())?;
+ let (device, queue) = adapter
+ .request_device(&wgpu::DeviceDescriptor {
+ label: Some("fframes_three_d"),
+ required_features: wgpu::Features::empty(),
+ required_limits: wgpu::Limits::default(),
+ ..Default::default()
+ })
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(Self::with_device(device, queue, None))
+ }
+
+ /// The renderer on `device`. When the backend shares the queue, the renderer holds
+ /// `queue_lock` while it submits.
+ fn with_device(
+ device: wgpu::Device,
+ queue: wgpu::Queue,
+ queue_lock: Option<Arc<Mutex<()>>>,
+ ) -> Gpu {
+ let scene_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("scene"),
+ source: wgpu::ShaderSource::Wgsl(include_str!("scene.wgsl").into()),
+ });
+ let shadow_module = device.create_shader_module(wgpu::include_wgsl!("shadow.wgsl"));
+ let post_module = device.create_shader_module(wgpu::include_wgsl!("post.wgsl"));
+
+ let uniform = |binding: u32, dynamic: bool, visibility: wgpu::ShaderStages| {
+ wgpu::BindGroupLayoutEntry {
+ binding,
+ visibility,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: dynamic,
+ min_binding_size: None,
+ },
+ count: None,
+ }
+ };
+ let texture = |binding: u32,
+ sample_type: wgpu::TextureSampleType,
+ view_dimension: wgpu::TextureViewDimension| {
+ wgpu::BindGroupLayoutEntry {
+ binding,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Texture {
+ sample_type,
+ view_dimension,
+ multisampled: false,
+ },
+ count: None,
+ }
+ };
+ let float_2d = |binding: u32| {
+ texture(
+ binding,
+ wgpu::TextureSampleType::Float { filterable: true },
+ wgpu::TextureViewDimension::D2,
+ )
+ };
+ let sampler = |binding: u32, kind: wgpu::SamplerBindingType| wgpu::BindGroupLayoutEntry {
+ binding,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Sampler(kind),
+ count: None,
+ };
+ let filtering = wgpu::SamplerBindingType::Filtering;
+ let bind_group_layout = |label: &str, entries: &[wgpu::BindGroupLayoutEntry]| {
+ device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some(label),
+ entries,
+ })
+ };
+ let frame_layout = bind_group_layout(
+ "frame",
+ &[
+ uniform(0, false, wgpu::ShaderStages::VERTEX_FRAGMENT),
+ texture(
+ 1,
+ wgpu::TextureSampleType::Depth,
+ wgpu::TextureViewDimension::D2Array,
+ ),
+ sampler(2, wgpu::SamplerBindingType::Comparison),
+ float_2d(3),
+ sampler(4, filtering),
+ float_2d(5),
+ sampler(6, filtering),
+ ],
+ );
+ let draw_layout = bind_group_layout(
+ "draw",
+ &[
+ uniform(0, true, wgpu::ShaderStages::VERTEX_FRAGMENT),
+ float_2d(1),
+ float_2d(2),
+ float_2d(3),
+ sampler(4, filtering),
+ float_2d(5),
+ float_2d(6),
+ ],
+ );
+ let shadow_layout = bind_group_layout(
+ "shadow pass",
+ &[uniform(0, false, wgpu::ShaderStages::VERTEX)],
+ );
+ let shadow_draw_layout = bind_group_layout(
+ "shadow draw",
+ &[uniform(0, true, wgpu::ShaderStages::VERTEX)],
+ );
+ let post_layout = bind_group_layout(
+ "post",
+ &[
+ uniform(0, false, wgpu::ShaderStages::FRAGMENT),
+ float_2d(1),
+ sampler(2, filtering),
+ float_2d(3),
+ float_2d(4),
+ float_2d(5),
+ float_2d(6),
+ ],
+ );
+
+ let pipeline_layout = |label: &str, groups: &[Option<&wgpu::BindGroupLayout>]| {
+ device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some(label),
+ bind_group_layouts: groups,
+ ..Default::default()
+ })
+ };
+ let scene_pipeline_layout =
+ pipeline_layout("scene", &[Some(&frame_layout), Some(&draw_layout)]);
+ let shadow_pipeline_layout =
+ pipeline_layout("shadow", &[Some(&shadow_layout), Some(&shadow_draw_layout)]);
+ let frame_only_layout = pipeline_layout("frame only", &[Some(&frame_layout)]);
+ let post_pipeline_layout = pipeline_layout("post", &[Some(&post_layout)]);
+
+ let shadow_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("shadow"),
+ layout: Some(&shadow_pipeline_layout),
+ vertex: wgpu::VertexState {
+ module: &shadow_module,
+ entry_point: Some("vs_shadow"),
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ buffers: &[
+ Some(wgpu::VertexBufferLayout {
+ array_stride: size_of::<Vertex>() as u64,
+ step_mode: wgpu::VertexStepMode::Vertex,
+ attributes: &wgpu::vertex_attr_array![0 => Float32x3],
+ }),
+ Some(instance_layout(&SHADOW_INSTANCE_ATTRIBUTES)),
+ ],
+ },
+ primitive: wgpu::PrimitiveState::default(),
+ depth_stencil: Some(depth_test(true, wgpu::CompareFunction::Less)),
+ multisample: wgpu::MultisampleState::default(),
+ fragment: Some(wgpu::FragmentState {
+ module: &shadow_module,
+ entry_point: Some("fs_shadow"),
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ targets: &[],
+ }),
+ multiview_mask: None,
+ cache: None,
+ });
+
+ let msaa = wgpu::MultisampleState {
+ count: MSAA,
+ ..Default::default()
+ };
+ let background = |multisample: wgpu::MultisampleState| {
+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("background"),
+ layout: Some(&frame_only_layout),
+ vertex: wgpu::VertexState {
+ module: &scene_module,
+ entry_point: Some("vs_fullscreen"),
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ buffers: &[],
+ },
+ primitive: wgpu::PrimitiveState::default(),
+ depth_stencil: Some(depth_test(false, wgpu::CompareFunction::Always)),
+ multisample,
+ fragment: Some(wgpu::FragmentState {
+ module: &scene_module,
+ entry_point: Some("fs_background"),
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ targets: &scene_targets(None),
+ }),
+ multiview_mask: None,
+ cache: None,
+ })
+ };
+ let particle = |entry: &str, blend: wgpu::BlendState| {
+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some(entry),
+ layout: Some(&frame_only_layout),
+ vertex: wgpu::VertexState {
+ module: &scene_module,
+ entry_point: Some("vs_particle"),
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ buffers: &[Some(wgpu::VertexBufferLayout {
+ array_stride: size_of::<ParticleInstance>() as u64,
+ step_mode: wgpu::VertexStepMode::Instance,
+ attributes: &wgpu::vertex_attr_array![0 => Float32x4, 1 => Float32x4],
+ })],
+ },
+ primitive: wgpu::PrimitiveState::default(),
+ depth_stencil: Some(depth_test(false, wgpu::CompareFunction::Greater)),
+ multisample: msaa,
+ fragment: Some(wgpu::FragmentState {
+ module: &scene_module,
+ entry_point: Some(entry),
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ targets: &scene_targets(Some(blend)),
+ }),
+ multiview_mask: None,
+ cache: None,
+ })
+ };
+ let post_pipeline = |entry: &str, targets: &[Option<wgpu::ColorTargetState>]| {
+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some(entry),
+ layout: Some(&post_pipeline_layout),
+ vertex: wgpu::VertexState {
+ module: &post_module,
+ entry_point: Some("vs_fullscreen"),
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ buffers: &[],
+ },
+ primitive: wgpu::PrimitiveState::default(),
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ fragment: Some(wgpu::FragmentState {
+ module: &post_module,
+ entry_point: Some(entry),
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ targets,
+ }),
+ multiview_mask: None,
+ cache: None,
+ })
+ };
+ let added_hdr = [Some(wgpu::ColorTargetState {
+ blend: Some(wgpu::BlendState::ADDITIVE),
+ ..HDR.into()
+ })];
+ let post = PostPipelines {
+ tile: post_pipeline("fs_tile", &[Some(KEY.into())]),
+ near: post_pipeline("fs_near", &[Some(KEY.into())]),
+ half: post_pipeline("fs_half", &[Some(HDR.into()), Some(KEY.into())]),
+ dof: post_pipeline("fs_dof", &[Some(HDR.into())]),
+ accumulate: post_pipeline("fs_accumulate", &added_hdr),
+ bright: post_pipeline("fs_bright", &[Some(HDR.into())]),
+ down: post_pipeline("fs_down", &[Some(HDR.into())]),
+ down_rgba: post_pipeline("fs_down_rgba", &[Some(HDR.into())]),
+ up: post_pipeline("fs_up", &added_hdr),
+ encode: post_pipeline("fs_encode", &[Some(OUTPUT.into())]),
+ };
+
+ let linear = |address_mode_u, address_mode_v, anisotropy_clamp| {
+ device.create_sampler(&wgpu::SamplerDescriptor {
+ address_mode_u,
+ address_mode_v,
+ address_mode_w: address_mode_u,
+ mag_filter: wgpu::FilterMode::Linear,
+ min_filter: wgpu::FilterMode::Linear,
+ mipmap_filter: wgpu::MipmapFilterMode::Linear,
+ anisotropy_clamp,
+ ..Default::default()
+ })
+ };
+ let (repeat, clamp) = (wgpu::AddressMode::Repeat, wgpu::AddressMode::ClampToEdge);
+ let shadow_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
+ mag_filter: wgpu::FilterMode::Linear,
+ min_filter: wgpu::FilterMode::Linear,
+ compare: Some(wgpu::CompareFunction::LessEqual),
+ ..Default::default()
+ });
+
+ let texel = |format: wgpu::TextureFormat, data: &[u8]| {
+ device
+ .create_texture_with_data(
+ &queue,
+ &texture_desc(
+ "single texel",
+ 1,
+ 1,
+ format,
+ wgpu::TextureUsages::TEXTURE_BINDING,
+ ),
+ wgpu::util::TextureDataOrder::LayerMajor,
+ data,
+ )
+ .create_view(&wgpu::TextureViewDescriptor::default())
+ };
+
+ Gpu {
+ white: texel(wgpu::TextureFormat::Rgba8Unorm, &[255; 4]),
+ black_hdr: texel(HDR, &[0; 8]),
+ linear_repeat: linear(repeat, repeat, 8),
+ linear_clamp: linear(clamp, clamp, 1),
+ env_sampler: linear(repeat, clamp, 1),
+ shadow_sampler,
+ shadow_pipeline,
+ background_pipeline: background(msaa),
+ background_1x: background(wgpu::MultisampleState::default()),
+ particle_additive: particle("fs_particle_additive", ADD_LIGHT),
+ particle_normal: particle(
+ "fs_particle_normal",
+ wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING,
+ ),
+ post,
+ device,
+ queue,
+ queue_lock,
+ scene_module,
+ frame_layout,
+ draw_layout,
+ shadow_layout,
+ shadow_draw_layout,
+ post_layout,
+ scene_pipeline_layout,
+ pipelines: Mutex::new(HashMap::new()),
+ meshes: Mutex::new(HashMap::new()),
+ textures: Mutex::new(HashMap::new()),
+ env_maps: Mutex::new(HashMap::new()),
+ contexts: Mutex::new(ContextPool {
+ free: Vec::new(),
+ created: 0,
+ }),
+ available: Condvar::new(),
+ layers: Mutex::new(Vec::new()),
+ }
+ }
+
+ /// Submits `commands`. Holds the queue lock of the backend when the queue is shared.
+ fn submit(&self, commands: wgpu::CommandBuffer) -> wgpu::SubmissionIndex {
+ let _queue = self.queue_lock.as_deref().map(lock);
+ self.queue.submit([commands])
+ }
+
+ /// The geometry pipeline for `key`, made on first use.
+ fn pipeline(&self, key: PipelineKey) -> wgpu::RenderPipeline {
+ let mut pipelines = lock(&self.pipelines);
+ if let Some(pipeline) = pipelines.get(&key) {
+ return pipeline.clone();
+ }
+ let blend = match key.blend {
+ Blend::Opaque => None,
+ Blend::Normal => Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
+ Blend::Additive => Some(ADD_LIGHT),
+ };
+ let constants = key.variant.constants(key.reflection_pass);
+ let pipeline = self
+ .device
+ .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("geometry"),
+ layout: Some(&self.scene_pipeline_layout),
+ vertex: wgpu::VertexState {
+ module: &self.scene_module,
+ entry_point: Some("vs_main"),
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ buffers: &[
+ Some(wgpu::VertexBufferLayout {
+ array_stride: size_of::<Vertex>() as u64,
+ step_mode: wgpu::VertexStepMode::Vertex,
+ attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Float32x2, 3 => Float32x4],
+ }),
+ Some(instance_layout(&INSTANCE_ATTRIBUTES)),
+ ],
+ },
+ primitive: wgpu::PrimitiveState {
+ cull_mode: key.cull,
+ ..Default::default()
+ },
+ depth_stencil: Some(depth_test(key.depth_write, wgpu::CompareFunction::Greater)),
+ multisample: wgpu::MultisampleState {
+ count: if key.reflection_pass { 1 } else { MSAA },
+ ..Default::default()
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &self.scene_module,
+ entry_point: Some("fs_main"),
+ compilation_options: wgpu::PipelineCompilationOptions {
+ constants: &constants,
+ ..Default::default()
+ },
+ targets: &scene_targets(blend),
+ }),
+ multiview_mask: None,
+ cache: None,
+ });
+ pipelines.insert(key, pipeline.clone());
+ pipeline
+ }
+
+ /// The vertex buffer, the index buffer and the index count of a rigid mesh. The mesh is
+ /// uploaded on first use.
+ fn mesh(&self, geometry: &Arc<Geometry>) -> (wgpu::Buffer, wgpu::Buffer, u32) {
+ let key = Arc::as_ptr(geometry) as usize;
+ let mut meshes = lock(&self.meshes);
+ if let Some(m) = meshes.get(&key) {
+ return (m.vertices.clone(), m.indices.clone(), m.index_count);
+ }
+ if meshes.len() > 64 {
+ meshes.retain(|_, m| m.geometry.strong_count() > 0);
+ }
+ let indices: Vec<u32> = geometry
+ .indices
+ .iter()
+ .copied()
+ .filter(|&i| (i as usize) < geometry.positions.len())
+ .collect();
+ let mesh = meshes.entry(key).or_insert(GpuMesh {
+ geometry: Arc::downgrade(geometry),
+ vertices: self
+ .device
+ .create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("mesh vertices"),
+ contents: bytemuck::cast_slice(&vertices_of(geometry, None)),
+ usage: wgpu::BufferUsages::VERTEX,
+ }),
+ indices: self
+ .device
+ .create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("mesh indices"),
+ contents: bytemuck::cast_slice(&indices),
+ usage: wgpu::BufferUsages::INDEX,
+ }),
+ index_count: indices.len() as u32,
+ });
+ (
+ mesh.vertices.clone(),
+ mesh.indices.clone(),
+ mesh.index_count,
+ )
+ }
+
+ /// The view of a material texture with its mipmaps, uploaded on first use.
+ fn texture(&self, texture: &Arc<Texture>) -> wgpu::TextureView {
+ let key = (Arc::as_ptr(texture) as usize, texture.srgb);
+ let mut textures = lock(&self.textures);
+ if let Some(t) = textures.get(&key) {
+ return t.view.clone();
+ }
+ textures.retain(|_, t| t.source.strong_count() > 0);
+ let format = if texture.srgb {
+ wgpu::TextureFormat::Rgba8UnormSrgb
+ } else {
+ wgpu::TextureFormat::Rgba8Unorm
+ };
+ let gpu_texture = self.device.create_texture(&wgpu::TextureDescriptor {
+ mip_level_count: texture.levels().count() as u32,
+ ..texture_desc(
+ "material texture",
+ texture.width,
+ texture.height,
+ format,
+ wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
+ )
+ });
+ for (level, (width, height, texels)) in texture.levels().enumerate() {
+ self.write_level(
+ &gpu_texture,
+ level as u32,
+ width,
+ height,
+ bytemuck::cast_slice(texels),
+ );
+ }
+ let entry = textures.entry(key).or_insert(GpuTexture {
+ source: Arc::downgrade(texture),
+ view: gpu_texture.create_view(&wgpu::TextureViewDescriptor::default()),
+ });
+ entry.view.clone()
+ }
+
+ /// The view and the level count of an environment panorama, uploaded on first use.
+ fn env_map(&self, map: &Arc<crate::EnvironmentMap>) -> (wgpu::TextureView, u32) {
+ let key = Arc::as_ptr(map) as usize;
+ let mut maps = lock(&self.env_maps);
+ if let Some(t) = maps.get(&key) {
+ return (t.view.clone(), t.levels);
+ }
+ maps.retain(|_, t| t.source.strong_count() > 0);
+ let levels: Vec<_> = map.levels().collect();
+ let (width, height, _) = levels[0];
+ let texture = self.device.create_texture(&wgpu::TextureDescriptor {
+ mip_level_count: levels.len() as u32,
+ ..texture_desc(
+ "environment",
+ width as u32,
+ height as u32,
+ HDR,
+ wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
+ )
+ });
+ for (level, (width, height, texels)) in levels.iter().enumerate() {
+ let half: Vec<u16> = texels
+ .iter()
+ .flat_map(|c| [to_f16(c.x), to_f16(c.y), to_f16(c.z), to_f16(1.0)])
+ .collect();
+ self.write_level(
+ &texture,
+ level as u32,
+ *width as u32,
+ *height as u32,
+ bytemuck::cast_slice(&half),
+ );
+ }
+ let entry = maps.entry(key).or_insert(EnvMapTexture {
+ source: Arc::downgrade(map),
+ view: texture.create_view(&wgpu::TextureViewDescriptor::default()),
+ levels: levels.len() as u32,
+ });
+ (entry.view.clone(), entry.levels)
+ }
+
+ /// Uploads one mipmap level. `data` holds the rows without padding.
+ fn write_level(
+ &self,
+ texture: &wgpu::Texture,
+ level: u32,
+ width: u32,
+ height: u32,
+ data: &[u8],
+ ) {
+ self.queue.write_texture(
+ wgpu::TexelCopyTextureInfo {
+ mip_level: level,
+ ..texture.as_image_copy()
+ },
+ data,
+ wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(data.len() as u32 / height),
+ rows_per_image: Some(height),
+ },
+ wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ );
+ }
+
+ /// Writes `data` to the start of `buffer`. When the data does not fit, the buffer is
+ /// replaced by a larger one (the next power of two).
+ fn write_growing(&self, buffer: &mut wgpu::Buffer, label: &str, data: &[u8]) {
+ if data.is_empty() {
+ return;
+ }
+ if data.len() as u64 > buffer.size() {
+ *buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some(label),
+ size: (data.len() as u64).next_power_of_two(),
+ usage: buffer.usage(),
+ mapped_at_creation: false,
+ });
+ }
+ self.queue.write_buffer(buffer, 0, data);
+ }
+
+ /// A bind group with `resources` at bindings 0, 1, 2 and so on.
+ fn bind_group(
+ &self,
+ label: &str,
+ layout: &wgpu::BindGroupLayout,
+ resources: &[wgpu::BindingResource<'_>],
+ ) -> wgpu::BindGroup {
+ let entries: Vec<wgpu::BindGroupEntry> = resources
+ .iter()
+ .enumerate()
+ .map(|(binding, resource)| wgpu::BindGroupEntry {
+ binding: binding as u32,
+ resource: resource.clone(),
+ })
+ .collect();
+ self.device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some(label),
+ layout,
+ entries: &entries,
+ })
+ }
+
+ /// The bind group of a mesh: its draw uniform at a dynamic offset and its textures.
+ fn draw_group(&self, cx: &FrameContext, material: &Material) -> wgpu::BindGroup {
+ let view = |t: &Option<Arc<Texture>>| {
+ t.as_ref()
+ .map_or_else(|| self.white.clone(), |t| self.texture(t))
+ };
+ let map = view(&material.map);
+ let emissive = view(&material.emissive_map);
+ let metal_rough = view(&material.metal_rough_map);
+ let normal = view(&material.normal_map);
+ let occlusion = view(&material.ao_map);
+ self.bind_group(
+ "draw",
+ &self.draw_layout,
+ &[
+ buffer_range(&cx.draw_buffer, 0, size_of::<DrawUniform>()),
+ wgpu::BindingResource::TextureView(&map),
+ wgpu::BindingResource::TextureView(&emissive),
+ wgpu::BindingResource::TextureView(&metal_rough),
+ wgpu::BindingResource::Sampler(&self.linear_repeat),
+ wgpu::BindingResource::TextureView(&normal),
+ wgpu::BindingResource::TextureView(&occlusion),
+ ],
+ )
+ }
+
+ /// A bind group of `post.wgsl` with the uniform in `slot` of the post buffer. The
+ /// textures are `src`, `depth_key`, `tiles`, `aux_tex` and `half_key` in this order.
+ fn post_group(
+ &self,
+ cx: &FrameContext,
+ slot: u64,
+ [src, key, tiles, aux, half_key]: [&wgpu::TextureView; 5],
+ ) -> wgpu::BindGroup {
+ self.bind_group(
+ "post",
+ &self.post_layout,
+ &[
+ buffer_range(
+ &cx.post_buffer,
+ slot * UNIFORM_ALIGNMENT,
+ size_of::<PostUniform>(),
+ ),
+ wgpu::BindingResource::TextureView(src),
+ wgpu::BindingResource::Sampler(&self.linear_clamp),
+ wgpu::BindingResource::TextureView(key),
+ wgpu::BindingResource::TextureView(tiles),
+ wgpu::BindingResource::TextureView(aux),
+ wgpu::BindingResource::TextureView(half_key),
+ ],
+ )
+ }
+
+ /// Takes a free frame context of this size from the pool, or makes one. Waits while all
+ /// contexts are in use. The shadow maps get exactly `shadow_size` texels, as on the CPU:
+ /// a context that kept larger maps from an earlier shot would shade the frame with
+ /// another texel size and normal offset than a fresh one. `None` keeps the maps.
+ fn take_context(&self, width: u32, height: u32, shadow_size: Option<u32>) -> FrameContext {
+ let mut pool = lock(&self.contexts);
+ loop {
+ let fits = |c: &FrameContext| c.width == width && c.height == height;
+ // A context with maps of this size first, so that shots do not reallocate them.
+ let found = (pool.free.iter())
+ .position(|c| fits(c) && shadow_size.is_none_or(|s| c.shadow_size == s))
+ .or_else(|| pool.free.iter().position(fits));
+ if let Some(i) = found {
+ let mut context = pool.free.swap_remove(i);
+ drop(pool);
+ if let Some(size) = shadow_size.filter(|&s| s != context.shadow_size) {
+ context.resize_shadows(&self.device, size);
+ }
+ return context;
+ }
+ if pool.created < CONTEXTS {
+ pool.created += 1;
+ break;
+ }
+ // Drops a free context of another size to make room for a new one.
+ if pool.free.pop().is_some() {
+ break;
+ }
+ pool = self
+ .available
+ .wait(pool)
+ .unwrap_or_else(PoisonError::into_inner);
+ }
+ drop(pool);
+ FrameContext::new(&self.device, width, height, shadow_size.unwrap_or(1024))
+ }
+
+ /// Puts a frame context back into the pool.
+ fn give_back(&self, context: FrameContext) {
+ lock(&self.contexts).free.push(context);
+ self.available.notify_one();
+ }
+
+ /// Renders the moments (one, or more for motion blur) and returns the pixels.
+ pub(crate) fn render(&self, renderer: &Renderer, moments: &[(&Scene, &Camera)]) -> Pixels {
+ let context = self.render_moments(renderer, moments);
+ let pixels = self.finish(&context, renderer);
+ self.give_back(context);
+ pixels
+ }
+
+ /// Renders the moments into a texture that the backend samples in place, see
+ /// `fframes::wgpu_layer`. Does not wait for the GPU.
+ fn render_layer(
+ &self,
+ renderer: &Renderer,
+ moments: &[(&Scene, &Camera)],
+ shared: &SharedGpu,
+ ) -> fframes_media::ImageData<'static> {
+ let context = self.render_moments(renderer, moments);
+ let (slot, texture, view) = self.take_layer(context.width, context.height);
+ let mut encoder = self
+ .device
+ .create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
+ self.post_process(&context, renderer, &mut encoder, &view);
+ wgpu_layer::finish_wgpu_layer(&mut encoder, &texture);
+ self.submit(encoder.finish());
+ self.give_back(context);
+ let image = wgpu_layer::wgpu_layer(shared, &texture);
+ let mut layers = lock(&self.layers);
+ layers[slot].image = Arc::downgrade(&image.href());
+ layers[slot].reserved = false;
+ drop(layers);
+ // Releases the resources of finished submissions. This does not wait for the GPU.
+ let _ = self.device.poll(wgpu::PollType::Poll);
+ image
+ }
+
+ /// A free layer texture of this size, or a new one. A layer is free when its frame is done.
+ fn take_layer(&self, width: u32, height: u32) -> (usize, wgpu::Texture, wgpu::TextureView) {
+ let mut layers = lock(&self.layers);
+ if let Some(slot) = layers.iter().position(|l| {
+ !l.reserved
+ && l.image.strong_count() == 0
+ && l.texture.width() == width
+ && l.texture.height() == height
+ }) {
+ let layer = &mut layers[slot];
+ layer.reserved = true;
+ return (slot, layer.texture.clone(), layer.view.clone());
+ }
+ let texture = self.device.create_texture(&texture_desc(
+ "fframes_three_d layer",
+ width,
+ height,
+ wgpu_layer::WGPU_LAYER_FORMAT,
+ wgpu_layer::WGPU_LAYER_USAGE | wgpu::TextureUsages::RENDER_ATTACHMENT,
+ ));
+ let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
+ layers.push(LayerTarget {
+ texture: texture.clone(),
+ view: view.clone(),
+ image: Weak::new(),
+ reserved: true,
+ });
+ (layers.len() - 1, texture, view)
+ }
+
+ /// Renders the moments into a frame context from the pool and averages them.
+ fn render_moments(&self, renderer: &Renderer, moments: &[(&Scene, &Camera)]) -> FrameContext {
+ let shadow_size = moments
+ .iter()
+ .flat_map(|(scene, _)| {
+ scene.nodes().filter_map(|(_, n)| match &n.object {
+ Object::Light(crate::Light::Directional(l)) => {
+ l.shadow.as_ref().map(|s| s.map_size.clamp(64, 8192))
+ }
+ _ => None,
+ })
+ })
+ .max();
+ let mut context = self.take_context(renderer.width, renderer.height, shadow_size);
+ let weight = 1.0 / moments.len().max(1) as f32;
+ for (i, (scene, camera)) in moments.iter().enumerate() {
+ self.render_moment(&mut context, scene, camera, weight, i, moments.len() == 1);
+ }
+ context
+ }
+
+ /// Renders the moment with index `moment` and adds it with `weight` to the average of
+ /// the frame. Moment 0 starts a new average. `single` tells that the moment is the
+ /// whole frame.
+ fn render_moment(
+ &self,
+ cx: &mut FrameContext,
+ scene: &Scene,
+ camera: &Camera,
+ weight: f32,
+ moment: usize,
+ single: bool,
+ ) {
+ let (width, height) = (cx.width, cx.height);
+ let worlds = scene.world_matrices();
+ let visible = scene.visibilities();
+ let view = camera.view_matrix();
+
+ // The lights, the meshes and the particles of the scene.
+ let mut lights = Lights {
+ direct: Vec::new(),
+ ambient: Vec3::ZERO,
+ hemisphere: None,
+ shadow_casters: Vec::new(),
+ };
+ let mut items: Vec<DrawItem> = Vec::new();
+ let mut streamed: Vec<Vertex> = Vec::new();
+ let mut instances = vec![InstanceData::new(Mat4::IDENTITY, Vec4::ONE)];
+ let mut additive: Vec<ParticleInstance> = Vec::new();
+ let mut normal: Vec<ParticleInstance> = Vec::new();
+ for (id, node) in scene.nodes() {
+ if !visible[id.index()] {
+ continue;
+ }
+ let world = worlds[id.index()];
+ match &node.object {
+ Object::Group => {}
+ Object::Light(light) => prepare::push_light(&mut lights, light, &world),
+ Object::Particles(particles) => {
+ let scale = world.x_axis.truncate().length();
+ let target = if particles.blending == Blending::Additive {
+ &mut additive
+ } else {
+ &mut normal
+ };
+ for p in &particles.items {
+ if p.opacity <= 0.0 {
+ continue;
+ }
+ target.push(ParticleInstance {
+ position: world
+ .transform_point3(p.position)
+ .extend(p.size * scale)
+ .to_array(),
+ color: (p.color.0 * p.opacity).extend(p.opacity).to_array(),
+ });
+ }
+ }
+ Object::Mesh(mesh) => {
+ let g = &mesh.geometry;
+ if g.indices.is_empty() || g.positions.is_empty() {
+ continue;
+ }
+ let (vertices, indices, index_count) = self.mesh(g);
+ // A skinned or morphed mesh streams its vertices in world space.
+ let (model, normal_matrix, vertices, vertex_offset, bounds) =
+ match prepare::deformed(mesh, &world, &worlds) {
+ Some((positions, normals)) => {
+ let offset = (streamed.len() * size_of::<Vertex>()) as u64;
+ let bounds = crate::Aabb::from_points(positions.iter().copied());
+ streamed.extend(vertices_of(g, Some((&positions, &normals))));
+ (Mat4::IDENTITY, Mat4::IDENTITY, None, offset, bounds)
+ }
+ None => (
+ world,
+ Mat4::from_mat3(Mat3::from_mat4(world).inverse().transpose()),
+ Some(vertices),
+ 0,
+ g.bounds().transformed(&world),
+ ),
+ };
+ // The copies of a rigid mesh go into the instance buffer.
+ let (first_instance, instance_count, bounds) = match &mesh.instances {
+ Some(copies) if vertices.is_some() => {
+ let first = instances.len() as u32;
+ instances.extend(
+ (copies.transforms.iter().enumerate())
+ .map(|(i, t)| InstanceData::new(*t, copies.color(i))),
+ );
+ (first, copies.transforms.len() as u32, mesh.bounds(&world))
+ }
+ _ => (0, 1, bounds),
+ };
+ let material = &mesh.material;
+ items.push(DrawItem {
+ material,
+ geometry: Arc::clone(g),
+ uniform: draw_uniform(mesh, model, normal_matrix),
+ vertices,
+ vertex_offset,
+ indices: Some(indices),
+ index_offset: 0,
+ index_count,
+ first_instance,
+ instance_count,
+ batched: false,
+ cast_shadow: mesh.cast_shadow
+ && !material.is_blended()
+ && material.shading != Shading::ShadowCatcher,
+ mirrored: mesh.skin.is_none() && world.determinant() < 0.0,
+ depth: -view.transform_point3(bounds.center()).z,
+ bounds,
+ variant: Variant::new(material, !g.uvs.is_empty(), scene),
+ });
+ }
+ }
+ }
+ let light_count = lights.direct.len().min(MAX_LIGHTS);
+ for item in &mut items {
+ item.variant.lights = light_count as u8;
+ }
+ let stream_indices = batch(&mut items, &mut streamed);
+ let order = draw_order(&items);
+
+ // The uploads: the streamed vertices, the draw uniforms and the particles. The
+ // particle buffer holds the additive particles first.
+ self.write_growing(
+ &mut cx.stream_buffer,
+ "streamed vertices",
+ bytemuck::cast_slice(&streamed),
+ );
+ self.write_growing(
+ &mut cx.stream_index_buffer,
+ "streamed indices",
+ bytemuck::cast_slice(&stream_indices),
+ );
+ self.write_growing(
+ &mut cx.instance_buffer,
+ "instances",
+ bytemuck::cast_slice(&instances),
+ );
+ let mut draws = vec![0u8; items.len().max(1) * DRAW_STRIDE as usize];
+ for (chunk, item) in draws.chunks_mut(DRAW_STRIDE as usize).zip(&items) {
+ chunk[..size_of::<DrawUniform>()].copy_from_slice(bytemuck::bytes_of(&item.uniform));
+ }
+ self.write_growing(&mut cx.draw_buffer, "draws", &draws);
+ let additive_count = additive.len() as u32;
+ let particles = [additive, normal].concat();
+ let normal_count = particles.len() as u32 - additive_count;
+ self.write_growing(
+ &mut cx.particle_buffer,
+ "particles",
+ bytemuck::cast_slice(&particles),
+ );
+
+ // The frame uniform.
+ let projection = REVERSED_Z * camera.projection_matrix(width as f32 / height as f32);
+ let view_proj = projection * view;
+ let focal = match camera.ortho_height {
+ Some(h) => height as f32 / h,
+ None => height as f32 / (2.0 * (camera.fov.to_radians() * 0.5).tan()),
+ };
+ let mut frame = FrameUniform::zeroed();
+ frame.view_proj = view_proj.to_cols_array();
+ frame.inv_view_proj = view_proj.inverse().to_cols_array();
+ frame.view_proj_rel = (projection * relative(view)).to_cols_array();
+ frame.camera = camera
+ .position
+ .extend(f32::from(camera.ortho_height.is_some()))
+ .to_array();
+ frame.forward = camera.forward().extend(0.0).to_array();
+ frame.viewport = [width as f32, height as f32, focal, camera.near];
+ frame.ambient = lights
+ .ambient
+ .extend(f32::from(lights.hemisphere.is_some()))
+ .to_array();
+ if let Some((sky, ground)) = lights.hemisphere {
+ frame.hemi_sky = sky.extend(0.0).to_array();
+ frame.hemi_ground = ground.extend(0.0).to_array();
+ }
+ let env = self.set_environment(&mut frame, scene);
+ let shadows = fit_shadows(&lights, &items, cx.shadow_size);
+ for (uniform, shadow) in frame.shadows.iter_mut().zip(&shadows) {
+ *uniform = shadow.unwrap_or_else(GpuShadow::zeroed);
+ }
+ for (uniform, light) in frame.lights.iter_mut().zip(&lights.direct) {
+ *uniform = gpu_light(light, &shadows);
+ }
+
+ // The targets and the frame uniform of the reflection.
+ let reflector = scene
+ .reflector
+ .filter(|_| items.iter().any(|it| it.material.reflection > 0.0));
+ if let Some(reflector) = reflector {
+ let size = |pixels: u32| (pixels as f32 * reflector.scale).ceil().max(1.0) as u32;
+ cx.prepare_reflection(&self.device, size(width), size(height));
+ }
+ let reflection = reflector.and(cx.reflection.as_ref());
+ frame.counts = [
+ light_count as f32,
+ env.as_ref().map_or(0.0, |(_, levels)| *levels as f32),
+ reflection.map_or(0.0, |r| r.levels as f32),
+ 0.0,
+ ];
+ if let (Some(reflector), Some(targets)) = (reflector, reflection) {
+ let (rw, rh) = (targets.width as f32, targets.height as f32);
+ let mirror = reflector.matrix();
+ let view_proj = projection * view * mirror;
+ let mut mirrored = frame;
+ mirrored.view_proj = view_proj.to_cols_array();
+ mirrored.inv_view_proj = view_proj.inverse().to_cols_array();
+ mirrored.view_proj_rel = (projection * relative(view * mirror)).to_cols_array();
+ mirrored.camera = mirror
+ .transform_point3(camera.position)
+ .extend(frame.camera[3])
+ .to_array();
+ mirrored.forward = mirror
+ .transform_vector3(camera.forward())
+ .extend(0.0)
+ .to_array();
+ mirrored.viewport = [rw, rh, focal * rh / height as f32, camera.near];
+ mirrored.clip_plane = reflector.plane().to_array();
+ self.queue
+ .write_buffer(&targets.frame_buffer, 0, bytemuck::bytes_of(&mirrored));
+ }
+ self.queue
+ .write_buffer(&cx.frame_buffer, 0, bytemuck::bytes_of(&frame));
+
+ // The bind groups.
+ let env_view = env.map_or_else(|| self.black_hdr.clone(), |(view, _)| view);
+ let frame_group = |buffer: &wgpu::Buffer, reflection: &wgpu::TextureView| {
+ self.bind_group(
+ "frame",
+ &self.frame_layout,
+ &[
+ buffer.as_entire_binding(),
+ wgpu::BindingResource::TextureView(&cx.shadow_array),
+ wgpu::BindingResource::Sampler(&self.shadow_sampler),
+ wgpu::BindingResource::TextureView(&env_view),
+ wgpu::BindingResource::Sampler(&self.env_sampler),
+ wgpu::BindingResource::TextureView(reflection),
+ wgpu::BindingResource::Sampler(&self.linear_clamp),
+ ],
+ )
+ };
+ let draw_groups: Vec<wgpu::BindGroup> = items
+ .iter()
+ .map(|item| self.draw_group(cx, item.material))
+ .collect();
+ let draw_meshes = |pass: &mut wgpu::RenderPass<'_>, reflection_pass: bool| {
+ self.draw_items(pass, &items, &order, &draw_groups, cx, reflection_pass);
+ };
+
+ let mut encoder = self
+ .device
+ .create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
+ self.draw_shadow_maps(&mut encoder, cx, &items, &shadows);
+
+ let clear = match &scene.background {
+ Background::Color(c) => wgpu::Color {
+ r: f64::from(c.0.x),
+ g: f64::from(c.0.y),
+ b: f64::from(c.0.z),
+ a: 1.0,
+ },
+ _ => wgpu::Color::TRANSPARENT,
+ };
+ let has_background = matches!(scene.background, Background::Environment { .. });
+
+ // The reflection pass: the scene without the reflectors, seen in the mirror.
+ if let Some(targets) = reflection {
+ let group = frame_group(&targets.frame_buffer, &self.black_hdr);
+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("reflection"),
+ color_attachments: &[
+ Some(color_attachment(
+ &targets.level_views[0],
+ None,
+ wgpu::LoadOp::Clear(clear),
+ wgpu::StoreOp::Store,
+ )),
+ Some(color_attachment(
+ &targets.key,
+ None,
+ wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
+ wgpu::StoreOp::Discard,
+ )),
+ ],
+ depth_stencil_attachment: Some(depth_attachment(
+ &targets.depth,
+ 0.0,
+ wgpu::StoreOp::Discard,
+ )),
+ ..Default::default()
+ });
+ pass.set_bind_group(0, &group, &[]);
+ if has_background {
+ pass.set_pipeline(&self.background_1x);
+ pass.draw(0..3, 0..1);
+ }
+ draw_meshes(&mut pass, true);
+ drop(pass);
+ self.blur_reflection(&mut encoder, cx, targets);
+ }
+
+ // The geometry pass.
+ let group = frame_group(
+ &cx.frame_buffer,
+ reflection.map_or(&self.black_hdr, |r| &r.view),
+ );
+ {
+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("geometry"),
+ color_attachments: &[
+ Some(color_attachment(
+ &cx.msaa_color,
+ Some(&cx.hdr),
+ wgpu::LoadOp::Clear(clear),
+ wgpu::StoreOp::Discard,
+ )),
+ Some(color_attachment(
+ &cx.msaa_key,
+ Some(&cx.key),
+ wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
+ wgpu::StoreOp::Discard,
+ )),
+ ],
+ depth_stencil_attachment: Some(depth_attachment(
+ &cx.depth,
+ 0.0,
+ wgpu::StoreOp::Discard,
+ )),
+ ..Default::default()
+ });
+ pass.set_bind_group(0, &group, &[]);
+ if has_background {
+ pass.set_pipeline(&self.background_pipeline);
+ pass.draw(0..3, 0..1);
+ }
+ draw_meshes(&mut pass, false);
+ if additive_count > 0 {
+ pass.set_pipeline(&self.particle_additive);
+ pass.set_vertex_buffer(0, cx.particle_buffer.slice(..));
+ pass.draw(0..6, 0..additive_count);
+ }
+ if normal_count > 0 {
+ pass.set_pipeline(&self.particle_normal);
+ let offset = u64::from(additive_count) * size_of::<ParticleInstance>() as u64;
+ pass.set_vertex_buffer(0, cx.particle_buffer.slice(offset..));
+ pass.draw(0..6, 0..normal_count);
+ }
+ }
+
+ // The depth of field, then the share of the moment in the average.
+ let focus = camera
+ .focus
+ .filter(|f| camera.ortho_height.is_none() && f.blur > 0.0);
+ let mut post = PostUniform {
+ encode: [0.0, 0.0, 0.0, weight],
+ ..Default::default()
+ };
+ if let Some(f) = focus {
+ let blur = f.blur * height as f32 / 1080.0;
+ post.dof = [f.distance, blur, (blur * 1.6).min(40.0), DOF_TILE as f32];
+ }
+ self.queue
+ .write_buffer(&cx.post_buffer, 0, bytemuck::bytes_of(&post));
+ let (source, result) = if focus.is_some() {
+ self.depth_of_field(&mut encoder, cx);
+ (&cx.dof, Accumulated::Dof)
+ } else {
+ (&cx.hdr, Accumulated::Hdr)
+ };
+ if single {
+ // One moment is the average already.
+ cx.result = result;
+ } else {
+ let black = &self.black_hdr;
+ let group = self.post_group(cx, 0, [source, &cx.key, &cx.tiles, black, black]);
+ let clear = (moment == 0).then_some(wgpu::Color::TRANSPARENT);
+ fullscreen(
+ &mut encoder,
+ &self.post.accumulate,
+ &[&group],
+ &[&cx.accum],
+ clear,
+ );
+ cx.result = Accumulated::Accum;
+ }
+ self.submit(encoder.finish());
+ }
+
+ /// Writes the fog, the environment and the background of the scene into the frame
+ /// uniform. Returns the view and the level count of the environment panorama, when the
+ /// environment has one.
+ fn set_environment(
+ &self,
+ frame: &mut FrameUniform,
+ scene: &Scene,
+ ) -> Option<(wgpu::TextureView, u32)> {
+ match scene.fog {
+ Some(Fog::Linear { color, near, far }) => {
+ frame.fog = color.0.extend(1.0).to_array();
+ frame.fog_params = [near, near + (far - near).max(1e-6), 0.0, 0.0];
+ }
+ Some(Fog::Exp2 { color, density }) => {
+ frame.fog = color.0.extend(2.0).to_array();
+ frame.fog_params = [0.0, 0.0, density, 0.0];
+ }
+ None => {}
+ }
+ match &scene.background {
+ Background::Transparent => {}
+ Background::Color(c) => {
+ frame.background = [1.0, 0.0, 0.0, 0.0];
+ frame.background_color = c.0.extend(1.0).to_array();
+ }
+ Background::Environment { blur } => frame.background = [2.0, *blur, 0.0, 0.0],
+ }
+ match &scene.environment {
+ Environment::None => None,
+ Environment::Studio(studio) => {
+ // The softboxes give the diffuse light. The reflections come from the studio
+ // baked into a panorama.
+ let count = studio.softboxes.len().min(MAX_SOFTBOXES);
+ frame.env = [1.0, studio.intensity, studio.rotation, count as f32];
+ frame.env_sky = studio.sky.0.extend(0.0).to_array();
+ frame.env_horizon = studio.horizon.0.extend(0.0).to_array();
+ frame.env_ground = studio.ground.0.extend(0.0).to_array();
+ for (uniform, b) in frame.softboxes.iter_mut().zip(&studio.softboxes) {
+ let solid_angle = 4.0 * b.half_size.x.sin() * b.half_size.y.sin();
+ *uniform = GpuSoftBox {
+ direction: b.direction.extend(solid_angle).to_array(),
+ color: b.color.0.extend(0.0).to_array(),
+ };
+ }
+ Some(self.env_map(&studio.baked()))
+ }
+ Environment::Map {
+ map,
+ intensity,
+ rotation,
+ } => {
+ frame.env = [2.0, *intensity, *rotation, 0.0];
+ Some(self.env_map(map))
+ }
+ }
+ }
+
+ /// Renders the depth of the shadow casters into the shadow maps.
+ fn draw_shadow_maps(
+ &self,
+ encoder: &mut wgpu::CommandEncoder,
+ cx: &FrameContext,
+ items: &[DrawItem],
+ shadows: &[Option<GpuShadow>],
+ ) {
+ let matrix = size_of::<[f32; 16]>();
+ let draw_group = self.bind_group(
+ "shadow draws",
+ &self.shadow_draw_layout,
+ &[buffer_range(&cx.draw_buffer, 0, matrix)],
+ );
+ for (i, shadow) in shadows.iter().enumerate() {
+ let Some(shadow) = shadow else { continue };
+ let offset = i as u64 * UNIFORM_ALIGNMENT;
+ self.queue.write_buffer(
+ &cx.shadow_pass_buffer,
+ offset,
+ bytemuck::cast_slice(&shadow.view_proj),
+ );
+ let pass_group = self.bind_group(
+ "shadow pass",
+ &self.shadow_layout,
+ &[buffer_range(&cx.shadow_pass_buffer, offset, matrix)],
+ );
+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("shadow"),
+ depth_stencil_attachment: Some(depth_attachment(
+ &cx.shadow_layers[i],
+ 1.0,
+ wgpu::StoreOp::Store,
+ )),
+ ..Default::default()
+ });
+ pass.set_pipeline(&self.shadow_pipeline);
+ pass.set_bind_group(0, &pass_group, &[]);
+ for (slot, item) in items.iter().enumerate() {
+ if item.cast_shadow && !item.batched {
+ pass.set_bind_group(1, &draw_group, &[(slot as u64 * DRAW_STRIDE) as u32]);
+ item.draw(&mut pass, cx);
+ }
+ }
+ }
+ }
+
+ /// Fills the smaller levels of the reflection. Each level is a box filtered half of the
+ /// level before it.
+ fn blur_reflection(
+ &self,
+ encoder: &mut wgpu::CommandEncoder,
+ cx: &FrameContext,
+ targets: &ReflectionTargets,
+ ) {
+ let black = &self.black_hdr;
+ for level in 1..targets.levels as usize {
+ let source_width = (targets.width >> (level - 1)).max(1);
+ let source_height = (targets.height >> (level - 1)).max(1);
+ let slot = REFLECTION_SLOT + level as u64;
+ let uniform = PostUniform {
+ texel: [
+ 1.0 / source_width as f32,
+ 1.0 / source_height as f32,
+ 0.0,
+ 0.0,
+ ],
+ ..Default::default()
+ };
+ self.queue.write_buffer(
+ &cx.post_buffer,
+ slot * UNIFORM_ALIGNMENT,
+ bytemuck::bytes_of(&uniform),
+ );
+ let source = &targets.level_views[level - 1];
+ let group = self.post_group(cx, slot, [source, black, black, black, black]);
+ fullscreen(
+ encoder,
+ &self.post.down_rgba,
+ &[&group],
+ &[&targets.level_views[level]],
+ Some(wgpu::Color::TRANSPARENT),
+ );
+ }
+ }
+
+ /// The depth of field of the HDR frame into `cx.dof`.
+ fn depth_of_field(&self, encoder: &mut wgpu::CommandEncoder, cx: &FrameContext) {
+ let black = &self.black_hdr;
+ // The tile and half passes write the textures that the later passes read. So they
+ // bind placeholders for them.
+ let group = self.post_group(cx, 0, [&cx.hdr, &cx.key, black, black, black]);
+ fullscreen(encoder, &self.post.tile, &[&group], &[&cx.tiles], None);
+ fullscreen(
+ encoder,
+ &self.post.half,
+ &[&group],
+ &[&cx.half_hdr, &cx.half_key],
+ None,
+ );
+ let group = self.post_group(cx, 0, [&cx.hdr, &cx.key, &cx.tiles, black, black]);
+ fullscreen(encoder, &self.post.near, &[&group], &[&cx.near], None);
+ let group = self.post_group(
+ cx,
+ 0,
+ [&cx.hdr, &cx.key, &cx.near, &cx.half_hdr, &cx.half_key],
+ );
+ fullscreen(encoder, &self.post.dof, &[&group], &[&cx.dof], None);
+ }
+
+ /// Draws the meshes in `order`. The reflection pass skips the reflectors and culls the
+ /// other faces, because the mirror turns the triangles around.
+ fn draw_items(
+ &self,
+ pass: &mut wgpu::RenderPass<'_>,
+ items: &[DrawItem],
+ order: &[usize],
+ draw_groups: &[wgpu::BindGroup],
+ cx: &FrameContext,
+ reflection_pass: bool,
+ ) {
+ for &slot in order {
+ let item = &items[slot];
+ let m = item.material;
+ if reflection_pass && m.reflection > 0.0 {
+ continue;
+ }
+ let blend = if !m.is_blended() {
+ Blend::Opaque
+ } else if m.blending == Blending::Additive {
+ Blend::Additive
+ } else {
+ Blend::Normal
+ };
+ pass.set_pipeline(&self.pipeline(PipelineKey {
+ cull: cull_face(m.side, item.mirrored != reflection_pass),
+ blend,
+ depth_write: blend == Blend::Opaque || (blend == Blend::Normal && m.depth_write),
+ variant: item.variant,
+ reflection_pass,
+ }));
+ pass.set_bind_group(1, &draw_groups[slot], &[(slot as u64 * DRAW_STRIDE) as u32]);
+ item.draw(pass, cx);
+ }
+ }
+
+ /// Bloom, tone mapping and the encoding of the average of the moments into `target`
+ /// (premultiplied sRGB RGBA8).
+ fn post_process(
+ &self,
+ cx: &FrameContext,
+ renderer: &Renderer,
+ encoder: &mut wgpu::CommandEncoder,
+ target: &wgpu::TextureView,
+ ) {
+ let bloom = renderer.bloom.filter(|b| b.strength > 0.0);
+ let black = &self.black_hdr;
+ let texel = |width: u32, height: u32| [1.0 / width as f32, 1.0 / height as f32, 0.0, 0.0];
+ // The uniforms of the passes, from slot 1 of the post buffer.
+ let mut slots: Vec<PostUniform> = Vec::new();
+ let mut pass = |uniform: PostUniform,
+ pipeline: &wgpu::RenderPipeline,
+ source: &wgpu::TextureView,
+ aux: &wgpu::TextureView,
+ output: &wgpu::TextureView| {
+ slots.push(uniform);
+ let group = self.post_group(
+ cx,
+ slots.len() as u64,
+ [source, &cx.key, &cx.tiles, aux, black],
+ );
+ fullscreen(encoder, pipeline, &[&group], &[output], None);
+ };
+ if let Some(b) = bloom {
+ let threshold = b.threshold.max(0.0);
+ pass(
+ PostUniform {
+ bloom: [threshold, threshold * 0.5 + 1e-4, 0.0, b.strength],
+ texel: texel(cx.width, cx.height),
+ ..Default::default()
+ },
+ &self.post.bright,
+ cx.result(),
+ black,
+ &cx.bloom[0].0,
+ );
+ for i in 1..cx.bloom.len() {
+ let (source, width, height) = &cx.bloom[i - 1];
+ pass(
+ PostUniform {
+ texel: texel(*width, *height),
+ ..Default::default()
+ },
+ &self.post.down,
+ source,
+ black,
+ &cx.bloom[i].0,
+ );
+ }
+ let factors: [f32; BLOOM_LEVELS] = [1.0, 0.8, 0.6, 0.4, 0.2, 0.1];
+ for i in (0..cx.bloom.len() - 1).rev() {
+ let (source, width, height) = &cx.bloom[i + 1];
+ let f = factors[i + 1];
+ pass(
+ PostUniform {
+ bloom: [0.0, 0.0, (f + (1.2 - f - f) * b.radius).max(0.0), 0.0],
+ texel: texel(*width, *height),
+ ..Default::default()
+ },
+ &self.post.up,
+ source,
+ black,
+ &cx.bloom[i].0,
+ );
+ }
+ }
+ let tone = match renderer.tone_mapping {
+ ToneMapping::Linear => 0.0,
+ ToneMapping::Aces => 1.0,
+ ToneMapping::Neutral => 2.0,
+ };
+ pass(
+ PostUniform {
+ bloom: [0.0, 0.0, 0.0, bloom.map_or(0.0, |b| b.strength)],
+ encode: [renderer.exposure, tone, f32::from(bloom.is_some()), 1.0],
+ ..Default::default()
+ },
+ &self.post.encode,
+ cx.result(),
+ if bloom.is_some() {
+ &cx.bloom[0].0
+ } else {
+ black
+ },
+ target,
+ );
+
+ let stride = UNIFORM_ALIGNMENT as usize;
+ let mut data = vec![0u8; slots.len() * stride];
+ for (chunk, uniform) in data.chunks_mut(stride).zip(&slots) {
+ chunk[..size_of::<PostUniform>()].copy_from_slice(bytemuck::bytes_of(uniform));
+ }
+ self.queue
+ .write_buffer(&cx.post_buffer, UNIFORM_ALIGNMENT, &data);
+ }
+
+ /// Post processes the frame into the output texture of the context and reads it back.
+ fn finish(&self, cx: &FrameContext, renderer: &Renderer) -> Pixels {
+ let (width, height) = (cx.width, cx.height);
+ let mut encoder = self
+ .device
+ .create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
+ self.post_process(cx, renderer, &mut encoder, &cx.output_view);
+ encoder.copy_texture_to_buffer(
+ cx.output.as_image_copy(),
+ wgpu::TexelCopyBufferInfo {
+ buffer: &cx.readback,
+ layout: wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(cx.padded_row),
+ rows_per_image: Some(height),
+ },
+ },
+ cx.output.size(),
+ );
+ let submission = self.submit(encoder.finish());
+ let slice = cx.readback.slice(..);
+ let (sender, receiver) = std::sync::mpsc::channel();
+ slice.map_async(wgpu::MapMode::Read, move |result| {
+ let _ = sender.send(result);
+ });
+ let _ = self.device.poll(wgpu::PollType::Wait {
+ submission_index: Some(submission),
+ timeout: None,
+ });
+ let row = (width * 4) as usize;
+ let mut rgba = vec![0u8; row * height as usize];
+ if let Ok(Ok(())) = receiver.recv()
+ && let Ok(mapped) = slice.get_mapped_range()
+ {
+ for (dst, src) in rgba
+ .chunks_exact_mut(row)
+ .zip(mapped.chunks(cx.padded_row as usize))
+ {
+ dst.copy_from_slice(&src[..row]);
+ }
+ drop(mapped);
+ cx.readback.unmap();
+ }
+ Pixels {
+ width,
+ height,
+ rgba,
+ }
+ }
+}
+
+/// `view` for positions relative to the camera, which `view` moves to the origin: the
+/// matrix without its translation. `relative(view) * (p - camera)` is `view * p`. Without
+/// the large translation, a small part far from the origin keeps its precision.
+fn relative(view: Mat4) -> Mat4 {
+ Mat4::from_cols(view.x_axis, view.y_axis, view.z_axis, Vec4::W)
+}
+
+/// A depth test against a `DEPTH` target.
+fn depth_test(write: bool, compare: wgpu::CompareFunction) -> wgpu::DepthStencilState {
+ wgpu::DepthStencilState {
+ format: DEPTH,
+ depth_write_enabled: Some(write),
+ depth_compare: Some(compare),
+ stencil: wgpu::StencilState::default(),
+ bias: wgpu::DepthBiasState::default(),
+ }
+}
+
+/// The color targets of the scene pipelines: the HDR color with `blend`, and the depth key.
+/// Only the pipelines without blending write the key.
+fn scene_targets(blend: Option<wgpu::BlendState>) -> [Option<wgpu::ColorTargetState>; 2] {
+ let key_writes = if blend.is_none() {
+ wgpu::ColorWrites::ALL
+ } else {
+ wgpu::ColorWrites::empty()
+ };
+ [
+ Some(wgpu::ColorTargetState {
+ blend,
+ ..HDR.into()
+ }),
+ Some(wgpu::ColorTargetState {
+ write_mask: key_writes,
+ ..KEY.into()
+ }),
+ ]
+}
+
+/// A 2D texture with one layer, one mipmap level and one sample.
+fn texture_desc(
+ label: &str,
+ width: u32,
+ height: u32,
+ format: wgpu::TextureFormat,
+ usage: wgpu::TextureUsages,
+) -> wgpu::TextureDescriptor<'_> {
+ wgpu::TextureDescriptor {
+ label: Some(label),
+ size: wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format,
+ usage,
+ view_formats: &[],
+ }
+}
+
+/// `size` bytes of `buffer` from `offset`, for a uniform binding.
+fn buffer_range(buffer: &wgpu::Buffer, offset: u64, size: usize) -> wgpu::BindingResource<'_> {
+ wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer,
+ offset,
+ size: wgpu::BufferSize::new(size as u64),
+ })
+}
+
+fn color_attachment<'a>(
+ view: &'a wgpu::TextureView,
+ resolve_target: Option<&'a wgpu::TextureView>,
+ load: wgpu::LoadOp<wgpu::Color>,
+ store: wgpu::StoreOp,
+) -> wgpu::RenderPassColorAttachment<'a> {
+ wgpu::RenderPassColorAttachment {
+ view,
+ depth_slice: None,
+ resolve_target,
+ ops: wgpu::Operations { load, store },
+ }
+}
+
+fn depth_attachment(
+ view: &wgpu::TextureView,
+ clear: f32,
+ store: wgpu::StoreOp,
+) -> wgpu::RenderPassDepthStencilAttachment<'_> {
+ wgpu::RenderPassDepthStencilAttachment {
+ view,
+ depth_ops: Some(wgpu::Operations {
+ load: wgpu::LoadOp::Clear(clear),
+ store,
+ }),
+ stencil_ops: None,
+ }
+}
+
+/// Draws one triangle that covers `targets`. With `clear` the pass clears the targets first,
+/// otherwise it draws over them.
+fn fullscreen(
+ encoder: &mut wgpu::CommandEncoder,
+ pipeline: &wgpu::RenderPipeline,
+ groups: &[&wgpu::BindGroup],
+ targets: &[&wgpu::TextureView],
+ clear: Option<wgpu::Color>,
+) {
+ let load = clear.map_or(wgpu::LoadOp::Load, wgpu::LoadOp::Clear);
+ let attachments: Vec<_> = targets
+ .iter()
+ .map(|view| Some(color_attachment(view, None, load, wgpu::StoreOp::Store)))
+ .collect();
+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("post"),
+ color_attachments: &attachments,
+ ..Default::default()
+ });
+ pass.set_pipeline(pipeline);
+ for (index, group) in groups.iter().enumerate() {
+ pass.set_bind_group(index as u32, *group, &[]);
+ }
+ pass.draw(0..3, 0..1);
+}
+
+/// The face to cull for a material side. A mirror turns the triangles around.
+fn cull_face(side: Side, mirrored: bool) -> Option<wgpu::Face> {
+ match (side, mirrored) {
+ (Side::Double, _) => None,
+ (Side::Front, false) | (Side::Back, true) => Some(wgpu::Face::Back),
+ (Side::Back, false) | (Side::Front, true) => Some(wgpu::Face::Front),
+ }
+}
+
+/// The interleaved vertices of a geometry. `deformed` replaces the positions and normals.
+fn vertices_of(g: &Geometry, deformed: Option<(&[Vec3], &[Vec3])>) -> Vec<Vertex> {
+ (0..g.positions.len())
+ .map(|i| {
+ let (p, n) = match deformed {
+ Some((positions, normals)) => (positions[i], normals[i]),
+ None => (g.positions[i], g.normals.get(i).copied().unwrap_or(Vec3::Y)),
+ };
+ Vertex {
+ position: p.to_array(),
+ normal: n.to_array(),
+ uv: g.uvs.get(i).copied().unwrap_or_default().to_array(),
+ color: g.colors.get(i).copied().unwrap_or(Vec4::ONE).to_array(),
+ }
+ })
+ .collect()
+}
+
+fn draw_uniform(mesh: &Mesh, model: Mat4, normal_matrix: Mat4) -> DrawUniform {
+ let m = &mesh.material;
+ let uv_transforms = [
+ &m.map,
+ &m.emissive_map,
+ &m.metal_rough_map,
+ &m.normal_map,
+ &m.ao_map,
+ ]
+ .map(|t| {
+ t.as_ref().map_or([1.0, 1.0, 0.0, 0.0], |t| {
+ [t.repeat.x, t.repeat.y, t.offset.x, t.offset.y]
+ })
+ });
+ DrawUniform {
+ model: model.to_cols_array(),
+ normal_matrix: normal_matrix.to_cols_array(),
+ color: m.color.0.extend(m.opacity).to_array(),
+ emissive: (m.emissive.0 * m.emissive_intensity)
+ .extend(m.env_intensity)
+ .to_array(),
+ pbr: [m.metalness, m.roughness, m.clearcoat, m.clearcoat_roughness],
+ flags: [
+ f32::from(m.flat_shading),
+ f32::from(m.blending == Blending::Additive),
+ f32::from(m.fog),
+ f32::from(m.is_blended()),
+ ],
+ maps: [
+ f32::from(m.map.is_some()),
+ f32::from(m.emissive_map.is_some()),
+ f32::from(m.metal_rough_map.is_some()),
+ f32::from(mesh.receive_shadow),
+ ],
+ attrs: [
+ f32::from(!mesh.geometry.uvs.is_empty()),
+ f32::from(
+ !mesh.geometry.colors.is_empty()
+ || mesh
+ .instances
+ .as_ref()
+ .is_some_and(|i| !i.colors.is_empty()),
+ ),
+ m.reflection,
+ 0.0,
+ ],
+ uv_transforms,
+ detail: [
+ f32::from(m.normal_map.is_some()),
+ m.normal_scale,
+ f32::from(m.ao_map.is_some()),
+ 0.0,
+ ],
+ }
+}
+
+/// A light in the layout of `scene.wgsl`. `shadows` holds the fitted shadow maps.
+fn gpu_light(light: &LightInfo, shadows: &[Option<GpuShadow>]) -> GpuLight {
+ match light.kind {
+ LightKind::Directional { direction, shadow } => {
+ let index = shadow
+ .filter(|&i| shadows.get(i).is_some_and(Option::is_some))
+ .map_or(-1.0, |i| i as f32);
+ GpuLight {
+ color: light.color.extend(0.0).to_array(),
+ position: [0.0; 4],
+ direction: direction.extend(0.0).to_array(),
+ params: [0.0, 0.0, index, 0.0],
+ }
+ }
+ LightKind::Point {
+ position,
+ distance,
+ decay,
+ } => GpuLight {
+ color: light.color.extend(1.0).to_array(),
+ position: position.extend(distance).to_array(),
+ direction: [0.0, 0.0, 0.0, decay],
+ params: [0.0, 0.0, -1.0, 0.0],
+ },
+ LightKind::Spot {
+ position,
+ direction,
+ distance,
+ decay,
+ cos_outer,
+ cos_inner,
+ } => GpuLight {
+ color: light.color.extend(2.0).to_array(),
+ position: position.extend(distance).to_array(),
+ direction: direction.extend(decay).to_array(),
+ params: [cos_outer, cos_inner, -1.0, 0.0],
+ },
+ }
+}
+
+/// Fits a shadow map of `map_size` texels to each shadow casting light (two at most). `None`
+/// for a light with nothing to shade.
+fn fit_shadows(lights: &Lights, items: &[DrawItem], map_size: u32) -> Vec<Option<GpuShadow>> {
+ lights
+ .shadow_casters
+ .iter()
+ .take(MAX_SHADOWS)
+ .map(|(direction, settings)| {
+ let bounds = settings.bounds.unwrap_or_else(|| {
+ items
+ .iter()
+ .filter(|it| it.cast_shadow)
+ .fold(crate::Aabb::EMPTY, |acc, it| acc.union(it.bounds))
+ });
+ if bounds.is_empty() {
+ return None;
+ }
+ let f = fit(*direction, &bounds, map_size as usize);
+ Some(GpuShadow {
+ view_proj: f.view_proj.to_cols_array(),
+ params: [
+ f.texel_world,
+ f.depth_per_texel,
+ settings.softness.max(0.0),
+ settings.strength.clamp(0.0, 1.0),
+ ],
+ params2: [settings.bias, map_size as f32, 0.0, 0.0],
+ })
+ })
+ .collect()
+}
+
+/// Merges small rigid opaque meshes that look the same into batches. Their vertices move to
+/// the space of the batch and into `streamed`. The space of a batch is the world space moved
+/// to the position of its first mesh, so that the vertices keep their precision far from the
+/// origin. Returns the indices of the batches.
+fn batch(items: &mut Vec<DrawItem>, streamed: &mut Vec<Vertex>) -> Vec<u32> {
+ let texture_id = |t: &Option<Arc<Texture>>| t.as_ref().map_or(0, |t| Arc::as_ptr(t) as usize);
+ let mut groups: HashMap<BatchKey, Vec<usize>> = HashMap::new();
+ for (i, item) in items.iter().enumerate() {
+ if item.vertices.is_none()
+ || item.first_instance != 0
+ || item.material.is_blended()
+ || item.index_count > BATCH_MAX_INDICES
+ {
+ continue;
+ }
+ // The draw uniform without the matrices, and the textures, which it does not hold.
+ let mut look =
+ bytemuck::bytes_of(&item.uniform)[std::mem::offset_of!(DrawUniform, color)..].to_vec();
+ for texture in [
+ &item.material.map,
+ &item.material.emissive_map,
+ &item.material.metal_rough_map,
+ &item.material.normal_map,
+ &item.material.ao_map,
+ ] {
+ look.extend_from_slice(&texture_id(texture).to_ne_bytes());
+ }
+ let key = (
+ look,
+ item.variant,
+ item.material.side as u8,
+ item.mirrored,
+ item.cast_shadow,
+ );
+ groups.entry(key).or_default().push(i);
+ }
+ let mut groups: Vec<Vec<usize>> = groups.into_values().filter(|g| g.len() > 1).collect();
+ // The order of a HashMap changes from run to run. The sort keeps the draw order the same.
+ groups.sort_by_key(|g| g[0]);
+
+ let mut indices: Vec<u32> = Vec::new();
+ for members in groups {
+ let vertex_offset = (streamed.len() * size_of::<Vertex>()) as u64;
+ let index_start = indices.len();
+ let mut bounds = crate::Aabb::EMPTY;
+ let mut depth = f32::INFINITY;
+ let mut base = 0u32;
+ let origin = Mat4::from_cols_array(&items[members[0]].uniform.model)
+ .w_axis
+ .truncate();
+ for &i in &members {
+ let item = &mut items[i];
+ let g = &item.geometry;
+ let model = Mat4::from_cols_array(&item.uniform.model);
+ let normal_matrix = Mat4::from_cols_array(&item.uniform.normal_matrix);
+ let (linear, offset) = (Mat3::from_mat4(model), model.w_axis.truncate() - origin);
+ let positions: Vec<Vec3> = g.positions.iter().map(|p| linear * *p + offset).collect();
+ let normals: Vec<Vec3> = (0..g.positions.len())
+ .map(|k| {
+ normal_matrix.transform_vector3(g.normals.get(k).copied().unwrap_or(Vec3::Y))
+ })
+ .collect();
+ streamed.extend(vertices_of(g, Some((&positions, &normals))));
+ indices.extend(
+ g.indices
+ .iter()
+ .copied()
+ .filter(|&k| (k as usize) < g.positions.len())
+ .map(|k| k + base),
+ );
+ base += g.positions.len() as u32;
+ bounds = bounds.union(item.bounds);
+ depth = depth.min(item.depth);
+ item.batched = true;
+ }
+ let first = &items[members[0]];
+ let mut uniform = first.uniform;
+ uniform.model = Mat4::from_translation(origin).to_cols_array();
+ uniform.normal_matrix = Mat4::IDENTITY.to_cols_array();
+ let batch = DrawItem {
+ material: first.material,
+ geometry: Arc::clone(&first.geometry),
+ uniform,
+ vertices: None,
+ vertex_offset,
+ indices: None,
+ index_offset: (index_start * size_of::<u32>()) as u64,
+ index_count: (indices.len() - index_start) as u32,
+ first_instance: 0,
+ instance_count: 1,
+ batched: false,
+ cast_shadow: first.cast_shadow,
+ mirrored: first.mirrored,
+ depth,
+ bounds,
+ variant: first.variant,
+ };
+ items.push(batch);
+ }
+ indices
+}
+
+/// The order in which the items are drawn. The opaque items come first, grouped by pipeline
+/// and front to back within a group, because every pipeline switch stalls the GPU. The
+/// blended items follow from back to front.
+fn draw_order(items: &[DrawItem]) -> Vec<usize> {
+ let mut order: Vec<usize> = (0..items.len()).filter(|&i| !items[i].batched).collect();
+ order.sort_by(|&a, &b| {
+ let (ia, ib) = (&items[a], &items[b]);
+ match (ia.material.is_blended(), ib.material.is_blended()) {
+ (false, true) => std::cmp::Ordering::Less,
+ (true, false) => std::cmp::Ordering::Greater,
+ (false, false) => ia
+ .pipeline_rank()
+ .cmp(&ib.pipeline_rank())
+ .then(ia.depth.total_cmp(&ib.depth)),
+ (true, true) => ib.depth.total_cmp(&ia.depth),
+ }
+ });
+ order
+}
+
+impl FrameContext {
+ fn new(device: &wgpu::Device, width: u32, height: u32, shadow_size: u32) -> FrameContext {
+ let view = |descriptor: &wgpu::TextureDescriptor| {
+ device
+ .create_texture(descriptor)
+ .create_view(&wgpu::TextureViewDescriptor::default())
+ };
+ let multisampled = |label: &str, format: wgpu::TextureFormat| {
+ view(&wgpu::TextureDescriptor {
+ sample_count: MSAA,
+ ..texture_desc(
+ label,
+ width.max(1),
+ height.max(1),
+ format,
+ wgpu::TextureUsages::RENDER_ATTACHMENT,
+ )
+ })
+ };
+ let sampled = |label: &str, format: wgpu::TextureFormat, w: u32, h: u32| {
+ view(&texture_desc(
+ label,
+ w.max(1),
+ h.max(1),
+ format,
+ wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
+ ))
+ };
+ let buffer = |label: &str, size: u64, usage: wgpu::BufferUsages| {
+ device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some(label),
+ size,
+ usage: usage | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ })
+ };
+
+ let mut bloom = Vec::new();
+ let (mut w, mut h) = ((width / 2).max(1), (height / 2).max(1));
+ bloom.push((sampled("bloom", HDR, w, h), w, h));
+ while bloom.len() < BLOOM_LEVELS && w > 8 && h > 8 {
+ w = (w / 2).max(1);
+ h = (h / 2).max(1);
+ bloom.push((sampled("bloom", HDR, w, h), w, h));
+ }
+ let output = device.create_texture(&texture_desc(
+ "output",
+ width,
+ height,
+ OUTPUT,
+ wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
+ ));
+ let padded_row = (width * 4).next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT);
+ let (tiles_w, tiles_h) = (width.div_ceil(DOF_TILE), height.div_ceil(DOF_TILE));
+ let (half_w, half_h) = (width.div_ceil(2), height.div_ceil(2));
+ let (shadow_array, shadow_layers) = shadow_targets(device, shadow_size);
+ let uniform = wgpu::BufferUsages::UNIFORM;
+ FrameContext {
+ width,
+ height,
+ msaa_color: multisampled("msaa color", HDR),
+ msaa_key: multisampled("msaa key", KEY),
+ depth: multisampled("depth", DEPTH),
+ hdr: sampled("hdr", HDR, width, height),
+ key: sampled("key", KEY, width, height),
+ tiles: sampled("dof tiles", KEY, tiles_w, tiles_h),
+ near: sampled("dof near", KEY, tiles_w, tiles_h),
+ half_hdr: sampled("half", HDR, half_w, half_h),
+ half_key: sampled("half key", KEY, half_w, half_h),
+ dof: sampled("dof", HDR, width, height),
+ accum: sampled("accumulation", HDR, width, height),
+ bloom,
+ output_view: output.create_view(&wgpu::TextureViewDescriptor::default()),
+ output,
+ readback: device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("readback"),
+ size: u64::from(padded_row) * u64::from(height),
+ usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ }),
+ padded_row,
+ shadow_size,
+ shadow_array,
+ shadow_layers,
+ result: Accumulated::Accum,
+ reflection: None,
+ frame_buffer: buffer("frame", size_of::<FrameUniform>() as u64, uniform),
+ shadow_pass_buffer: buffer(
+ "shadow pass",
+ UNIFORM_ALIGNMENT * MAX_SHADOWS as u64,
+ uniform,
+ ),
+ post_buffer: buffer("post", UNIFORM_ALIGNMENT * POST_SLOTS, uniform),
+ draw_buffer: buffer("draws", DRAW_STRIDE * 256, uniform),
+ stream_buffer: buffer("streamed vertices", 1 << 20, wgpu::BufferUsages::VERTEX),
+ instance_buffer: buffer("instances", 1 << 16, wgpu::BufferUsages::VERTEX),
+ stream_index_buffer: buffer("streamed indices", 1 << 18, wgpu::BufferUsages::INDEX),
+ particle_buffer: buffer("particles", 1 << 16, wgpu::BufferUsages::VERTEX),
+ }
+ }
+
+ /// Makes the reflection targets at this size, unless they exist already.
+ fn prepare_reflection(&mut self, device: &wgpu::Device, width: u32, height: u32) {
+ if self
+ .reflection
+ .as_ref()
+ .is_none_or(|r| r.width != width || r.height != height)
+ {
+ self.reflection = Some(ReflectionTargets::new(device, width, height));
+ }
+ }
+
+ /// The finished HDR frame, see [`Accumulated`].
+ fn result(&self) -> &wgpu::TextureView {
+ match self.result {
+ Accumulated::Accum => &self.accum,
+ Accumulated::Hdr => &self.hdr,
+ Accumulated::Dof => &self.dof,
+ }
+ }
+
+ fn resize_shadows(&mut self, device: &wgpu::Device, size: u32) {
+ (self.shadow_array, self.shadow_layers) = shadow_targets(device, size);
+ self.shadow_size = size;
+ }
+}
+
+/// The targets of the reflection: an HDR image with blurred levels, its depth and key
+/// targets, and the frame uniform of the mirrored view.
+struct ReflectionTargets {
+ width: u32,
+ height: u32,
+ levels: u32,
+ /// All levels, for sampling.
+ view: wgpu::TextureView,
+ /// One view per level, for rendering.
+ level_views: Vec<wgpu::TextureView>,
+ key: wgpu::TextureView,
+ depth: wgpu::TextureView,
+ frame_buffer: wgpu::Buffer,
+}
+
+impl ReflectionTargets {
+ fn new(device: &wgpu::Device, width: u32, height: u32) -> Self {
+ let levels = crate::render::reflection::level_count(width as usize, height as usize) as u32;
+ let texture = device.create_texture(&wgpu::TextureDescriptor {
+ mip_level_count: levels,
+ ..texture_desc(
+ "reflection",
+ width,
+ height,
+ HDR,
+ wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
+ )
+ });
+ let level_views = (0..levels)
+ .map(|level| {
+ texture.create_view(&wgpu::TextureViewDescriptor {
+ base_mip_level: level,
+ mip_level_count: Some(1),
+ ..Default::default()
+ })
+ })
+ .collect();
+ let attachment = |label: &str, format: wgpu::TextureFormat| {
+ device
+ .create_texture(&texture_desc(
+ label,
+ width,
+ height,
+ format,
+ wgpu::TextureUsages::RENDER_ATTACHMENT,
+ ))
+ .create_view(&wgpu::TextureViewDescriptor::default())
+ };
+ Self {
+ width,
+ height,
+ levels,
+ view: texture.create_view(&wgpu::TextureViewDescriptor::default()),
+ level_views,
+ key: attachment("reflection key", KEY),
+ depth: attachment("reflection depth", DEPTH),
+ frame_buffer: device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("reflection frame"),
+ size: size_of::<FrameUniform>() as u64,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ }),
+ }
+ }
+}
+
+/// The shadow maps as one array view for sampling and one view per layer for rendering.
+fn shadow_targets(device: &wgpu::Device, size: u32) -> (wgpu::TextureView, Vec<wgpu::TextureView>) {
+ let texture = device.create_texture(&wgpu::TextureDescriptor {
+ size: wgpu::Extent3d {
+ width: size,
+ height: size,
+ depth_or_array_layers: MAX_SHADOWS as u32,
+ },
+ ..texture_desc(
+ "shadow maps",
+ size,
+ size,
+ DEPTH,
+ wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
+ )
+ });
+ let array = texture.create_view(&wgpu::TextureViewDescriptor {
+ dimension: Some(wgpu::TextureViewDimension::D2Array),
+ ..Default::default()
+ });
+ let layers = (0..MAX_SHADOWS as u32)
+ .map(|layer| {
+ texture.create_view(&wgpu::TextureViewDescriptor {
+ dimension: Some(wgpu::TextureViewDimension::D2),
+ base_array_layer: layer,
+ array_layer_count: Some(1),
+ ..Default::default()
+ })
+ })
+ .collect();
+ (array, layers)
+}
diff --git a/fframes-three-d/src/gpu/post.wgsl b/fframes-three-d/src/gpu/post.wgsl
new file mode 100644
index 00000000..213494c8
--- /dev/null
+++ b/fframes-three-d/src/gpu/post.wgsl
@@ -0,0 +1,328 @@
+// The post processing passes of the GPU renderer: depth of field, motion blur accumulation,
+// bloom, and the final tone mapping and encoding. They follow `render/post.rs`.
+
+struct Post {
+ // focus distance, blur (pixels), max blur, tile size
+ dof: vec4f,
+ // threshold, knee, up weight, strength
+ bloom: vec4f,
+ // exposure, tone mapping (0 linear, 1 aces, 2 neutral), has bloom, accumulate weight
+ encode: vec4f,
+ // texel size of the source (1 / width, 1 / height), 0, 0
+ texel: vec4f,
+}
+
+@group(0) @binding(0) var<uniform> post: Post;
+@group(0) @binding(1) var src: texture_2d<f32>;
+@group(0) @binding(2) var src_sampler: sampler;
+@group(0) @binding(3) var depth_key: texture_2d<f32>;
+@group(0) @binding(4) var tiles: texture_2d<f32>;
+// The bloom in the encoding pass, the half resolution frame in the depth of field.
+@group(0) @binding(5) var aux_tex: texture_2d<f32>;
+// The half resolution depth keys in the depth of field.
+@group(0) @binding(6) var half_key: texture_2d<f32>;
+
+struct FullscreenOut {
+ @builtin(position) clip: vec4f,
+ @location(0) uv: vec2f,
+}
+
+@vertex
+fn vs_fullscreen(@builtin(vertex_index) index: u32) -> FullscreenOut {
+ let uv = vec2f(f32((index << 1u) & 2u), f32(index & 2u));
+ var out: FullscreenOut;
+ out.clip = vec4f(uv * 2.0 - 1.0, 0.0, 1.0);
+ out.uv = vec2f(uv.x, 1.0 - uv.y);
+ return out;
+}
+
+// The depth of field.
+
+// The blur radius of a depth key (1 / distance, 0 for the background).
+fn coc_of(key: f32) -> f32 {
+ return min(post.dof.y * abs(1.0 - post.dof.x * key), post.dof.z);
+}
+
+// The largest blur in a tile of the depth buffer. The blur grows with the distance from the
+// focus on both sides. So it is largest at the nearest or at the farthest point of the tile.
+// Gathers find the key range of the tile, four keys per fetch.
+@fragment
+fn fs_tile(in: FullscreenOut) -> @location(0) vec4f {
+ let tile = i32(post.dof.w);
+ let origin = vec2i(in.clip.xy) * tile;
+ let size = vec2f(textureDimensions(depth_key));
+ var near = 0.0;
+ var far = 1e30;
+ for (var y = 0; y < tile; y += 2) {
+ for (var x = 0; x < tile; x += 2) {
+ // The center of a 2x2 block. The sampler clamps the blocks past the edge.
+ let p = (vec2f(origin + vec2i(x, y)) + 1.0) / size;
+ let keys = textureGather(0, depth_key, src_sampler, p);
+ near = max(near, max(max(keys.x, keys.y), max(keys.z, keys.w)));
+ far = min(far, min(min(keys.x, keys.y), min(keys.z, keys.w)));
+ }
+ }
+ return vec4f(max(coc_of(near), coc_of(far)), 0.0, 0.0, 1.0);
+}
+
+// The largest blur in the tiles around each tile. This is how far the pixels of the tile
+// gather.
+@fragment
+fn fs_near(in: FullscreenOut) -> @location(0) vec4f {
+ let t = vec2i(in.clip.xy);
+ let tile = i32(post.dof.w);
+ let tsize = vec2i(textureDimensions(tiles));
+ let reach = i32(ceil(post.dof.z / f32(tile)));
+ var m = 0.0;
+ for (var dy = -reach; dy <= reach; dy++) {
+ for (var dx = -reach; dx <= reach; dx++) {
+ let q = clamp(t + vec2i(dx, dy), vec2i(0), tsize - 1);
+ m = max(m, textureLoad(tiles, q, 0).r);
+ }
+ }
+ return vec4f(m, 0.0, 0.0, 1.0);
+}
+
+// Samples farther than this many pixels from their pixel come from the half resolution
+// frame. The blur is wide there, and the cache holds more of the smaller frame.
+const DOF_INNER: f32 = 6.0;
+
+struct HalfOut {
+ @location(0) color: vec4f,
+ @location(1) key: vec4f,
+}
+
+// The frame and its depth keys, averaged over 2x2 pixels.
+@fragment
+fn fs_half(in: FullscreenOut) -> HalfOut {
+ let origin = vec2i(in.clip.xy) * 2;
+ let size = vec2i(textureDimensions(src));
+ var color = vec4f(0.0);
+ var key = 0.0;
+ for (var y = 0; y < 2; y++) {
+ for (var x = 0; x < 2; x++) {
+ let p = min(origin + vec2i(x, y), size - 1);
+ color += textureLoad(src, p, 0);
+ key += textureLoad(depth_key, p, 0).r;
+ }
+ }
+ var out: HalfOut;
+ out.color = color * 0.25;
+ out.key = vec4f(key * 0.25, 0.0, 0.0, 1.0);
+ return out;
+}
+
+// Gathering depth of field. The samples lie on a golden angle spiral, out to the largest
+// blur nearby. A sample counts when its own blur reaches this pixel. Samples behind a sharp
+// pixel blur only a little into it.
+@fragment
+fn fs_dof(in: FullscreenOut) -> @location(0) vec4f {
+ let p = vec2i(in.clip.xy);
+ let size = vec2i(textureDimensions(src));
+ let tile = i32(post.dof.w);
+ // Here `tiles` holds the output of `fs_near`.
+ let radius_max = textureLoad(tiles, p / tile, 0).r;
+ let center = textureLoad(src, p, 0);
+ if (radius_max < 0.5) {
+ return center;
+ }
+ let center_key = textureLoad(depth_key, p, 0).r;
+ let center_coc = coc_of(center_key);
+ var sum = center;
+ var count = 1.0;
+ var radius = 0.8;
+ var angle = 0.0;
+ // The inner samples come from the full frame. Each source has its own loop, because a
+ // branch in one loop makes the GPU fetch from both sources.
+ loop {
+ if (radius >= min(radius_max, DOF_INNER)) {
+ break;
+ }
+ // A sample past the edge takes the edge pixel.
+ let s = clamp(vec2i(round(vec2f(p) + vec2f(cos(angle), sin(angle)) * radius)), vec2i(0), size - 1);
+ let key = textureLoad(depth_key, s, 0).r;
+ var sample_coc = coc_of(key);
+ // The sample is farther away than the center (it has a smaller key).
+ if (key < center_key) {
+ sample_coc = min(sample_coc, center_coc * 2.0);
+ }
+ let m = clamp(sample_coc - radius + 0.5, 0.0, 1.0);
+ sum += mix(sum / count, textureLoad(src, s, 0), m);
+ count += 1.0;
+ radius += 1.6 / radius;
+ angle += 2.399963;
+ }
+ // The outer samples come from the half resolution frame, at half the density. They are
+ // 2x2 averages already.
+ let half_size = vec2i(textureDimensions(aux_tex));
+ loop {
+ if (radius >= radius_max) {
+ break;
+ }
+ // The 2x2 block that contains the sample point.
+ let offset = vec2f(cos(angle), sin(angle)) * radius;
+ let s = clamp(vec2i(floor((vec2f(p) + 0.5 + offset) * 0.5)), vec2i(0), half_size - 1);
+ let key = textureLoad(half_key, s, 0).r;
+ var sample_coc = coc_of(key);
+ if (key < center_key) {
+ sample_coc = min(sample_coc, center_coc * 2.0);
+ }
+ let m = clamp(sample_coc - radius + 0.5, 0.0, 1.0);
+ sum += mix(sum / count, textureLoad(aux_tex, s, 0), m);
+ count += 1.0;
+ radius += 3.2 / radius;
+ angle += 2.399963;
+ }
+ return sum / count;
+}
+
+// Adds a weighted moment to the motion blur average. The pipeline blends additively.
+@fragment
+fn fs_accumulate(in: FullscreenOut) -> @location(0) vec4f {
+ return textureLoad(src, vec2i(in.clip.xy), 0) * post.encode.w;
+}
+
+// The bloom.
+
+// The bright parts of the frame at half size, with a soft knee at the threshold.
+@fragment
+fn fs_bright(in: FullscreenOut) -> @location(0) vec4f {
+ let d = post.texel.xy;
+ let c = (textureSampleLevel(src, src_sampler, in.uv + vec2f(-0.5, -0.5) * d, 0.0)
+ + textureSampleLevel(src, src_sampler, in.uv + vec2f(0.5, -0.5) * d, 0.0)
+ + textureSampleLevel(src, src_sampler, in.uv + vec2f(-0.5, 0.5) * d, 0.0)
+ + textureSampleLevel(src, src_sampler, in.uv + vec2f(0.5, 0.5) * d, 0.0)).rgb * 0.25;
+ let brightness = max(c.r, max(c.g, c.b));
+ let threshold = post.bloom.x;
+ let knee = post.bloom.y;
+ var soft = clamp(brightness - threshold + knee, 0.0, 2.0 * knee);
+ soft = soft * soft / (4.0 * knee);
+ let contribution = max(soft, brightness - threshold) / max(brightness, 1e-4);
+ return vec4f(c * max(contribution, 0.0), 1.0);
+}
+
+// The source at half size: the average of four bilinear samples.
+fn down(uv: vec2f) -> vec4f {
+ let d = post.texel.xy;
+ let c = textureSampleLevel(src, src_sampler, uv + vec2f(-d.x, -d.y), 0.0)
+ + textureSampleLevel(src, src_sampler, uv + vec2f(d.x, -d.y), 0.0)
+ + textureSampleLevel(src, src_sampler, uv + vec2f(-d.x, d.y), 0.0)
+ + textureSampleLevel(src, src_sampler, uv + vec2f(d.x, d.y), 0.0);
+ return c * 0.25;
+}
+
+@fragment
+fn fs_down(in: FullscreenOut) -> @location(0) vec4f {
+ return vec4f(down(in.uv).rgb, 1.0);
+}
+
+// `fs_down` that keeps the coverage, for the levels of the reflection.
+@fragment
+fn fs_down_rgba(in: FullscreenOut) -> @location(0) vec4f {
+ return down(in.uv);
+}
+
+// The next smaller level through a 3x3 tent filter, times the level weight. The pipeline
+// blends additively.
+@fragment
+fn fs_up(in: FullscreenOut) -> @location(0) vec4f {
+ let d = post.texel.xy;
+ var sum = textureSampleLevel(src, src_sampler, in.uv, 0.0).rgb * 4.0;
+ sum = sum + (textureSampleLevel(src, src_sampler, in.uv + vec2f(-d.x, 0.0), 0.0).rgb
+ + textureSampleLevel(src, src_sampler, in.uv + vec2f(d.x, 0.0), 0.0).rgb
+ + textureSampleLevel(src, src_sampler, in.uv + vec2f(0.0, -d.y), 0.0).rgb
+ + textureSampleLevel(src, src_sampler, in.uv + vec2f(0.0, d.y), 0.0).rgb) * 2.0;
+ sum = sum + textureSampleLevel(src, src_sampler, in.uv + vec2f(-d.x, -d.y), 0.0).rgb
+ + textureSampleLevel(src, src_sampler, in.uv + vec2f(d.x, -d.y), 0.0).rgb
+ + textureSampleLevel(src, src_sampler, in.uv + vec2f(-d.x, d.y), 0.0).rgb
+ + textureSampleLevel(src, src_sampler, in.uv + vec2f(d.x, d.y), 0.0).rgb;
+ return vec4f(sum * (post.bloom.z / 16.0), 0.0);
+}
+
+// The encoding.
+
+// ACES filmic tone mapping, as in three.js.
+fn aces(color: vec3f) -> vec3f {
+ let input = mat3x3f(
+ vec3f(0.59719, 0.07600, 0.02840),
+ vec3f(0.35458, 0.90834, 0.13383),
+ vec3f(0.04823, 0.01566, 0.83777),
+ );
+ let output = mat3x3f(
+ vec3f(1.60475, -0.10208, -0.00327),
+ vec3f(-0.53108, 1.10813, -0.07276),
+ vec3f(-0.07367, -0.00605, 1.07602),
+ );
+ let v = input * (color / 0.6);
+ let a = v * (v + 0.0245786) - 0.000090537;
+ let b = v * (0.983729 * v + 0.432951) + 0.238081;
+ return clamp(output * (a / b), vec3f(0.0), vec3f(1.0));
+}
+
+// Khronos PBR Neutral tone mapping.
+fn neutral(color_in: vec3f) -> vec3f {
+ let start = 0.8 - 0.04;
+ let desaturation = 0.15;
+ var color = color_in;
+ let x = min(color.r, min(color.g, color.b));
+ var offset = 0.04;
+ if (x < 0.08) {
+ offset = x - 6.25 * x * x;
+ }
+ color -= offset;
+ let peak = max(color.r, max(color.g, color.b));
+ if (peak < start) {
+ return max(color, vec3f(0.0));
+ }
+ let d = 1.0 - start;
+ let new_peak = 1.0 - d * d / (peak + d - start);
+ color *= new_peak / peak;
+ let g = 1.0 - 1.0 / (desaturation * (peak - new_peak) + 1.0);
+ return max(mix(color, vec3f(new_peak), g), vec3f(0.0));
+}
+
+fn to_srgb(c: f32) -> f32 {
+ if (c <= 0.0031308) {
+ return c * 12.92;
+ }
+ return 1.055 * pow(c, 1.0 / 2.4) - 0.055;
+}
+
+// The 4x4 Bayer matrix ([[0, 8, 2, 10], [12, 4, 14, 6], [3, 11, 1, 9], [15, 7, 13, 5]]).
+// The shader computes it, because a table in a function is built again for each pixel.
+fn bayer(p: vec2i) -> f32 {
+ let x = p.x & 3;
+ let y = p.y & 3;
+ let fine = 2 * ((x & 1) ^ (y & 1)) + (y & 1);
+ let coarse = 2 * (((x >> 1) & 1) ^ ((y >> 1) & 1)) + ((y >> 1) & 1);
+ return (f32(4 * fine + coarse) + 0.5) / 16.0;
+}
+
+// Adds the bloom, applies the exposure and the tone mapping, and encodes premultiplied sRGB
+// with ordered dithering.
+@fragment
+fn fs_encode(in: FullscreenOut) -> @location(0) vec4f {
+ let p = vec2i(in.clip.xy);
+ var px = textureLoad(src, p, 0);
+ if (post.encode.z > 0.5) {
+ px = vec4f(px.rgb + textureSampleLevel(aux_tex, src_sampler, in.uv, 0.0).rgb * post.bloom.w, px.a);
+ }
+ let rgb = max(px.rgb, vec3f(0.0)) * post.encode.x;
+ // Light without coverage (glows, additive surfaces) becomes partly opaque.
+ let alpha = clamp(max(px.a, min(max(rgb.r, max(rgb.g, rgb.b)), 1.0)), 0.0, 1.0);
+ if (alpha <= 0.0) {
+ return vec4f(0.0);
+ }
+ let straight = rgb / alpha;
+ var mapped = clamp(straight, vec3f(0.0), vec3f(1.0));
+ let tone = i32(post.encode.y);
+ if (tone == 1) {
+ mapped = aces(straight);
+ } else if (tone == 2) {
+ mapped = clamp(neutral(straight), vec3f(0.0), vec3f(1.0));
+ }
+ let a8 = floor(alpha * 255.0 + 0.5) / 255.0;
+ let dither = (bayer(p) - 0.5) / 255.0;
+ let encoded = vec3f(to_srgb(mapped.r), to_srgb(mapped.g), to_srgb(mapped.b));
+ return vec4f(clamp((encoded + dither) * a8, vec3f(0.0), vec3f(1.0)), a8);
+}
diff --git a/fframes-three-d/src/gpu/scene.wgsl b/fframes-three-d/src/gpu/scene.wgsl
new file mode 100644
index 00000000..2bbb8bf8
--- /dev/null
+++ b/fframes-three-d/src/gpu/scene.wgsl
@@ -0,0 +1,732 @@
+// The geometry, background and particle passes of the GPU renderer.
+// The shading follows `render/shade.rs` function by function, so both renderers agree.
+
+const PI: f32 = 3.14159265;
+
+struct Light {
+ // rgb, kind (0 directional, 1 point, 2 spot)
+ color: vec4f,
+ // xyz, cutoff distance
+ position: vec4f,
+ // xyz, decay
+ direction: vec4f,
+ // cos outer, cos inner, shadow map index (-1 for none), 0
+ params: vec4f,
+}
+
+struct SoftBox {
+ // xyz direction, solid angle
+ direction: vec4f,
+ // rgb, 0
+ color: vec4f,
+}
+
+struct Shadow {
+ view_proj: mat4x4f,
+ // world size of a texel, depth per texel, softness (texels), strength
+ params: vec4f,
+ // bias (texels), map size, 0, 0
+ params2: vec4f,
+}
+
+struct Frame {
+ view_proj: mat4x4f,
+ inv_view_proj: mat4x4f,
+ // `view_proj` for positions relative to the camera
+ view_proj_rel: mat4x4f,
+ // xyz, 1 for an orthographic camera
+ camera: vec4f,
+ // xyz, 0
+ forward: vec4f,
+ // width, height, focal length (pixels per unit at distance 1), near
+ viewport: vec4f,
+ // rgb, 1 with a hemisphere light
+ ambient: vec4f,
+ hemi_sky: vec4f,
+ hemi_ground: vec4f,
+ // rgb, kind (0 none, 1 linear, 2 exp2)
+ fog: vec4f,
+ // near, far, density, 0
+ fog_params: vec4f,
+ // kind (0 none, 1 studio, 2 map), intensity, rotation, softbox count
+ env: vec4f,
+ env_sky: vec4f,
+ env_horizon: vec4f,
+ env_ground: vec4f,
+ // kind (0 transparent, 1 color, 2 environment), blur, 0, 0
+ background: vec4f,
+ background_color: vec4f,
+ // light count, environment map levels, reflection levels (0 without a reflection), 0
+ counts: vec4f,
+ // the plane of the reflector: xyz normal, w offset
+ clip_plane: vec4f,
+ lights: array<Light, 16>,
+ softboxes: array<SoftBox, 8>,
+ shadows: array<Shadow, 2>,
+}
+
+struct Draw {
+ model: mat4x4f,
+ normal_matrix: mat4x4f,
+ // rgb, opacity
+ color: vec4f,
+ // rgb times intensity, environment intensity
+ emissive: vec4f,
+ // metalness, roughness, clearcoat, clearcoat roughness
+ pbr: vec4f,
+ // flat shading, additive, fog, blended
+ flags: vec4f,
+ // has map, has emissive map, has metal rough map, receives shadows
+ maps: vec4f,
+ // has uv, has color, reflection, 0
+ attrs: vec4f,
+ // the uv repeat and offset of each map: color, emissive, metal rough, normal, occlusion
+ uv_transforms: array<vec4f, 5>,
+ // has normal map, normal scale, has ao map, 0
+ detail: vec4f,
+}
+
+// The pipeline constants of a material (`Variant` in `mod.rs`). A material compiles only the
+// paths that it uses. This keeps the shader small enough to run at full SIMD width. The
+// background and particle pipelines use the default values.
+override SHADING: u32 = 0u; // 0 standard, 1 unlit, 2 shadow catcher, 3 normals
+override ENVIRONMENT: u32 = 255u; // 0 none, 1 studio, 2 map, 255 from the frame
+override CLEARCOAT: bool = true;
+override TEXTURED: bool = true;
+override FOG: bool = true;
+override LIGHTS: u32 = 255u; // the light count, 255 from the frame
+override REFLECTION: bool = false; // the material shows the reflection of the scene
+override REFLECTION_PASS: bool = false; // draws the reflection: nothing behind the reflector
+override NORMAL_MAP: bool = false;
+
+@group(0) @binding(0) var<uniform> frame: Frame;
+@group(0) @binding(1) var shadow_maps: texture_depth_2d_array;
+@group(0) @binding(2) var shadow_sampler: sampler_comparison;
+@group(0) @binding(3) var env_tex: texture_2d<f32>;
+@group(0) @binding(4) var env_sampler: sampler;
+// The scene in the mirror of the reflector. The blurred levels are for rough surfaces.
+@group(0) @binding(5) var reflection_tex: texture_2d<f32>;
+@group(0) @binding(6) var reflection_sampler: sampler;
+
+@group(1) @binding(0) var<uniform> draw: Draw;
+@group(1) @binding(1) var map_tex: texture_2d<f32>;
+@group(1) @binding(2) var emissive_tex: texture_2d<f32>;
+@group(1) @binding(3) var mr_tex: texture_2d<f32>;
+@group(1) @binding(4) var tex_sampler: sampler;
+@group(1) @binding(5) var normal_tex: texture_2d<f32>;
+@group(1) @binding(6) var ao_tex: texture_2d<f32>;
+
+// The smoothstep of `render/shade.rs`. The formula is explicit, so that both renderers
+// compute the same value.
+fn smooth_step(e0: f32, e1: f32, x: f32) -> f32 {
+ let t = clamp((x - e0) / (e1 - e0), 0.0, 1.0);
+ return t * t * (3.0 - 2.0 * t);
+}
+
+// The largest component of `v`.
+fn largest(v: vec3f) -> f32 {
+ return max(v.x, max(v.y, v.z));
+}
+
+fn normalize_or(v: vec3f, fallback: vec3f) -> vec3f {
+ let l = length(v);
+ if (l > 1e-8) {
+ return v / l;
+ }
+ return fallback;
+}
+
+// The environment.
+
+fn rotate_y(v: vec3f, angle: f32) -> vec3f {
+ if (angle == 0.0) {
+ return v;
+ }
+ let s = sin(angle);
+ let c = cos(angle);
+ return vec3f(c * v.x + s * v.z, v.y, -s * v.x + c * v.z);
+}
+
+fn gradient(y: f32, softness: f32) -> vec3f {
+ let width = 0.08 + softness * 0.6;
+ if (y >= 0.0) {
+ return mix(frame.env_horizon.rgb, frame.env_sky.rgb, smooth_step(0.0, width + 0.35, y));
+ }
+ return mix(frame.env_horizon.rgb, frame.env_ground.rgb, smooth_step(0.0, width, -y));
+}
+
+fn equirect_uv(dir: vec3f) -> vec2f {
+ let d = normalize_or(dir, vec3f(0.0, 1.0, 0.0));
+ return vec2f(atan2(d.z, d.x) / (2.0 * PI) + 0.5, 0.5 - asin(clamp(d.y, -1.0, 1.0)) / PI);
+}
+
+fn light_count() -> i32 {
+ if (LIGHTS == 255u) {
+ return i32(frame.counts.x);
+ }
+ return i32(LIGHTS);
+}
+
+fn env_kind() -> i32 {
+ if (ENVIRONMENT == 255u) {
+ return i32(frame.env.x);
+ }
+ return i32(ENVIRONMENT);
+}
+
+fn env_radiance(dir_in: vec3f, roughness: f32) -> vec3f {
+ let kind = env_kind();
+ let intensity = frame.env.y;
+ if (kind == 1 || kind == 2) {
+ // A panorama: the baked studio or the environment map.
+ let dir = rotate_y(dir_in, -frame.env.z);
+ let levels = frame.counts.y;
+ let lod = min(sqrt(clamp(roughness, 0.0, 1.0)) * (levels - 1.0), levels - 1.0);
+ return textureSampleLevel(env_tex, env_sampler, equirect_uv(dir), lod).rgb * intensity;
+ }
+ return vec3f(0.0);
+}
+
+// The reflection of the scene at a pixel position, blurred for `roughness`. Returns the
+// premultiplied color and the coverage.
+fn planar_reflection(screen: vec2f, roughness: f32) -> vec4f {
+ let uv = screen / frame.viewport.xy;
+ let last = frame.counts.z - 1.0;
+ let lod = min(sqrt(clamp(roughness, 0.0, 1.0)) * last, last);
+ return textureSampleLevel(reflection_tex, reflection_sampler, uv, lod);
+}
+
+fn env_irradiance(n_in: vec3f) -> vec3f {
+ let kind = env_kind();
+ let intensity = frame.env.y;
+ let n = rotate_y(n_in, -frame.env.z);
+ if (kind == 1) {
+ var color = gradient(n.y, 1.0);
+ let count = i32(frame.env.w);
+ for (var i = 0; i < count; i++) {
+ let b = &frame.softboxes[i];
+ let direction = b.direction;
+ color += b.color.rgb * (direction.w * max(dot(n, direction.xyz), 0.0) / PI);
+ }
+ return color * intensity;
+ }
+ if (kind == 2) {
+ return textureSampleLevel(env_tex, env_sampler, equirect_uv(n), frame.counts.y - 1.0).rgb * intensity;
+ }
+ return vec3f(0.0);
+}
+
+// The lighting.
+
+fn attenuation(distance: f32, cutoff: f32, decay: f32) -> f32 {
+ var att = 1.0 / pow(max(distance, 0.01), decay);
+ if (cutoff > 0.0) {
+ let x = clamp(1.0 - pow(distance / cutoff, 4.0), 0.0, 1.0);
+ att = att * x * x;
+ }
+ return att;
+}
+
+fn ggx(n_dot_h: f32, alpha: f32) -> f32 {
+ let a2 = alpha * alpha;
+ let d = n_dot_h * n_dot_h * (a2 - 1.0) + 1.0;
+ return a2 / (PI * d * d);
+}
+
+fn smith_visibility(n_dot_l: f32, n_dot_v: f32, alpha: f32) -> f32 {
+ let a2 = alpha * alpha;
+ let gv = n_dot_l * sqrt(n_dot_v * n_dot_v * (1.0 - a2) + a2);
+ let gl = n_dot_v * sqrt(n_dot_l * n_dot_l * (1.0 - a2) + a2);
+ return 0.5 / max(gv + gl, 1e-6);
+}
+
+fn env_brdf(roughness: f32, n_dot_v: f32) -> vec2f {
+ let c0 = vec4f(-1.0, -0.0275, -0.572, 0.022);
+ let c1 = vec4f(1.0, 0.0425, 1.04, -0.04);
+ let r = c0 * roughness + c1;
+ let a004 = min(r.x * r.x, exp2(-9.28 * n_dot_v)) * r.x + r.y;
+ return vec2f(a004 * -1.04 + r.z, a004 * 1.04 + r.w);
+}
+
+// The visibility of a point in shadow map `index`: 1 when lit, 1 - strength in full shadow.
+// It is the average of a 4x4 grid of bilinear comparisons.
+fn shadow_visibility(index: i32, position: vec3f, normal: vec3f, n_dot_l: f32) -> f32 {
+ let s = &frame.shadows[index];
+ let params = s.params;
+ let offset = normal * params.x * (1.0 + 2.0 * (1.0 - clamp(n_dot_l, 0.0, 1.0)));
+ let clip = s.view_proj * vec4f(position + offset, 1.0);
+ let p = clip.xyz / clip.w;
+ let uv = vec2f(p.x * 0.5 + 0.5, 0.5 - p.y * 0.5);
+ if (uv.x <= 0.0 || uv.x >= 1.0 || uv.y <= 0.0 || uv.y >= 1.0 || p.z > 1.0) {
+ return 1.0;
+ }
+ let params2 = s.params2;
+ let z = p.z - params2.x * params.y;
+ let texel = 1.0 / params2.y;
+ let r = params.z;
+ var lit = 0.0;
+ for (var j = 0; j < 4; j++) {
+ for (var i = 0; i < 4; i++) {
+ let d = vec2f(f32(i) - 1.5, f32(j) - 1.5) / 1.5 * r * texel;
+ lit += textureSampleCompareLevel(shadow_maps, shadow_sampler, uv + d, index, z);
+ }
+ }
+ lit /= 16.0;
+ return 1.0 - params.w * (1.0 - lit);
+}
+
+// The geometry pass.
+
+// `uv` with the repeat and the offset of map `index` (see `Draw.uv_transforms`).
+fn map_uv(uv: vec2f, index: i32) -> vec2f {
+ let t = draw.uv_transforms[index];
+ return uv * t.xy + t.zw;
+}
+
+struct VertexIn {
+ @location(0) position: vec3f,
+ @location(1) normal: vec3f,
+ @location(2) uv: vec2f,
+ @location(3) color: vec4f,
+}
+
+// One copy of the mesh: the identity for a mesh without copies.
+struct InstanceIn {
+ @location(4) model_0: vec4f,
+ @location(5) model_1: vec4f,
+ @location(6) model_2: vec4f,
+ @location(7) model_3: vec4f,
+ @location(8) normal_0: vec4f,
+ @location(9) normal_1: vec4f,
+ @location(10) normal_2: vec4f,
+ @location(11) color: vec4f,
+}
+
+struct VertexOut {
+ @builtin(position) clip: vec4f,
+ // The position relative to the camera. Its steps between pixels keep their precision
+ // in close views and far from the origin.
+ @location(0) @interpolate(perspective, centroid) rel: vec3f,
+ @location(1) @interpolate(perspective, centroid) normal: vec3f,
+ @location(2) @interpolate(perspective, centroid) uv: vec2f,
+ @location(3) @interpolate(perspective, centroid) color: vec4f,
+ @location(4) @interpolate(perspective, centroid) view_w: f32,
+}
+
+struct FragmentOut {
+ @location(0) color: vec4f,
+ // 1 / view distance, for the depth of field
+ @location(1) key: vec4f,
+}
+
+@vertex
+fn vs_main(in: VertexIn, copy: InstanceIn) -> VertexOut {
+ var out: VertexOut;
+ let model = mat4x4f(copy.model_0, copy.model_1, copy.model_2, copy.model_3);
+ let normal = mat3x3f(copy.normal_0.xyz, copy.normal_1.xyz, copy.normal_2.xyz);
+ let local = model * vec4f(in.position, 1.0);
+ // The translation of the mesh minus the camera position is exact. A small part far
+ // from the origin keeps its shape.
+ let m = draw.model;
+ let rel = mat3x3f(m[0].xyz, m[1].xyz, m[2].xyz) * local.xyz + (m[3].xyz - frame.camera.xyz) * local.w;
+ out.clip = frame.view_proj_rel * vec4f(rel, 1.0);
+ out.rel = rel;
+ out.normal = (draw.normal_matrix * vec4f(normal * in.normal, 0.0)).xyz;
+ out.uv = in.uv;
+ out.color = in.color * copy.color;
+ out.view_w = out.clip.w;
+ return out;
+}
+
+@fragment
+fn fs_main(in: VertexOut) -> FragmentOut {
+ let world = in.rel + frame.camera.xyz;
+ if (REFLECTION_PASS && dot(frame.clip_plane.xyz, world) + frame.clip_plane.w < 0.0) {
+ discard;
+ }
+ // Derivatives and texture samples come first. They need uniform control flow.
+ // In a close view the steps between pixels are micrometers, and the products of two
+ // steps fall below the threshold of `normalize_or`. Only their directions matter, so
+ // they are scaled to about 1.
+ let step_x = dpdx(in.rel);
+ let step_y = dpdy(in.rel);
+ let step = 1.0 / max(largest(max(abs(step_x), abs(step_y))), 1e-30);
+ let dx = step_x * step;
+ let dy = step_y * step;
+ // How much the smooth normal turns across the pixel, for the specular antialiasing.
+ let n_smooth = normalize_or(in.normal, vec3f(0.0, 1.0, 0.0));
+ let dnx = dpdx(n_smooth);
+ let dny = dpdy(n_smooth);
+ let normal_variation = dot(dnx, dnx) + dot(dny, dny);
+ var texel = vec4f(1.0);
+ var emissive_texel = vec4f(1.0);
+ var mr_texel = vec4f(1.0);
+ var ao_texel = vec4f(1.0);
+ if (TEXTURED) {
+ texel = textureSample(map_tex, tex_sampler, map_uv(in.uv, 0));
+ emissive_texel = textureSample(emissive_tex, tex_sampler, map_uv(in.uv, 1));
+ mr_texel = textureSample(mr_tex, tex_sampler, map_uv(in.uv, 2));
+ ao_texel = textureSample(ao_tex, tex_sampler, map_uv(in.uv, 4));
+ }
+ // The normal map, and the directions of +U and +V on the triangle (`uv_directions` in
+ // `shade.rs`).
+ var normal_texel = vec4f(0.5, 0.5, 1.0, 1.0);
+ var dpdu = vec3f(0.0);
+ var dpdv = vec3f(0.0);
+ if (NORMAL_MAP) {
+ let uv = map_uv(in.uv, 3);
+ normal_texel = textureSample(normal_tex, tex_sampler, uv);
+ let uv_x = dpdx(uv);
+ let uv_y = dpdy(uv);
+ let uv_step = 1.0 / max(largest(vec3f(max(abs(uv_x), abs(uv_y)), 0.0)), 1e-30);
+ let duvx = uv_x * uv_step;
+ let duvy = uv_y * uv_step;
+ let side = sign(duvx.x * duvy.y - duvy.x * duvx.y);
+ dpdu = (dx * duvy.y - dy * duvx.y) * side;
+ dpdv = (dy * duvx.x - dx * duvy.x) * side;
+ }
+
+ // The material comes next, so that the texels are not live during the lighting.
+ var base = draw.color.rgb;
+ var alpha = draw.color.a;
+ if (draw.attrs.y > 0.5) {
+ base *= in.color.rgb;
+ alpha *= in.color.a;
+ }
+ if (draw.attrs.x > 0.5 && draw.maps.x > 0.5) {
+ base *= texel.rgb;
+ alpha *= texel.a;
+ }
+ var emissive = draw.emissive.rgb;
+ if (draw.attrs.x > 0.5 && draw.maps.y > 0.5) {
+ emissive *= emissive_texel.rgb;
+ }
+ var metal_rough = vec2f(1.0);
+ if (draw.attrs.x > 0.5 && draw.maps.z > 0.5) {
+ metal_rough = mr_texel.bg;
+ }
+ var occlusion = 1.0;
+ if (draw.attrs.x > 0.5 && draw.detail.z > 0.5) {
+ occlusion = ao_texel.r;
+ }
+
+ var v: vec3f;
+ let to_camera = -in.rel;
+ let distance = length(to_camera);
+ if (frame.camera.w > 0.5) {
+ v = -frame.forward.xyz;
+ } else {
+ v = to_camera / max(distance, 1e-6);
+ }
+ var face = normalize_or(cross(dx, dy), n_smooth);
+ if (dot(face, v) < 0.0) {
+ face = -face;
+ }
+ // The shadow maps come next. Each map needs sixteen samples and many registers. Few
+ // other values are live at this point.
+ var shadows = vec2f(1.0);
+ if (SHADING == 0u && draw.maps.w > 0.5) {
+ shadows = shadow_factors(world, face);
+ }
+ var n = n_smooth;
+ if (draw.flags.x > 0.5) {
+ n = face;
+ }
+ if (NORMAL_MAP && draw.attrs.x > 0.5) {
+ n = bend(n, dpdu, dpdv, normal_texel, draw.detail.y);
+ }
+ // A back face, or a smooth normal that points away from the camera near a silhouette,
+ // turns around.
+ if (dot(n, face) < 0.0) {
+ n = -n;
+ }
+
+ let n_dot_v = max(dot(n, v), 1e-4);
+
+ var out: FragmentOut;
+ out.key = vec4f(1.0 / max(in.view_w, 1e-4), 0.0, 0.0, 1.0);
+ var rgb = vec3f(0.0);
+ if (SHADING == 1u) {
+ rgb = base + emissive;
+ } else if (SHADING == 3u) {
+ rgb = n * 0.5 + 0.5;
+ } else if (SHADING == 2u) {
+ var shadow = 1.0;
+ for (var i = 0; i < light_count(); i++) {
+ let light = &frame.lights[i];
+ let index = light.params.z;
+ if (i32(light.color.w) == 0 && index >= 0.0) {
+ shadow *= shadow_visibility(i32(index), world, face, dot(face, -light.direction.xyz));
+ }
+ }
+ out.color = vec4f(0.0, 0.0, 0.0, (1.0 - shadow) * draw.color.a);
+ return out;
+ } else {
+ rgb = standard(in.rel, in.clip.xy, base, n, face, v, n_dot_v, metal_rough, occlusion, shadows, normal_variation) + emissive;
+ }
+
+ if (FOG && draw.flags.z > 0.5 && frame.fog.w > 0.5) {
+ var f = 0.0;
+ if (frame.fog.w < 1.5) {
+ f = clamp((distance - frame.fog_params.x) / (frame.fog_params.y - frame.fog_params.x), 0.0, 1.0);
+ } else {
+ f = 1.0 - exp(-pow(frame.fog_params.z * distance, 2.0));
+ }
+ if (draw.flags.y > 0.5) {
+ rgb *= 1.0 - f;
+ } else {
+ rgb = mix(rgb, frame.fog.rgb, f);
+ }
+ }
+ // The HDR target is a 16 bit float. A sharp sun glint can overflow to infinity.
+ rgb = clamp(rgb, vec3f(0.0), vec3f(30000.0));
+ // An opaque surface covers its pixels whatever the alpha of its texture.
+ if (draw.flags.w < 0.5) {
+ alpha = 1.0;
+ }
+ if (draw.flags.y > 0.5) {
+ out.color = vec4f(rgb * alpha, 0.0);
+ } else {
+ out.color = vec4f(rgb * alpha, alpha);
+ }
+ return out;
+}
+
+// The normal `n` bent by the normal map `texel` (`bend` in `shade.rs`).
+fn bend(n: vec3f, dpdu: vec3f, dpdv: vec3f, texel: vec4f, scale: f32) -> vec3f {
+ let m = texel.rgb * 2.0 - 1.0;
+ let t = normalize_or(dpdu - n * dot(n, dpdu), vec3f(0.0));
+ let b = normalize_or(dpdv - n * dot(n, dpdv), vec3f(0.0));
+ return normalize_or(t * (m.x * scale) - b * (m.y * scale) + n * m.z, n);
+}
+
+// The visibility of a point in each of the two shadow maps, see `shadow_visibility`.
+fn shadow_factors(position: vec3f, face: vec3f) -> vec2f {
+ var shadows = vec2f(1.0);
+ for (var i = 0; i < light_count(); i++) {
+ let light = &frame.lights[i];
+ let index = i32(light.params.z);
+ if (i32(light.color.w) != 0 || index < 0 || index > 1) {
+ continue;
+ }
+ let fl = dot(face, -light.direction.xyz);
+ if (fl > 0.0) {
+ shadows[index] = shadow_visibility(index, position, face, fl);
+ }
+ }
+ return shadows;
+}
+
+// The light of a standard (PBR) surface at `rel`, the position relative to the camera.
+// `metal_rough` scales the metalness and the roughness. `shadows` comes from
+// `shadow_factors`. `normal_variation` tells how much the normal turns across the pixel.
+fn standard(rel: vec3f, screen: vec2f, base: vec3f, n: vec3f, face: vec3f, v: vec3f, n_dot_v: f32, metal_rough: vec2f, occlusion: f32, shadows: vec2f, normal_variation: f32) -> vec3f {
+ var metalness = draw.pbr.x * metal_rough.x;
+ var roughness = draw.pbr.y * metal_rough.y;
+ roughness = clamp(roughness, 0.045, 1.0);
+ metalness = clamp(metalness, 0.0, 1.0);
+ var alpha = roughness * roughness;
+ let clearcoat = clamp(draw.pbr.z, 0.0, 1.0);
+ var cc_roughness = draw.pbr.w;
+ var cc_alpha = pow(clamp(cc_roughness, 0.045, 1.0), 2.0);
+ // Specular antialiasing (Kaplanyan 2016, with the constants of Filament). A normal that
+ // turns within the pixel makes the highlight wider, so that it does not sparkle.
+ let kernel = min(0.3 * normal_variation, 0.04);
+ if (kernel > 0.0) {
+ alpha = sqrt(min(alpha * alpha + kernel, 1.0));
+ roughness = sqrt(alpha);
+ cc_alpha = sqrt(min(cc_alpha * cc_alpha + kernel, 1.0));
+ cc_roughness = sqrt(cc_alpha);
+ }
+ let f0 = mix(vec3f(0.04), base, metalness);
+ let diffuse = base * (1.0 - metalness);
+
+ // The light from the environment comes first. `face` is not used after it, so the light
+ // loop uses few enough registers for the full SIMD width.
+ var irradiance = frame.ambient.rgb / PI;
+ if (frame.ambient.w > 0.5) {
+ irradiance += mix(frame.hemi_ground.rgb, frame.hemi_sky.rgb, n.y * 0.5 + 0.5) / PI;
+ }
+ let has_env = env_kind() != 0;
+ let env_intensity = draw.emissive.w;
+ if (has_env) {
+ irradiance += env_irradiance(n) * env_intensity;
+ }
+ var indirect = diffuse * irradiance;
+ let brdf = env_brdf(roughness, n_dot_v);
+ if (has_env) {
+ var r = reflect(-v, n);
+ r = normalize_or(mix(r, n, alpha), n);
+ let horizon = pow(clamp(1.0 + dot(r, face), 0.0, 1.0), 2.0);
+ let env = env_radiance(r, roughness) * env_intensity;
+ var radiance = env * horizon;
+ if (REFLECTION) {
+ // The reflection of the scene replaces the environment where it covers the pixel.
+ let p = planar_reflection(screen, roughness);
+ radiance = mix(radiance, (p.rgb + env * (1.0 - p.a)) * horizon, draw.attrs.z);
+ }
+ indirect += radiance * (f0 * brdf.x + vec3f(brdf.y));
+ if (CLEARCOAT && clearcoat > 0.0) {
+ let rc = reflect(-v, n);
+ let cb = env_brdf(cc_roughness, n_dot_v);
+ let fc = (0.04 * cb.x + cb.y) * clearcoat;
+ var coat = env_radiance(rc, cc_roughness) * env_intensity;
+ if (REFLECTION) {
+ let p = planar_reflection(screen, cc_roughness);
+ coat = mix(coat, p.rgb + coat * (1.0 - p.a), draw.attrs.z);
+ }
+ indirect = indirect * (1.0 - fc) + coat * (horizon * fc);
+ }
+ } else {
+ indirect += irradiance * (f0 * brdf.x + vec3f(brdf.y)) * 0.5;
+ }
+ indirect *= occlusion;
+
+ var direct = vec3f(0.0);
+ for (var i = 0; i < light_count(); i++) {
+ let light = &frame.lights[i];
+ let color = light.color;
+ let kind = i32(color.w);
+ var l = vec3f(0.0);
+ var radiance = color.rgb;
+ if (kind == 0) {
+ l = -light.direction.xyz;
+ let index = i32(light.params.z);
+ if (index >= 0 && index <= 1) {
+ radiance *= shadows[index];
+ }
+ } else {
+ let lp = light.position;
+ let ld = light.direction;
+ // Both positions relative to the camera: a light close to a small part far
+ // from the origin keeps its direction.
+ let d = (lp.xyz - frame.camera.xyz) - rel;
+ let dist = length(d);
+ l = d / max(dist, 1e-6);
+ radiance *= attenuation(dist, lp.w, ld.w);
+ if (kind == 2) {
+ let cone = light.params;
+ radiance *= smooth_step(cone.x, cone.y, dot(-l, ld.xyz));
+ }
+ }
+ let n_dot_l = dot(n, l);
+ if (n_dot_l <= 0.0 || max(radiance.r, max(radiance.g, radiance.b)) <= 0.0) {
+ continue;
+ }
+ let h = normalize_or(l + v, n);
+ let n_dot_h = max(dot(n, h), 0.0);
+ let v_dot_h = max(dot(v, h), 0.0);
+ let fresnel = f0 + (vec3f(1.0) - f0) * pow(1.0 - v_dot_h, 5.0);
+ let specular = fresnel * (ggx(n_dot_h, alpha) * smith_visibility(n_dot_l, n_dot_v, alpha));
+ var lit = (diffuse * (vec3f(1.0) - fresnel) / PI + specular) * radiance * n_dot_l;
+ if (CLEARCOAT && clearcoat > 0.0) {
+ let fc = (0.04 + 0.96 * pow(1.0 - v_dot_h, 5.0)) * clearcoat;
+ let coat = ggx(n_dot_h, cc_alpha) * smith_visibility(n_dot_l, n_dot_v, cc_alpha) * fc;
+ lit = lit * (1.0 - fc) + radiance * (coat * n_dot_l);
+ }
+ direct += lit;
+ }
+ return direct + indirect;
+}
+
+// The background.
+
+struct FullscreenOut {
+ @builtin(position) clip: vec4f,
+ @location(0) ndc: vec2f,
+}
+
+@vertex
+fn vs_fullscreen(@builtin(vertex_index) index: u32) -> FullscreenOut {
+ let uv = vec2f(f32((index << 1u) & 2u), f32(index & 2u));
+ var out: FullscreenOut;
+ out.ndc = uv * 2.0 - 1.0;
+ out.clip = vec4f(out.ndc, 0.0, 1.0);
+ return out;
+}
+
+@fragment
+fn fs_background(in: FullscreenOut) -> FragmentOut {
+ var out: FragmentOut;
+ out.key = vec4f(0.0);
+ let kind = i32(frame.background.x);
+ if (kind == 1) {
+ out.color = vec4f(frame.background_color.rgb, 1.0);
+ } else {
+ let near = frame.inv_view_proj * vec4f(in.ndc, 1.0, 1.0);
+ let far = frame.inv_view_proj * vec4f(in.ndc, 0.0, 1.0);
+ let dir = normalize_or(far.xyz / far.w - near.xyz / near.w, vec3f(0.0, 0.0, -1.0));
+ out.color = vec4f(env_radiance(dir, frame.background.y), 1.0);
+ }
+ return out;
+}
+
+// The particles.
+
+struct ParticleIn {
+ // xyz, size
+ @location(0) position: vec4f,
+ // rgb times opacity, opacity
+ @location(1) color: vec4f,
+}
+
+struct ParticleOut {
+ @builtin(position) clip: vec4f,
+ @location(0) @interpolate(flat) center: vec2f,
+ @location(1) @interpolate(flat) radius: f32,
+ // rgb times opacity, the coverage of a blended particle
+ @location(2) @interpolate(flat) color: vec4f,
+}
+
+// A particle is a round dot, drawn as a quad around its center.
+@vertex
+fn vs_particle(in: ParticleIn, @builtin(vertex_index) index: u32) -> ParticleOut {
+ var out: ParticleOut;
+ let c = frame.view_proj * vec4f(in.position.xyz, 1.0);
+ // A particle in front of the near plane moves out of the view. The depth is reversed:
+ // `z > w` is in front of the near plane, also for orthographic cameras.
+ if (c.w <= 0.0 || c.z > c.w) {
+ out.clip = vec4f(2.0, 2.0, 2.0, 1.0);
+ return out;
+ }
+ let ndc = c.xy / c.w;
+ let center = vec2f((ndc.x * 0.5 + 0.5) * frame.viewport.x, (0.5 - ndc.y * 0.5) * frame.viewport.y);
+ var radius = in.position.w * frame.viewport.z;
+ if (frame.camera.w < 0.5) {
+ radius /= c.w;
+ }
+ // A particle smaller than 0.6 pixels is drawn at 0.6 pixels with less energy.
+ let drawn = max(radius, 0.6);
+ let energy = (radius / drawn) * (radius / drawn);
+ out.color = in.color * energy;
+ out.center = center;
+ out.radius = drawn;
+ let corners = array<vec2f, 6>(vec2f(-1.0, -1.0), vec2f(1.0, -1.0), vec2f(1.0, 1.0), vec2f(-1.0, -1.0), vec2f(1.0, 1.0), vec2f(-1.0, 1.0));
+ let p = center + corners[index] * (drawn + 1.0);
+ out.clip = vec4f(p.x / frame.viewport.x * 2.0 - 1.0, 1.0 - p.y / frame.viewport.y * 2.0, c.z / c.w, 1.0);
+ return out;
+}
+
+fn particle_alpha(in: ParticleOut) -> f32 {
+ let d = distance(in.clip.xy, in.center);
+ let r = in.radius;
+ let falloff = 1.0 - clamp((d - r * 0.3) / (r * 0.7 + 0.5), 0.0, 1.0);
+ return falloff * falloff;
+}
+
+@fragment
+fn fs_particle_additive(in: ParticleOut) -> FragmentOut {
+ var out: FragmentOut;
+ out.key = vec4f(0.0);
+ out.color = vec4f(in.color.rgb * particle_alpha(in), 0.0);
+ return out;
+}
+
+@fragment
+fn fs_particle_normal(in: ParticleOut) -> FragmentOut {
+ var out: FragmentOut;
+ out.key = vec4f(0.0);
+ let a = particle_alpha(in);
+ out.color = vec4f(in.color.rgb * a, in.color.a * a);
+ return out;
+}
diff --git a/fframes-three-d/src/gpu/shadow.wgsl b/fframes-three-d/src/gpu/shadow.wgsl
new file mode 100644
index 00000000..71db4841
--- /dev/null
+++ b/fframes-three-d/src/gpu/shadow.wgsl
@@ -0,0 +1,45 @@
+// The depth pass into a shadow map.
+
+struct ShadowPass {
+ view_proj: mat4x4f,
+}
+
+// The start of `Draw` in `scene.wgsl`.
+struct Draw {
+ model: mat4x4f,
+}
+
+@group(0) @binding(0) var<uniform> shadow_pass: ShadowPass;
+@group(1) @binding(0) var<uniform> draw: Draw;
+
+// The model matrix of one copy of the mesh: the identity for a mesh without copies.
+struct InstanceIn {
+ @location(1) model_0: vec4f,
+ @location(2) model_1: vec4f,
+ @location(3) model_2: vec4f,
+ @location(4) model_3: vec4f,
+}
+
+struct ShadowOut {
+ @builtin(position) clip: vec4f,
+ @location(0) depth: f32,
+}
+
+// The light camera is orthographic: `w` is 1 and the depth is linear across a triangle.
+// The rasterizer would clip a caster beyond the near plane, but a caster between the light
+// and the map still throws its shadow. The vertex sits in the middle of the depth range,
+// and the fragment writes the depth clamped to the near plane, as the CPU rasterizer does.
+@vertex
+fn vs_shadow(@location(0) position: vec3f, copy: InstanceIn) -> ShadowOut {
+ let model = mat4x4f(copy.model_0, copy.model_1, copy.model_2, copy.model_3);
+ let clip = shadow_pass.view_proj * (draw.model * (model * vec4f(position, 1.0)));
+ var out: ShadowOut;
+ out.clip = vec4f(clip.xy, 0.5 * clip.w, clip.w);
+ out.depth = clip.z / clip.w;
+ return out;
+}
+
+@fragment
+fn fs_shadow(in: ShadowOut) -> @builtin(frag_depth) f32 {
+ return clamp(in.depth, 0.0, 1.0);
+}
diff --git a/fframes-three-d/src/lib.rs b/fframes-three-d/src/lib.rs
new file mode 100644
index 00000000..7ef0fe9d
--- /dev/null
+++ b/fframes-three-d/src/lib.rs
@@ -0,0 +1,120 @@
+//! 3D scenes for fframes, with an API after three.js. fframes re-exports this crate as
+//! `fframes::three_d` with its `3d` feature: `fframes = { features = ["3d", "wgpu"] }`.
+//!
+//! A [`Scene`] holds [`Node`]s in a hierarchy: meshes, lights, particles and groups. A
+//! [`Camera`] looks at the scene. A [`Renderer`] makes an image of both for an `<image>`
+//! element in the `svgr!` tree of a frame. Regular SVG can go below and above it.
+//!
+//! The renderer has 4x multisampling and physically based materials: metal and roughness,
+//! clearcoat and specular antialiasing. A procedural studio or an HDR panorama lights the
+//! scene. The renderer draws soft shadows, planar reflections ([`Reflector`]), transparency,
+//! additive glows and particles. It also has fog, depth of field, motion blur, bloom and
+//! ACES tone mapping.
+//!
+//! The default renderer is a multithreaded software rasterizer. It runs on all backends:
+//! CPU, Skia and the wasm editor. The `wgpu` feature of fframes (the `gpu` feature of this
+//! crate) renders with wgpu on Vulkan, Metal or DX12, see [`Renderer::gpu`]. The two paths
+//! use the same shading. On average, a GPU frame differs from the CPU frame by less than
+//! one 8-bit step. Without a usable GPU, the CPU renders.
+//!
+//! A backend can share its GPU, see `fframes::shared_gpu`. The Skia Vulkan backend does
+//! this with its `wgpu` feature. [`Renderer::render`] then renders on that device into a
+//! texture that Skia draws. The 3D image stays on the GPU until the encoder.
+//!
+//! Units are meters and radians. Colors as hex numbers or `&str` are sRGB.
+//!
+//! # Example
+//!
+//! ```rust,ignore
+//! use fframes::three_d::*;
+//! use fframes::{FFramesContext, Frame, Svgr, Video, svgr};
+//!
+//! struct Spin {
+//! scene: Scene,
+//! cube: NodeId,
+//! renderer: Renderer,
+//! }
+//!
+//! impl Spin {
+//! fn new() -> Self {
+//! let mut scene = Scene::new().environment(Environment::studio());
+//! let cube = scene.add(Node::mesh(
+//! Geometry::rounded_box(1.0, 1.0, 1.0, 0.08, 4),
+//! Material::metal(0xd4d8e0, 0.25),
+//! ).at(0.0, 0.5, 0.0));
+//! scene.add(Node::mesh(Geometry::floor(20.0, 20.0), Material::shadow_catcher(0.6)));
+//! scene.add(Node::light(Light::sun(Rgb::WHITE, 3.0, vec3(2.0, 5.0, 3.0))));
+//! Self { scene, cube, renderer: Renderer::new(1920, 1080).bloom(Bloom::default()) }
+//! }
+//! }
+//!
+//! // in render_frame
+//! let t = frame.seconds();
+//! let mut scene = self.scene.clone();
+//! scene[self.cube].rotation = euler(0.0, t, 0.0);
+//! let camera = Camera::perspective(35.0).orbit(vec3(0.0, 0.5, 0.0), 5.0, 30.0, 15.0);
+//! let image = self.renderer.render(&scene, &camera);
+//! svgr!(<svg ...><image href={image.href()} x="0" y="0" width="1920" height="1080" /></svg>)
+//! ```
+//!
+//! # Coming from three.js
+//!
+//! | three.js | `fframes_three_d` |
+//! | --- | --- |
+//! | `new Mesh(new BoxGeometry(1, 2, 3), new MeshStandardMaterial({ color: 0xff0000 }))` | `Node::mesh(Geometry::cuboid(1.0, 2.0, 3.0), Material::standard(0xff0000))` |
+//! | `mesh.position.set(x, y, z)`, `mesh.rotation.set(x, y, z)` | `.at(x, y, z)`, `.euler(x, y, z)` or `scene[id].position = ...` |
+//! | `new Group()`, `group.add(mesh)` | [`Node::group`], `scene.add_to(group, node)` |
+//! | `metalness`, `roughness`, `emissive`, `emissiveIntensity`, `clearcoat`, `map`, `normalMap`, `normalScale`, `aoMap` | the same names on [`Material`] |
+//! | `MeshBasicMaterial`, `ShadowMaterial` | [`Material::unlit`], [`Material::shadow_catcher`] |
+//! | `AmbientLight`, `HemisphereLight`, `DirectionalLight`, `PointLight`, `SpotLight` | [`Light`] |
+//! | `light.castShadow = true` | [`Light::sun`] or [`Light::with_shadow`] |
+//! | `scene.environment = pmrem(RoomEnvironment)` | [`Environment::studio`] |
+//! | `RGBELoader` panorama | [`Environment::map`] with [`EnvironmentMap::decode`] |
+//! | `scene.fog = new Fog(color, near, far)` | [`Scene::fog`] with [`Fog::Linear`] |
+//! | `Reflector` | [`Scene::reflector`] with [`Material::reflection`] |
+//! | `camera.position.set(..); camera.lookAt(..)` | `Camera::perspective(fov).at(..).look_at(..)` |
+//! | `vector.project(camera)` | [`Camera::project`] |
+//! | `GLTFLoader` + `AnimationMixer` | [`Model::from_gltf`] + [`ModelInstance::play`] |
+//! | `STLLoader`, `toCreasedNormals` | [`Geometry::from_stl`], [`Geometry::smooth`] |
+//! | `VideoTexture` | [`Texture::from_image`] of a decoded video frame, for each frame |
+//! | `UnrealBloomPass`, `ACESFilmicToneMapping` | [`Bloom`], [`ToneMapping`] |
+//! | `Points` | [`Node::particles`] |
+//! | `InstancedMesh`, `instanceColor` | [`Node::instanced`] with [`Instances`] |
+
+// Colors are hex numbers as in three.js: `0xff8800`.
+#![allow(clippy::unreadable_literal)]
+// Rasterization and mesh generation index several parallel arrays in one loop.
+#![allow(clippy::needless_range_loop, clippy::items_after_statements)]
+
+mod animation;
+mod camera;
+mod color;
+mod environment;
+mod geometry;
+mod gltf;
+#[cfg(all(feature = "gpu", not(target_arch = "wasm32")))]
+mod gpu;
+mod light;
+mod material;
+pub mod math;
+mod render;
+mod scene;
+mod texture;
+
+pub use animation::{AnimationClip, Channel, Interpolation, Keyframes};
+pub use camera::{Camera, Focus};
+pub use color::Rgb;
+pub use environment::{Environment, EnvironmentMap, SoftBox, Studio};
+pub use geometry::{
+ Geometry, Glyph, GlyphShapes, MorphTarget, Shape, SkinWeights, StlError, TextError,
+};
+pub use gltf::{Model, ModelError, ModelInstance};
+pub use light::{DirectionalLight, Light, PointLight, Shadow, SpotLight};
+pub use material::{Blending, Material, Shading, Side};
+pub use math::{Aabb, Mat3, Mat4, Quat, Vec2, Vec3, Vec4, deg, euler, euler_deg, vec2, vec3, vec4};
+pub use render::{Bloom, Pixels, Renderer, ToneMapping};
+pub use scene::{
+ Background, Fog, Instances, Mesh, Node, NodeId, Object, Particle, Particles, Reflector, Scene,
+ Skin,
+};
+pub use texture::Texture;
diff --git a/fframes-three-d/src/light.rs b/fframes-three-d/src/light.rs
new file mode 100644
index 00000000..740bf02e
--- /dev/null
+++ b/fframes-three-d/src/light.rs
@@ -0,0 +1,191 @@
+use glam::Vec3;
+
+use crate::Rgb;
+use crate::math::Aabb;
+
+/// A light source. Add it to a scene with [`Node::light`](crate::Node::light).
+///
+/// Point and spot lights shine from the world position of their node. The rotation of the
+/// node turns the direction of directional and spot lights.
+///
+/// Intensities follow the physically based mode of three.js. A directional light of
+/// intensity π lights a white surface that faces it to full white. The light of point and
+/// spot lights falls off with the inverse square of the distance (candela).
+#[derive(Debug, Clone, PartialEq)]
+pub enum Light {
+ /// Light from all directions, three.js `AmbientLight`.
+ Ambient {
+ color: Rgb,
+ intensity: f32,
+ },
+ /// The sky color from above and the ground color from below, three.js `HemisphereLight`.
+ Hemisphere {
+ sky: Rgb,
+ ground: Rgb,
+ intensity: f32,
+ },
+ Directional(DirectionalLight),
+ Point(PointLight),
+ Spot(SpotLight),
+}
+
+/// Parallel rays as from the sun, three.js `DirectionalLight`. It is the only light that
+/// casts shadows.
+#[derive(Debug, Clone, PartialEq)]
+pub struct DirectionalLight {
+ pub color: Rgb,
+ pub intensity: f32,
+ /// The unit direction that the light travels, in the space of the node.
+ pub direction: Vec3,
+ /// The shadow settings. `None` casts no shadows.
+ pub shadow: Option<Shadow>,
+}
+
+/// The shadow map settings of a [`DirectionalLight`], three.js `light.shadow`.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Shadow {
+ /// The size of the square shadow map in texels. Default 2048.
+ pub map_size: u32,
+ /// The radius of the soft shadow filter in shadow map texels. Default 1.5.
+ pub softness: f32,
+ /// The darkness of the shadow, `0..1`. Default 1.
+ pub strength: f32,
+ /// The depth bias in shadow map texels. It prevents shadow acne on lit surfaces.
+ /// Default 1.5.
+ pub bias: f32,
+ /// The world box that receives shadows. `None`, the default, fits the box of all
+ /// shadow casters. Set it when the casters are far apart.
+ pub bounds: Option<Aabb>,
+}
+
+impl Default for Shadow {
+ fn default() -> Self {
+ Self {
+ map_size: 2048,
+ softness: 1.5,
+ strength: 1.0,
+ bias: 1.5,
+ bounds: None,
+ }
+ }
+}
+
+/// A light bulb, three.js `PointLight`.
+#[derive(Debug, Clone, PartialEq)]
+pub struct PointLight {
+ pub color: Rgb,
+ pub intensity: f32,
+ /// The range in meters. The light fades out smoothly towards it. 0 gives no limit.
+ pub distance: f32,
+ /// The exponent of the falloff. 2 is physically correct.
+ pub decay: f32,
+}
+
+/// A cone of light, three.js `SpotLight`.
+#[derive(Debug, Clone, PartialEq)]
+pub struct SpotLight {
+ pub color: Rgb,
+ pub intensity: f32,
+ /// The range in meters. The light fades out smoothly towards it. 0 gives no limit.
+ pub distance: f32,
+ /// The exponent of the falloff. 2 is physically correct.
+ pub decay: f32,
+ /// Half the angle of the cone in radians.
+ pub angle: f32,
+ /// The part of the cone that fades out, `0..1`.
+ pub penumbra: f32,
+ /// The unit direction of the cone axis, in the space of the node.
+ pub direction: Vec3,
+}
+
+impl Light {
+ /// Light from all directions, three.js `AmbientLight`.
+ pub fn ambient(color: impl Into<Rgb>, intensity: f32) -> Self {
+ Light::Ambient {
+ color: color.into(),
+ intensity,
+ }
+ }
+
+ /// Sky light from above and ground light from below, three.js `HemisphereLight`.
+ pub fn hemisphere(sky: impl Into<Rgb>, ground: impl Into<Rgb>, intensity: f32) -> Self {
+ Light::Hemisphere {
+ sky: sky.into(),
+ ground: ground.into(),
+ intensity,
+ }
+ }
+
+ /// A directional light that shines from `from` towards the origin, without shadows.
+ ///
+ /// It is a three.js `DirectionalLight` at the position `from` with the default target.
+ /// For shadows, use [`Light::sun`] or [`Light::with_shadow`].
+ pub fn directional(color: impl Into<Rgb>, intensity: f32, from: Vec3) -> Self {
+ Light::Directional(DirectionalLight {
+ color: color.into(),
+ intensity,
+ direction: (-from).normalize_or(Vec3::NEG_Y),
+ shadow: None,
+ })
+ }
+
+ /// A directional light that casts soft shadows, see [`Light::directional`].
+ pub fn sun(color: impl Into<Rgb>, intensity: f32, from: Vec3) -> Self {
+ Self::directional(color, intensity, from).with_shadow(Shadow::default())
+ }
+
+ /// A point light with decay 2. `distance` is the range in meters, 0 for no limit.
+ pub fn point(color: impl Into<Rgb>, intensity: f32, distance: f32) -> Self {
+ Light::Point(PointLight {
+ color: color.into(),
+ intensity,
+ distance,
+ decay: 2.0,
+ })
+ }
+
+ /// A spot light that points down -Y, with no range limit and decay 2.
+ ///
+ /// `angle` is half the cone angle in radians. `penumbra` is the part of the cone that
+ /// fades out, `0..1`. Aim the light with [`Light::pointing`] or turn its node.
+ pub fn spot(color: impl Into<Rgb>, intensity: f32, angle: f32, penumbra: f32) -> Self {
+ Light::Spot(SpotLight {
+ color: color.into(),
+ intensity,
+ distance: 0.0,
+ decay: 2.0,
+ angle,
+ penumbra,
+ direction: Vec3::NEG_Y,
+ })
+ }
+
+ /// Sets the shadow of a directional light. Other lights ignore it.
+ pub fn with_shadow(mut self, shadow: Shadow) -> Self {
+ if let Light::Directional(light) = &mut self {
+ light.shadow = Some(shadow);
+ }
+ self
+ }
+
+ /// Sets the direction of a directional or spot light. Other lights ignore it.
+ pub fn pointing(mut self, direction: Vec3) -> Self {
+ if let Light::Directional(DirectionalLight { direction: d, .. })
+ | Light::Spot(SpotLight { direction: d, .. }) = &mut self
+ {
+ *d = direction.normalize_or(Vec3::NEG_Y);
+ }
+ self
+ }
+
+ /// The intensity, mutable. Use it for flicker and fades.
+ pub fn intensity_mut(&mut self) -> &mut f32 {
+ match self {
+ Light::Ambient { intensity, .. }
+ | Light::Hemisphere { intensity, .. }
+ | Light::Directional(DirectionalLight { intensity, .. })
+ | Light::Point(PointLight { intensity, .. })
+ | Light::Spot(SpotLight { intensity, .. }) => intensity,
+ }
+ }
+}
diff --git a/fframes-three-d/src/material.rs b/fframes-three-d/src/material.rs
new file mode 100644
index 00000000..c5c9209c
--- /dev/null
+++ b/fframes-three-d/src/material.rs
@@ -0,0 +1,318 @@
+use std::sync::Arc;
+
+use crate::{Rgb, Texture};
+
+/// The side of a triangle that the renderer draws.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum Side {
+ /// The side where the vertices go counterclockwise. The default.
+ #[default]
+ Front,
+ /// The other side.
+ Back,
+ /// Both sides.
+ Double,
+}
+
+/// How a transparent surface or a particle combines with the color behind it.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum Blending {
+ /// Alpha blending. The default.
+ #[default]
+ Normal,
+ /// Adds light, for glows, energy, sparks and holograms. It never makes a color darker.
+ Additive,
+}
+
+/// The lighting model of a [`Material`].
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum Shading {
+ /// Physically based metal and roughness, three.js `MeshStandardMaterial`. With
+ /// clearcoat it is `MeshPhysicalMaterial`. The default.
+ #[default]
+ Standard,
+ /// No lighting, three.js `MeshBasicMaterial`. The surface shows its color and its
+ /// emissive light.
+ Unlit,
+ /// Invisible except for the shadows that fall on it, three.js `ShadowMaterial`. Put it
+ /// on a floor to ground objects over an SVG background.
+ ShadowCatcher,
+ /// World space normals as colors, for debugging.
+ Normals,
+}
+
+/// The look of a surface, after three.js `MeshStandardMaterial`.
+///
+/// A material is a plain value, and each mesh owns its copy. To animate a property, set it
+/// on the scene of the frame: `scene[id].material_mut().unwrap().emissive_intensity = glow`.
+///
+/// ```rust
+/// use fframes::three_d::{Material, Rgb};
+///
+/// let steel = Material::metal(0xb8c0cc, 0.3);
+/// let paint = Material::standard(0xff5500).roughness(0.45).clearcoat(1.0);
+/// let visor = Material::standard(0x111111).emissive(0x33ddff, 6.0);
+/// let ghost = Material::standard(0x88ccff).opacity(0.3).additive();
+/// ```
+#[derive(Debug, Clone)]
+pub struct Material {
+ /// Default [`Shading::Standard`].
+ pub shading: Shading,
+ /// The base color. Default white.
+ pub color: Rgb,
+ /// `0..1`, default 1. Below 1, or with [`Material::transparent`], the renderer blends
+ /// the surface after the opaque geometry, sorted back to front. Otherwise the surface
+ /// is opaque and the alpha of `map` and of vertex colors has no effect.
+ pub opacity: f32,
+ /// `0..1`, default 0.
+ pub metalness: f32,
+ /// `0..1`, default 1. [`Material::standard`] sets 0.5.
+ pub roughness: f32,
+ /// The color of the emitted light. Default black.
+ pub emissive: Rgb,
+ /// The multiplier for `emissive`. Default 1.
+ pub emissive_intensity: f32,
+ /// A second glossy layer on top, as on car paint, `0..1`. Default 0.
+ pub clearcoat: f32,
+ /// The roughness of the clearcoat. Default 0.05.
+ pub clearcoat_roughness: f32,
+ /// How much of the [`Reflector`](crate::Reflector) of the scene the surface shows instead
+ /// of the environment reflection, `0..1`. Default 0. Roughness blurs it. Only surfaces on
+ /// the plane of the reflector can use it.
+ pub reflection: f32,
+ /// The multiplier for the reflections and the ambient light of the environment.
+ /// Default 1.
+ pub env_intensity: f32,
+ /// Shading with the face normal of each triangle, for a faceted look. Default `false`.
+ pub flat_shading: bool,
+ /// Default [`Side::Front`].
+ pub side: Side,
+ /// Default [`Blending::Normal`].
+ pub blending: Blending,
+ /// Blending also at opacity 1. Default `false`.
+ pub transparent: bool,
+ /// Blended surfaces write depth only when this is set. Default `false`.
+ pub depth_write: bool,
+ /// The base color texture, three.js `map`. It multiplies `color`.
+ pub map: Option<Arc<Texture>>,
+ /// The emissive texture, three.js `emissiveMap`. It multiplies `emissive`.
+ pub emissive_map: Option<Arc<Texture>>,
+ /// The glTF metallic-roughness texture: roughness in green, metalness in blue.
+ pub metal_rough_map: Option<Arc<Texture>>,
+ /// The tangent space normal map, three.js `normalMap`. Green points up in the image (the
+ /// OpenGL convention of three.js and glTF). Load it with [`Texture::decode_linear`].
+ pub normal_map: Option<Arc<Texture>>,
+ /// How much the normal map bends the normals, three.js `normalScale`. Default 1.
+ pub normal_scale: f32,
+ /// The ambient occlusion map, three.js `aoMap`. Its red channel darkens the light from
+ /// the environment and the ambient lights. Load it with [`Texture::decode_linear`].
+ pub ao_map: Option<Arc<Texture>>,
+ /// Whether the scene fog applies. Default `true`.
+ pub fog: bool,
+}
+
+impl Default for Material {
+ fn default() -> Self {
+ Self {
+ shading: Shading::Standard,
+ color: Rgb::WHITE,
+ opacity: 1.0,
+ metalness: 0.0,
+ roughness: 1.0,
+ emissive: Rgb::BLACK,
+ emissive_intensity: 1.0,
+ clearcoat: 0.0,
+ clearcoat_roughness: 0.05,
+ reflection: 0.0,
+ env_intensity: 1.0,
+ flat_shading: false,
+ side: Side::Front,
+ blending: Blending::Normal,
+ transparent: false,
+ depth_write: false,
+ map: None,
+ emissive_map: None,
+ metal_rough_map: None,
+ normal_map: None,
+ normal_scale: 1.0,
+ ao_map: None,
+ fog: true,
+ }
+ }
+}
+
+impl Material {
+ /// A dielectric such as plastic, paint or rubber, with roughness 0.5.
+ pub fn standard(color: impl Into<Rgb>) -> Self {
+ Self {
+ color: color.into(),
+ roughness: 0.5,
+ ..Default::default()
+ }
+ }
+
+ /// A metal. Its reflections take its color. `roughness` is `0..1`.
+ pub fn metal(color: impl Into<Rgb>, roughness: f32) -> Self {
+ Self {
+ color: color.into(),
+ metalness: 1.0,
+ roughness,
+ ..Default::default()
+ }
+ }
+
+ /// A surface without lighting, three.js `MeshBasicMaterial`.
+ pub fn unlit(color: impl Into<Rgb>) -> Self {
+ Self {
+ shading: Shading::Unlit,
+ color: color.into(),
+ ..Default::default()
+ }
+ }
+
+ /// Pure light: unlit, additive and without fog. It emits `color * intensity`, and bright
+ /// values bloom.
+ pub fn glow(color: impl Into<Rgb>, intensity: f32) -> Self {
+ Self::unlit(color.into() * intensity).additive().no_fog()
+ }
+
+ /// A surface that shows only the shadows on it, three.js `ShadowMaterial`. `opacity` is
+ /// the darkness of the shadows.
+ pub fn shadow_catcher(opacity: f32) -> Self {
+ Self {
+ shading: Shading::ShadowCatcher,
+ opacity,
+ ..Default::default()
+ }
+ }
+
+ /// World space normals as colors, for debugging.
+ pub fn normals() -> Self {
+ Self {
+ shading: Shading::Normals,
+ ..Default::default()
+ }
+ }
+
+ /// Sets the base color.
+ pub fn color(mut self, color: impl Into<Rgb>) -> Self {
+ self.color = color.into();
+ self
+ }
+
+ /// Sets the metalness, `0..1`.
+ pub fn metalness(mut self, metalness: f32) -> Self {
+ self.metalness = metalness;
+ self
+ }
+
+ /// Sets the roughness, `0..1`.
+ pub fn roughness(mut self, roughness: f32) -> Self {
+ self.roughness = roughness;
+ self
+ }
+
+ /// Sets the emitted light to `color * intensity`. Lighting does not change it. Above
+ /// about 1 it blooms.
+ pub fn emissive(mut self, color: impl Into<Rgb>, intensity: f32) -> Self {
+ self.emissive = color.into();
+ self.emissive_intensity = intensity;
+ self
+ }
+
+ /// Sets the glossy top layer, `0..1`.
+ pub fn clearcoat(mut self, amount: f32) -> Self {
+ self.clearcoat = amount;
+ self
+ }
+
+ /// Sets the multiplier for the light of the environment.
+ pub fn env_intensity(mut self, intensity: f32) -> Self {
+ self.env_intensity = intensity;
+ self
+ }
+
+ /// Shows the scene mirrored in its [`Reflector`](crate::Reflector) instead of the
+ /// environment reflection. `amount` is `0..1`, and roughness blurs the mirror image.
+ pub fn reflection(mut self, amount: f32) -> Self {
+ self.reflection = amount.clamp(0.0, 1.0);
+ self
+ }
+
+ /// Sets the opacity, `0..1`.
+ pub fn opacity(mut self, opacity: f32) -> Self {
+ self.opacity = opacity;
+ self
+ }
+
+ /// Makes the surface add its light to the color behind it, see [`Blending::Additive`].
+ pub fn additive(mut self) -> Self {
+ self.blending = Blending::Additive;
+ self.transparent = true;
+ self
+ }
+
+ /// Blends the surface also at opacity 1.
+ pub fn transparent(mut self) -> Self {
+ self.transparent = true;
+ self
+ }
+
+ /// Draws both sides of each triangle.
+ pub fn double_sided(self) -> Self {
+ self.side(Side::Double)
+ }
+
+ /// Sets the side of the triangles that the renderer draws.
+ pub fn side(mut self, side: Side) -> Self {
+ self.side = side;
+ self
+ }
+
+ /// Shades with face normals, for a faceted look.
+ pub fn flat(mut self) -> Self {
+ self.flat_shading = true;
+ self
+ }
+
+ /// Sets the base color texture.
+ pub fn map(mut self, texture: impl Into<Arc<Texture>>) -> Self {
+ self.map = Some(texture.into());
+ self
+ }
+
+ /// Sets the emissive texture.
+ pub fn emissive_map(mut self, texture: impl Into<Arc<Texture>>) -> Self {
+ self.emissive_map = Some(texture.into());
+ self
+ }
+
+ /// Sets the normal map.
+ pub fn normal_map(mut self, texture: impl Into<Arc<Texture>>) -> Self {
+ self.normal_map = Some(texture.into());
+ self
+ }
+
+ /// Sets how much the normal map bends the normals.
+ pub fn normal_scale(mut self, scale: f32) -> Self {
+ self.normal_scale = scale;
+ self
+ }
+
+ /// Sets the ambient occlusion map.
+ pub fn ao_map(mut self, texture: impl Into<Arc<Texture>>) -> Self {
+ self.ao_map = Some(texture.into());
+ self
+ }
+
+ /// Turns off the scene fog for this surface.
+ pub fn no_fog(mut self) -> Self {
+ self.fog = false;
+ self
+ }
+
+ /// Whether the renderer draws the surface in the blended pass.
+ pub(crate) fn is_blended(&self) -> bool {
+ self.transparent || self.opacity < 1.0 || self.blending == Blending::Additive
+ }
+}
diff --git a/fframes-three-d/src/math.rs b/fframes-three-d/src/math.rs
new file mode 100644
index 00000000..0086abdc
--- /dev/null
+++ b/fframes-three-d/src/math.rs
@@ -0,0 +1,113 @@
+//! Math types from `glam` and a few helpers.
+//!
+//! The conventions are the same as in three.js. Coordinates are right-handed, Y is up, a
+//! camera looks along -Z, and angles are in radians.
+
+pub use glam::{EulerRot, Mat3, Mat4, Quat, Vec2, Vec3, Vec4, vec2, vec3, vec4};
+
+/// Converts degrees to radians.
+#[inline]
+pub fn deg(degrees: f32) -> f32 {
+ degrees.to_radians()
+}
+
+/// Makes a rotation from Euler angles in radians, applied in X, Y, Z order.
+/// This is the three.js default order `"XYZ"`.
+#[inline]
+pub fn euler(x: f32, y: f32, z: f32) -> Quat {
+ Quat::from_euler(EulerRot::XYZ, x, y, z)
+}
+
+/// Makes a rotation from Euler angles in degrees, applied in X, Y, Z order.
+#[inline]
+pub fn euler_deg(x: f32, y: f32, z: f32) -> Quat {
+ euler(deg(x), deg(y), deg(z))
+}
+
+/// Hermite interpolation from 0 to 1 while `x` goes from `edge0` to `edge1`.
+/// The result is 0 below `edge0` and 1 above `edge1`, like GLSL `smoothstep`.
+#[inline]
+pub fn smoothstep(edge0: f32, edge1: f32, x: f32) -> f32 {
+ let t = ((x - edge0) / (edge1 - edge0)).clamp(0.0, 1.0);
+ t * t * (3.0 - 2.0 * t)
+}
+
+/// An axis-aligned bounding box. The default value is [`Aabb::EMPTY`].
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct Aabb {
+ pub min: Vec3,
+ pub max: Vec3,
+}
+
+impl Default for Aabb {
+ fn default() -> Self {
+ Self::EMPTY
+ }
+}
+
+impl Aabb {
+ /// A box that contains no points. Extending it with a point gives a box around that point.
+ pub const EMPTY: Aabb = Aabb {
+ min: Vec3::splat(f32::INFINITY),
+ max: Vec3::splat(f32::NEG_INFINITY),
+ };
+
+ /// The smallest box that contains all `points`.
+ pub fn from_points(points: impl IntoIterator<Item = Vec3>) -> Self {
+ let mut aabb = Self::EMPTY;
+ for p in points {
+ aabb.extend(p);
+ }
+ aabb
+ }
+
+ /// Grows the box to contain `p`.
+ pub fn extend(&mut self, p: Vec3) {
+ self.min = self.min.min(p);
+ self.max = self.max.max(p);
+ }
+
+ /// The smallest box that contains both boxes.
+ pub fn union(self, other: Aabb) -> Aabb {
+ Aabb {
+ min: self.min.min(other.min),
+ max: self.max.max(other.max),
+ }
+ }
+
+ /// True when the box contains no points.
+ pub fn is_empty(&self) -> bool {
+ self.min.x > self.max.x
+ }
+
+ pub fn center(&self) -> Vec3 {
+ (self.min + self.max) * 0.5
+ }
+
+ pub fn size(&self) -> Vec3 {
+ self.max - self.min
+ }
+
+ /// The eight corners. Bit 0 of the index selects max X, bit 1 max Y, bit 2 max Z.
+ pub fn corners(&self) -> [Vec3; 8] {
+ let (a, b) = (self.min, self.max);
+ [
+ Vec3::new(a.x, a.y, a.z),
+ Vec3::new(b.x, a.y, a.z),
+ Vec3::new(a.x, b.y, a.z),
+ Vec3::new(b.x, b.y, a.z),
+ Vec3::new(a.x, a.y, b.z),
+ Vec3::new(b.x, a.y, b.z),
+ Vec3::new(a.x, b.y, b.z),
+ Vec3::new(b.x, b.y, b.z),
+ ]
+ }
+
+ /// The axis-aligned box around this box after the transform `m`.
+ pub fn transformed(&self, m: &Mat4) -> Aabb {
+ if self.is_empty() {
+ return *self;
+ }
+ Aabb::from_points(self.corners().map(|c| m.transform_point3(c)))
+ }
+}
diff --git a/fframes-three-d/src/render/mod.rs b/fframes-three-d/src/render/mod.rs
new file mode 100644
index 00000000..7ef95e9a
--- /dev/null
+++ b/fframes-three-d/src/render/mod.rs
@@ -0,0 +1,443 @@
+//! The CPU renderer: a multithreaded software rasterizer. It runs wherever fframes runs
+//! (the CPU backend, the Skia backend, the wasm editor) and gives the same pixels on all
+//! of them.
+
+mod post;
+pub(crate) mod prepare;
+mod raster;
+pub(crate) mod reflection;
+mod shade;
+pub(crate) mod shadow;
+
+use std::sync::atomic::{AtomicU64, Ordering};
+
+use glam::{Vec2, Vec4};
+use rayon::prelude::*;
+
+pub use post::{Bloom, ToneMapping};
+
+use crate::{Camera, Scene};
+use prepare::{Viewport, World};
+use raster::Blended;
+use reflection::ReflectionMap;
+use shade::ShadeContext;
+use shadow::ShadowMap;
+
+/// Renders [`Scene`]s into images for `svgr!`.
+///
+/// Make it once, for example in the constructor of the video. It holds only settings.
+/// Then call [`Renderer::render`] in `render_frame`. With the `wgpu` feature of fframes it
+/// renders on the GPU, see [`Renderer::gpu`].
+///
+/// ```rust,ignore
+/// let renderer = Renderer::new(1920, 1080).bloom(Bloom::default());
+///
+/// // in render_frame
+/// let image = renderer.render(&scene, &camera);
+/// fframes::svgr!(<image href={image.href()} x="0" y="0" width="1920" height="1080" />)
+/// ```
+#[derive(Debug, Clone, PartialEq)]
+pub struct Renderer {
+ /// The width of the image in pixels.
+ pub width: u32,
+ /// The height of the image in pixels.
+ pub height: u32,
+ /// Whether to use 4x multisampling. Without it, edges are jagged, but frames render
+ /// about two times faster.
+ pub antialias: bool,
+ /// The multiplier of the light before tone mapping.
+ pub exposure: f32,
+ /// How HDR colors map to the display.
+ pub tone_mapping: ToneMapping,
+ /// The glow around bright pixels, `None` for no glow.
+ pub bloom: Option<Bloom>,
+ /// Render on the GPU when the `wgpu` feature of fframes is on, see [`Renderer::gpu`].
+ pub gpu: bool,
+}
+
+/// Premultiplied sRGB RGBA8 pixels from [`Renderer::render_pixels`].
+///
+/// Use [`Pixels::get`] to read a pixel and [`Pixels::to_straight_rgba`] to save a PNG.
+#[derive(Debug, Clone)]
+pub struct Pixels {
+ pub width: u32,
+ pub height: u32,
+ /// Premultiplied alpha, row major.
+ pub rgba: Vec<u8>,
+}
+
+impl Pixels {
+ /// The pixel at `x`, `y`, with straight (not premultiplied) alpha.
+ pub fn get(&self, x: u32, y: u32) -> [u8; 4] {
+ straight(self.rgba.as_chunks::<4>().0[(y * self.width + x) as usize])
+ }
+
+ /// All pixels as straight alpha RGBA8, for example to save a PNG.
+ pub fn to_straight_rgba(&self) -> Vec<u8> {
+ self.rgba
+ .as_chunks::<4>()
+ .0
+ .iter()
+ .flat_map(|p| straight(*p))
+ .collect()
+ }
+
+ /// The image for an `<image href>` in `svgr!`.
+ pub fn into_image(self) -> fframes_media::ImageData<'static> {
+ use fframes_media::{ImageData, ImageMetadata};
+
+ static NEXT_ID: AtomicU64 = AtomicU64::new(0);
+ // Each image gets a new id, so a cache with the id as key never gives an old frame.
+ let id = format!(
+ "fframes_three_d:{}",
+ NEXT_ID.fetch_add(1, Ordering::Relaxed)
+ );
+ let (width, height) = (self.width, self.height);
+ let metadata = ImageMetadata { width, height };
+
+ #[cfg(not(target_arch = "wasm32"))]
+ return ImageData::new_from_raw_data(
+ std::sync::Arc::new(usvgr::PreloadedImageData {
+ data: std::borrow::Cow::Owned(self.rgba),
+ width,
+ height,
+ id: id.clone(),
+ }),
+ id,
+ metadata,
+ );
+
+ // The editor shows images from URLs, so the pixels go into a PNG data URL.
+ #[cfg(target_arch = "wasm32")]
+ {
+ use base64::Engine;
+
+ let mut png_bytes = Vec::new();
+ let mut encoder = png::Encoder::new(&mut png_bytes, width, height);
+ encoder.set_color(png::ColorType::Rgba);
+ encoder.set_depth(png::BitDepth::Eight);
+ encoder.set_compression(png::Compression::Fast);
+ if let Ok(mut writer) = encoder.write_header() {
+ let _ = writer.write_image_data(&self.to_straight_rgba());
+ }
+ let url = format!(
+ "data:image/png;base64,{}",
+ base64::engine::general_purpose::STANDARD.encode(&png_bytes)
+ );
+ ImageData::new_from_web_source(
+ fframes_media::OwnedSharedString::new_owned(url.as_str()),
+ url,
+ id,
+ metadata,
+ )
+ }
+ }
+}
+
+/// A premultiplied pixel with straight alpha.
+fn straight([r, g, b, a]: [u8; 4]) -> [u8; 4] {
+ if a == 0 {
+ return [0, 0, 0, 0];
+ }
+ let un = |c: u8| ((u32::from(c) * 255 + u32::from(a) / 2) / u32::from(a)).min(255) as u8;
+ [un(r), un(g), un(b), a]
+}
+
+impl Renderer {
+ /// A renderer for `width` x `height` images with antialiasing, ACES tone mapping and no
+ /// bloom. It renders on the GPU with the `wgpu` feature of fframes. In the wasm editor the
+ /// size is halved, so the previews stay interactive.
+ pub fn new(width: u32, height: u32) -> Self {
+ #[cfg(target_arch = "wasm32")]
+ let (width, height) = ((width / 2).max(1), (height / 2).max(1));
+ Self {
+ width: width.max(1),
+ height: height.max(1),
+ antialias: true,
+ exposure: 1.0,
+ tone_mapping: ToneMapping::Aces,
+ bloom: None,
+ gpu: cfg!(feature = "gpu"),
+ }
+ }
+
+ /// Renders on the GPU (Vulkan, Metal or DX12 through wgpu). This is the default with
+ /// the `wgpu` feature of fframes. Without the feature, or without a GPU that works, the
+ /// CPU renders. The shading is the same, and the pixels differ only by rounding.
+ pub fn gpu(mut self) -> Self {
+ self.gpu = true;
+ self
+ }
+
+ /// Renders on the CPU, also with the `wgpu` feature.
+ pub fn cpu(mut self) -> Self {
+ self.gpu = false;
+ self
+ }
+
+ /// Whether frames render on the GPU: [`Renderer::gpu`] is set and a GPU was found.
+ pub fn uses_gpu(&self) -> bool {
+ #[cfg(all(feature = "gpu", not(target_arch = "wasm32")))]
+ return self.gpu && crate::gpu::gpu().is_some();
+ #[cfg(not(all(feature = "gpu", not(target_arch = "wasm32"))))]
+ return false;
+ }
+
+ /// Adds a glow around bright pixels, see [`Bloom`].
+ pub fn bloom(mut self, bloom: Bloom) -> Self {
+ self.bloom = Some(bloom);
+ self
+ }
+
+ /// Multiplies the light before tone mapping. Values above 1 make the image brighter.
+ pub fn exposure(mut self, exposure: f32) -> Self {
+ self.exposure = exposure;
+ self
+ }
+
+ /// Sets how HDR colors map to the display, see [`ToneMapping`].
+ pub fn tone_mapping(mut self, tone_mapping: ToneMapping) -> Self {
+ self.tone_mapping = tone_mapping;
+ self
+ }
+
+ /// Turns 4x multisampling on or off. Without it, edges are jagged, but frames render
+ /// about two times faster.
+ pub fn antialias(mut self, antialias: bool) -> Self {
+ self.antialias = antialias;
+ self
+ }
+
+ /// Renders at `scale` times the size, for example for drafts. Put the image in the SVG
+ /// at the full size, and it scales up.
+ pub fn scaled(mut self, scale: f32) -> Self {
+ self.width = ((self.width as f32 * scale).round() as u32).max(1);
+ self.height = ((self.height as f32 * scale).round() as u32).max(1);
+ self
+ }
+
+ /// Renders a frame into an image for `<image href={image.href()} .../>`.
+ ///
+ /// With [`Renderer::gpu`] and a backend that shares its GPU (the Skia Vulkan backend
+ /// with its `wgpu` feature), the image is a texture on that GPU. The backend draws it
+ /// there, so the frame does not go back to the CPU. In all other cases the image holds
+ /// pixels.
+ pub fn render(&self, scene: &Scene, camera: &Camera) -> fframes_media::ImageData<'static> {
+ self.image(&[(scene, camera)])
+ }
+
+ /// Renders a frame into pixels.
+ pub fn render_pixels(&self, scene: &Scene, camera: &Camera) -> Pixels {
+ self.pixels(&[(scene, camera)])
+ }
+
+ /// Renders a frame with motion blur. It renders `samples` moments in the shutter time
+ /// and averages them before bloom and tone mapping.
+ ///
+ /// `moment(offset)` makes the scene and the camera at `offset`, in `-0.5..0.5`. The
+ /// shutter is centered on the frame. Map the offset to time, for example
+ /// `t + offset / fps * 0.5` for a half open shutter.
+ ///
+ /// ```rust,ignore
+ /// let image = renderer.render_motion_blur(4, |offset| self.build(t + offset / 60.0));
+ /// ```
+ pub fn render_motion_blur(
+ &self,
+ samples: usize,
+ moment: impl FnMut(f32) -> (Scene, Camera),
+ ) -> fframes_media::ImageData<'static> {
+ let moments: Vec<(Scene, Camera)> = shutter_offsets(samples).map(moment).collect();
+ let moments: Vec<(&Scene, &Camera)> = moments.iter().map(|(s, c)| (s, c)).collect();
+ self.image(&moments)
+ }
+
+ /// [`Renderer::render_motion_blur`] into pixels.
+ pub fn render_motion_blur_pixels(
+ &self,
+ samples: usize,
+ moment: impl FnMut(f32) -> (Scene, Camera),
+ ) -> Pixels {
+ let moments: Vec<(Scene, Camera)> = shutter_offsets(samples).map(moment).collect();
+ let moments: Vec<(&Scene, &Camera)> = moments.iter().map(|(s, c)| (s, c)).collect();
+ self.pixels(&moments)
+ }
+
+ /// The average of the moments as an image. It stays on the GPU when the backend shares
+ /// its GPU.
+ fn image(&self, moments: &[(&Scene, &Camera)]) -> fframes_media::ImageData<'static> {
+ #[cfg(all(feature = "gpu", not(target_arch = "wasm32")))]
+ if self.gpu
+ && let Some(image) = crate::gpu::layer(self, moments)
+ {
+ return image;
+ }
+ self.pixels(moments).into_image()
+ }
+
+ /// The average of the moments as pixels.
+ fn pixels(&self, moments: &[(&Scene, &Camera)]) -> Pixels {
+ #[cfg(all(feature = "gpu", not(target_arch = "wasm32")))]
+ if self.gpu
+ && let Some(gpu) = crate::gpu::gpu()
+ {
+ return gpu.render(self, moments);
+ }
+ self.cpu_pixels(moments)
+ }
+
+ /// The average of the moments as pixels of the CPU rasterizer. The moments render at
+ /// the same time.
+ fn cpu_pixels(&self, moments: &[(&Scene, &Camera)]) -> Pixels {
+ let mut hdr = moments
+ .par_iter()
+ .map(|(scene, camera)| self.render_hdr(scene, camera))
+ .collect::<Vec<_>>()
+ .into_iter()
+ .reduce(|mut sum, hdr| {
+ sum.iter_mut().zip(&hdr).for_each(|(a, b)| *a += *b);
+ sum
+ })
+ .unwrap_or_default();
+ if moments.len() > 1 {
+ let scale = 1.0 / moments.len() as f32;
+ for p in &mut hdr {
+ *p *= scale;
+ }
+ }
+ let (width, height) = (self.width as usize, self.height as usize);
+ if let Some(bloom) = &self.bloom {
+ post::bloom(&mut hdr, width, height, bloom);
+ }
+ Pixels {
+ width: self.width,
+ height: self.height,
+ rgba: post::encode(&hdr, width, height, self.exposure, self.tone_mapping),
+ }
+ }
+
+ /// Premultiplied linear HDR pixels, before bloom and tone mapping.
+ fn render_hdr(&self, scene: &Scene, camera: &Camera) -> Vec<Vec4> {
+ let (width, height) = (self.width as usize, self.height as usize);
+ let (mut world, lights) = prepare::build_world(scene);
+ let shadows: Vec<Option<ShadowMap>> = lights
+ .shadow_casters
+ .iter()
+ .map(|(direction, settings)| ShadowMap::build(*direction, settings, &world))
+ .collect();
+ let baked = scene.environment.baked();
+ let ortho = camera.ortho_height.is_some();
+ let view_proj = camera.view_projection(width as f32 / height as f32);
+ // The shading of the frame. The reflection changes only the camera fields.
+ let frame = ShadeContext {
+ lights: &lights,
+ shadows: &shadows,
+ environment: &scene.environment,
+ baked: baked.as_deref(),
+ fog: scene.fog,
+ background: &scene.background,
+ camera_position: camera.position,
+ ortho_forward: ortho.then(|| camera.forward()),
+ reflection: None,
+ viewport: Vec2::new(width as f32, height as f32),
+ };
+
+ // The reflection renders first, because the surfaces that show it sample it.
+ let reflection = scene
+ .reflector
+ .filter(|_| world.draws.iter().any(|d| d.material.reflection > 0.0))
+ .map(|reflector| {
+ let size = (frame.viewport * reflector.scale).ceil().max(Vec2::ONE);
+ let mirror = reflector.matrix();
+ let shade = ShadeContext {
+ camera_position: mirror.transform_point3(camera.position),
+ ortho_forward: frame.ortho_forward.map(|f| mirror.transform_vector3(f)),
+ viewport: size,
+ ..frame
+ };
+ let viewport = Viewport {
+ size,
+ view_proj: view_proj * mirror,
+ ortho,
+ mirrored: true,
+ clip_plane: Some(reflector.plane()),
+ };
+ let (hdr, _) = render_view(&mut world, &shade, &viewport, camera, false);
+ ReflectionMap::new(size.x as usize, size.y as usize, hdr)
+ });
+
+ let shade = ShadeContext {
+ reflection: reflection.as_ref(),
+ ..frame
+ };
+ let viewport = Viewport {
+ size: frame.viewport,
+ view_proj,
+ ortho,
+ mirrored: false,
+ clip_plane: None,
+ };
+ let (mut hdr, depth) = render_view(&mut world, &shade, &viewport, camera, self.antialias);
+ if let Some(focus) = camera.focus
+ && !ortho
+ && focus.blur > 0.0
+ {
+ // `blur` is in pixels of a 1080 pixel tall frame
+ let scale = height as f32 / 1080.0;
+ post::depth_of_field(
+ &mut hdr,
+ &depth,
+ width,
+ height,
+ focus.distance,
+ focus.blur * scale,
+ );
+ }
+ hdr
+ }
+}
+
+/// The moments of a shutter that is centered on the frame, in `-0.5..0.5`.
+fn shutter_offsets(samples: usize) -> impl Iterator<Item = f32> {
+ let samples = samples.max(1);
+ (0..samples).map(move |i| (i as f32 + 0.5) / samples as f32 - 0.5)
+}
+
+/// Renders one view into premultiplied linear HDR. Also returns the depth key of the
+/// nearest opaque surface of each pixel.
+///
+/// The mirrored view of a reflection leaves out the particles and the surfaces that show
+/// the reflection.
+fn render_view(
+ world: &mut World,
+ shade: &ShadeContext,
+ viewport: &Viewport,
+ camera: &Camera,
+ multisample: bool,
+) -> (Vec<Vec4>, Vec<f32>) {
+ let reflection = viewport.mirrored;
+ let (opaque, blended_tris) = prepare::setup_triangles(world, viewport, |d| {
+ !reflection || d.material.reflection <= 0.0
+ });
+ let sprites = if reflection {
+ Vec::new()
+ } else {
+ prepare::setup_sprites(&world.sprites, camera, viewport)
+ };
+ let mut blended: Vec<Blended> = blended_tris
+ .iter()
+ .map(Blended::Tri)
+ .chain(sprites.iter().map(Blended::Sprite))
+ .collect();
+ blended.sort_by(|a, b| b.depth().total_cmp(&a.depth()));
+ raster::rasterize(&raster::Frame {
+ width: viewport.size.x as usize,
+ height: viewport.size.y as usize,
+ streams: &world.streams,
+ draws: &world.draws,
+ opaque: &opaque,
+ blended: &blended,
+ shade,
+ inverse_view_proj: viewport.view_proj.inverse(),
+ multisample,
+ })
+}
diff --git a/fframes-three-d/src/render/post.rs b/fframes-three-d/src/render/post.rs
new file mode 100644
index 00000000..beef4824
--- /dev/null
+++ b/fframes-three-d/src/render/post.rs
@@ -0,0 +1,403 @@
+//! Post processing of the HDR frame: bloom, depth of field, tone mapping and the conversion
+//! to premultiplied sRGB bytes.
+
+use std::sync::LazyLock;
+
+use glam::{Mat3, Vec2, Vec3, Vec4};
+use rayon::prelude::*;
+
+use super::reflection::{MAX_LEVELS, level_count};
+use crate::color::linear_to_srgb;
+
+/// Glow around bright pixels, like the three.js `UnrealBloomPass`.
+///
+/// Give it to [`Renderer::bloom`](super::Renderer::bloom). Only pixels brighter than
+/// `threshold` glow. Thus the parts that must glow need an emissive intensity above it.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct Bloom {
+ /// How much glow is added.
+ pub strength: f32,
+ /// How far the glow spreads, `0..1`.
+ pub radius: f32,
+ /// The linear brightness above which pixels glow. Lit surfaces are seldom brighter
+ /// than 1. Emissive parts and sparks must be brighter.
+ pub threshold: f32,
+}
+
+impl Default for Bloom {
+ fn default() -> Self {
+ Self {
+ strength: 0.8,
+ radius: 0.6,
+ threshold: 1.0,
+ }
+ }
+}
+
+/// How HDR colors map to the display, as in three.js.
+///
+/// Set it with [`Renderer::tone_mapping`](super::Renderer::tone_mapping).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum ToneMapping {
+ /// Clamps each channel to `0..1`.
+ Linear,
+ /// three.js `ACESFilmicToneMapping`. It gives high contrast, and bright colors become
+ /// white.
+ #[default]
+ Aces,
+ /// three.js `NeutralToneMapping` (Khronos PBR Neutral). It keeps base colors accurate.
+ Neutral,
+}
+
+/// An image of linear premultiplied colors, row major. The bloom and the reflection filter
+/// it.
+pub(crate) struct Image {
+ pub width: usize,
+ pub height: usize,
+ pub data: Vec<Vec4>,
+}
+
+impl Image {
+ /// The bilinear sample at `u`, `v` (`0..1` over the image). Outside the image it
+ /// clamps to the edge, like the GPU sampler.
+ pub fn sample(&self, u: f32, v: f32) -> Vec4 {
+ let x = (u * self.width as f32 - 0.5).clamp(0.0, self.width as f32 - 1.0);
+ let y = (v * self.height as f32 - 0.5).clamp(0.0, self.height as f32 - 1.0);
+ let (x0, y0) = (x.floor() as usize, y.floor() as usize);
+ let (x1, y1) = ((x0 + 1).min(self.width - 1), (y0 + 1).min(self.height - 1));
+ let (fx, fy) = (x - x0 as f32, y - y0 as f32);
+ let at = |x: usize, y: usize| self.data[y * self.width + x];
+ at(x0, y0)
+ .lerp(at(x1, y0), fx)
+ .lerp(at(x0, y1).lerp(at(x1, y1), fx), fy)
+ }
+
+ /// The image and its [`level_count`] levels. Each level has half the size of the
+ /// level before it.
+ pub fn mip_chain(self) -> Vec<Image> {
+ let count = level_count(self.width, self.height);
+ let mut levels = vec![self];
+ while levels.len() < count {
+ levels.push(levels[levels.len() - 1].downsample());
+ }
+ levels
+ }
+
+ /// Makes a copy at half the size from four bilinear taps one texel out (a 4x4 tent
+ /// filter). The GPU does the same in `fs_down` and `fs_down_rgba`.
+ fn downsample(&self) -> Image {
+ let width = (self.width / 2).max(1);
+ let height = (self.height / 2).max(1);
+ let (du, dv) = (1.0 / self.width as f32, 1.0 / self.height as f32);
+ let mut data = vec![Vec4::ZERO; width * height];
+ data.par_chunks_mut(width).enumerate().for_each(|(y, row)| {
+ let v = (y as f32 + 0.5) / height as f32;
+ for (x, out) in row.iter_mut().enumerate() {
+ let u = (x as f32 + 0.5) / width as f32;
+ *out = (self.sample(u - du, v - dv)
+ + self.sample(u + du, v - dv)
+ + self.sample(u - du, v + dv)
+ + self.sample(u + du, v + dv))
+ * 0.25;
+ }
+ });
+ Image {
+ width,
+ height,
+ data,
+ }
+ }
+
+ /// Adds `coarse`, upsampled with a 3x3 tent filter, times `weight`.
+ fn add_upsampled(&mut self, coarse: &Image, weight: f32) {
+ let (width, height) = (self.width, self.height);
+ let (du, dv) = (1.0 / coarse.width as f32, 1.0 / coarse.height as f32);
+ self.data
+ .par_chunks_mut(width)
+ .enumerate()
+ .for_each(|(y, row)| {
+ let v = (y as f32 + 0.5) / height as f32;
+ for (x, out) in row.iter_mut().enumerate() {
+ let u = (x as f32 + 0.5) / width as f32;
+ let mut sum = coarse.sample(u, v) * 4.0;
+ sum += (coarse.sample(u - du, v)
+ + coarse.sample(u + du, v)
+ + coarse.sample(u, v - dv)
+ + coarse.sample(u, v + dv))
+ * 2.0;
+ sum += coarse.sample(u - du, v - dv)
+ + coarse.sample(u + du, v - dv)
+ + coarse.sample(u - du, v + dv)
+ + coarse.sample(u + du, v + dv);
+ *out += sum * (weight / 16.0);
+ }
+ });
+ }
+}
+
+/// Adds the glow of `bloom` to `hdr`, a frame of `width` x `height` pixels.
+pub(crate) fn bloom(hdr: &mut [Vec4], width: usize, height: usize, bloom: &Bloom) {
+ if bloom.strength <= 0.0 {
+ return;
+ }
+ // The bright pass, at half resolution and with a soft knee.
+ let (hw, hh) = ((width / 2).max(1), (height / 2).max(1));
+ let threshold = bloom.threshold.max(0.0);
+ let knee = threshold * 0.5 + 1e-4;
+ let mut bright = vec![Vec4::ZERO; hw * hh];
+ let source = &*hdr;
+ bright.par_chunks_mut(hw).enumerate().for_each(|(y, row)| {
+ for (x, out) in row.iter_mut().enumerate() {
+ let mut sum = Vec3::ZERO;
+ for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
+ let sx = (x * 2 + dx).min(width - 1);
+ let sy = (y * 2 + dy).min(height - 1);
+ sum += source[sy * width + sx].truncate();
+ }
+ let c = sum * 0.25;
+ let brightness = c.max_element();
+ let soft = (brightness - threshold + knee).clamp(0.0, 2.0 * knee);
+ let soft = soft * soft / (4.0 * knee);
+ let contribution = soft.max(brightness - threshold) / brightness.max(1e-4);
+ *out = (c * contribution.max(0.0)).extend(0.0);
+ }
+ });
+
+ // Each level glows wider than the level before it. These are the weights of the levels
+ // after the first. `radius` moves weight to the wide levels.
+ const FACTORS: [f32; MAX_LEVELS - 1] = [0.8, 0.6, 0.4, 0.2, 0.1];
+ let mut levels = Image {
+ width: hw,
+ height: hh,
+ data: bright,
+ }
+ .mip_chain();
+ let Some(mut glow) = levels.pop() else {
+ return;
+ };
+ while let Some(mut finer) = levels.pop() {
+ // three.js `lerpBloomFactor`
+ let f = FACTORS[levels.len()];
+ finer.add_upsampled(&glow, (f + (1.2 - f - f) * bloom.radius).max(0.0));
+ glow = finer;
+ }
+ hdr.par_chunks_mut(width).enumerate().for_each(|(y, row)| {
+ let v = (y as f32 + 0.5) / height as f32;
+ for (x, px) in row.iter_mut().enumerate() {
+ let u = (x as f32 + 0.5) / width as f32;
+ *px += glow.sample(u, v) * bloom.strength;
+ }
+ });
+}
+
+fn aces(color: Vec3) -> Vec3 {
+ const INPUT: Mat3 = Mat3::from_cols(
+ Vec3::new(0.59719, 0.07600, 0.02840),
+ Vec3::new(0.35458, 0.90834, 0.13383),
+ Vec3::new(0.04823, 0.01566, 0.83777),
+ );
+ const OUTPUT: Mat3 = Mat3::from_cols(
+ Vec3::new(1.60475, -0.10208, -0.00327),
+ Vec3::new(-0.53108, 1.10813, -0.07276),
+ Vec3::new(-0.07367, -0.00605, 1.07602),
+ );
+ let v = INPUT * (color / 0.6);
+ let a = v * (v + 0.024_578_6) - 0.000_090_537;
+ let b = v * (0.983_729 * v + 0.432_951) + 0.238_081;
+ (OUTPUT * (a / b)).clamp(Vec3::ZERO, Vec3::ONE)
+}
+
+fn neutral(mut color: Vec3) -> Vec3 {
+ const START: f32 = 0.8 - 0.04;
+ const DESATURATION: f32 = 0.15;
+ let x = color.min_element();
+ let offset = if x < 0.08 { x - 6.25 * x * x } else { 0.04 };
+ color -= offset;
+ let peak = color.max_element();
+ if peak < START {
+ return color.max(Vec3::ZERO);
+ }
+ let d = 1.0 - START;
+ let new_peak = 1.0 - d * d / (peak + d - START);
+ color *= new_peak / peak;
+ let g = 1.0 - 1.0 / (DESATURATION * (peak - new_peak) + 1.0);
+ color.lerp(Vec3::splat(new_peak), g).max(Vec3::ZERO)
+}
+
+const LUT_SIZE: usize = 16384;
+
+/// The sRGB bytes of `LUT_SIZE` linear values in `0..1`.
+static SRGB: LazyLock<Vec<u8>> = LazyLock::new(|| {
+ (0..LUT_SIZE)
+ .map(|i| {
+ (linear_to_srgb(i as f32 / (LUT_SIZE - 1) as f32) * 255.0)
+ .round()
+ .clamp(0.0, 255.0) as u8
+ })
+ .collect()
+});
+
+/// Tone maps `hdr` and encodes it as premultiplied sRGB RGBA8, the format of `usvgr`
+/// images.
+pub(crate) fn encode(
+ hdr: &[Vec4],
+ width: usize,
+ height: usize,
+ exposure: f32,
+ tone_mapping: ToneMapping,
+) -> Vec<u8> {
+ let lut: &[u8] = &SRGB;
+ let mut out = vec![0u8; width * height * 4];
+ out.par_chunks_mut(width * 4)
+ .enumerate()
+ .for_each(|(y, row)| {
+ for (x, out) in row.as_chunks_mut::<4>().0.iter_mut().enumerate() {
+ let px = hdr[y * width + x];
+ let rgb = px.truncate().max(Vec3::ZERO) * exposure;
+ // Light without coverage (glows, additive blending) becomes partly opaque light.
+ let alpha = px.w.max(rgb.max_element().min(1.0)).clamp(0.0, 1.0);
+ if alpha <= 0.0 {
+ continue;
+ }
+ let straight = rgb / alpha;
+ let mapped = match tone_mapping {
+ ToneMapping::Linear => straight.clamp(Vec3::ZERO, Vec3::ONE),
+ ToneMapping::Aces => aces(straight),
+ ToneMapping::Neutral => neutral(straight).clamp(Vec3::ZERO, Vec3::ONE),
+ };
+ let a8 = (alpha * 255.0 + 0.5) as u8;
+ let alpha = f32::from(a8) / 255.0;
+ // An ordered dither against banding in dark gradients.
+ let dither = (bayer(x, y) - 0.5) / 255.0;
+ let channel = |c: f32| {
+ let i = ((c * (LUT_SIZE - 1) as f32) as usize).min(LUT_SIZE - 1);
+ let srgb = f32::from(lut[i]) / 255.0;
+ (((srgb + dither) * alpha).clamp(0.0, 1.0) * 255.0 + 0.5) as u8
+ };
+ *out = [channel(mapped.x), channel(mapped.y), channel(mapped.z), a8];
+ }
+ });
+ out
+}
+
+/// The 4x4 Bayer threshold of a pixel, in `0..1`.
+#[inline]
+fn bayer(x: usize, y: usize) -> f32 {
+ const M: [[u8; 4]; 4] = [[0, 8, 2, 10], [12, 4, 14, 6], [3, 11, 1, 9], [15, 7, 13, 5]];
+ (f32::from(M[y & 3][x & 3]) + 0.5) / 16.0
+}
+
+/// Blurs `hdr` by the distance from the focus, like the depth of field of a lens.
+///
+/// It gathers, as in the single pass bokeh of Gustafsson. Each pixel averages samples on a
+/// golden angle spiral, out to the largest blur near it. A sample counts where its own blur
+/// reaches back to the pixel. Samples behind a sharp pixel blur only a little into it. Thus
+/// sharp edges stay sharp in front of a blurred background.
+///
+/// `depth` holds the depth key of each pixel: `1 / distance`, or 0 for the background.
+/// `focus` is the focus distance. `blur` is the blur radius in pixels of objects very far
+/// behind the focus.
+pub(crate) fn depth_of_field(
+ hdr: &mut [Vec4],
+ depth: &[f32],
+ width: usize,
+ height: usize,
+ focus: f32,
+ blur: f32,
+) {
+ // Samples nearer than INNER pixels read the frame. Samples farther away read a copy at
+ // half resolution: the blur is wide there, and the smaller copy stays in the cache.
+ const INNER: f32 = 6.0;
+ const TILE: usize = 16;
+ let max_blur = (blur * 1.6).min(40.0);
+ // `focus * key` is `focus / distance`.
+ let coc_of = |key: f32| (blur * (1.0 - focus * key).abs()).min(max_blur);
+ let coc: Vec<f32> = depth.iter().map(|&key| coc_of(key)).collect();
+
+ // The largest blur that reaches into each tile. Pixels of tiles without blur are
+ // skipped.
+ let (tw, th) = (width.div_ceil(TILE), height.div_ceil(TILE));
+ let mut tile_max = vec![0.0f32; tw * th];
+ for y in 0..height {
+ for x in 0..width {
+ let t = (y / TILE) * tw + x / TILE;
+ tile_max[t] = tile_max[t].max(coc[y * width + x]);
+ }
+ }
+ let reach = (max_blur / TILE as f32).ceil() as usize;
+ let mut near_max = vec![0.0f32; tw * th];
+ for ty in 0..th {
+ for tx in 0..tw {
+ let mut m = 0.0f32;
+ for ny in ty.saturating_sub(reach)..(ty + reach + 1).min(th) {
+ for nx in tx.saturating_sub(reach)..(tx + reach + 1).min(tw) {
+ m = m.max(tile_max[ny * tw + nx]);
+ }
+ }
+ near_max[ty * tw + tx] = m;
+ }
+ }
+
+ let source = hdr.to_vec();
+ let (hw, hh) = (width.div_ceil(2), height.div_ceil(2));
+ let mut half = vec![(Vec4::ZERO, 0.0f32); hw * hh];
+ half.par_chunks_mut(hw).enumerate().for_each(|(hy, row)| {
+ for (hx, out) in row.iter_mut().enumerate() {
+ let mut color = Vec4::ZERO;
+ let mut key = 0.0;
+ for dy in 0..2 {
+ for dx in 0..2 {
+ let x = (hx * 2 + dx).min(width - 1);
+ let y = (hy * 2 + dy).min(height - 1);
+ color += source[y * width + x];
+ key += depth[y * width + x];
+ }
+ }
+ *out = (color * 0.25, key * 0.25);
+ }
+ });
+ // The sample direction turns by the golden angle from sample to sample.
+ let turn = Vec2::from_angle(2.399_963);
+ hdr.par_chunks_mut(width).enumerate().for_each(|(y, row)| {
+ for (x, out) in row.iter_mut().enumerate() {
+ let radius_max = near_max[(y / TILE) * tw + x / TILE];
+ if radius_max < 0.5 {
+ continue;
+ }
+ let i = y * width + x;
+ let center_coc = coc[i];
+ let center_key = depth[i];
+ let mut sum = source[i];
+ let mut count = 1.0;
+ let mut radius = 0.8f32;
+ let mut dir = Vec2::X;
+ while radius < radius_max {
+ let offset = dir * radius;
+ // `as usize` saturates at 0, so samples past the edge read the edge pixel.
+ let (color, key) = if radius < INNER {
+ let sx = ((x as f32 + offset.x).round() as usize).min(width - 1);
+ let sy = ((y as f32 + offset.y).round() as usize).min(height - 1);
+ (source[sy * width + sx], depth[sy * width + sx])
+ } else {
+ // the 2x2 block that the sample point is in
+ let sx = (((x as f32 + 0.5 + offset.x) * 0.5) as usize).min(hw - 1);
+ let sy = (((y as f32 + 0.5 + offset.y) * 0.5) as usize).min(hh - 1);
+ half[sy * hw + sx]
+ };
+ let mut sample_coc = coc_of(key);
+ // A sample farther away than the pixel (a smaller key) blurs only a little
+ // over it.
+ if key < center_key {
+ sample_coc = sample_coc.min(center_coc * 2.0);
+ }
+ let m = (sample_coc - radius + 0.5).clamp(0.0, 1.0);
+ sum += (sum / count).lerp(color, m);
+ count += 1.0;
+ // The far samples are 2x2 averages, so half the density is enough.
+ radius += if radius < INNER { 1.6 } else { 3.2 } / radius;
+ dir = turn.rotate(dir);
+ }
+ *out = sum / count;
+ }
+ });
+}
diff --git a/fframes-three-d/src/render/prepare.rs b/fframes-three-d/src/render/prepare.rs
new file mode 100644
index 00000000..c6997399
--- /dev/null
+++ b/fframes-three-d/src/render/prepare.rs
@@ -0,0 +1,667 @@
+//! Prepares a scene for the rasterizer. First the meshes, particles and lights go into
+//! world space once per frame. Then each view projects them into screen triangles and
+//! screen particles.
+
+use glam::{Mat3, Mat4, Vec2, Vec3, Vec4};
+
+use crate::scene::{Mesh, Object};
+use crate::{Blending, Camera, Light, Material, Scene, Side};
+
+/// A mesh instance of the frame.
+pub(crate) struct Draw<'s> {
+ pub material: &'s Material,
+ pub cast_shadow: bool,
+ pub receive_shadow: bool,
+ pub has_uv: bool,
+ pub has_color: bool,
+}
+
+/// The world space vertices of all visible meshes.
+#[derive(Default)]
+pub(crate) struct Streams {
+ pub pos: Vec<Vec3>,
+ pub nrm: Vec<Vec3>,
+ pub uv: Vec<Vec2>,
+ pub col: Vec<Vec4>,
+}
+
+impl Streams {
+ /// Adds the vertex at `t` from vertex `a` to vertex `b`, and returns its index.
+ fn lerp(&mut self, a: u32, b: u32, t: f32) -> u32 {
+ let (a, b) = (a as usize, b as usize);
+ self.pos.push(self.pos[a].lerp(self.pos[b], t));
+ self.nrm.push(self.nrm[a].lerp(self.nrm[b], t));
+ self.uv.push(self.uv[a].lerp(self.uv[b], t));
+ self.col.push(self.col[a].lerp(self.col[b], t));
+ self.pos.len() as u32 - 1
+ }
+}
+
+/// A world space triangle: three indices into [`Streams`] and the index of its [`Draw`].
+#[derive(Clone, Copy)]
+pub(crate) struct WorldTri {
+ pub v: [u32; 3],
+ pub draw: u32,
+}
+
+/// The type and the world space placement of a direct light.
+pub(crate) enum LightKind {
+ Directional {
+ /// The direction in which the light travels.
+ direction: Vec3,
+ /// The index of the light in [`Lights::shadow_casters`].
+ shadow: Option<usize>,
+ },
+ Point {
+ position: Vec3,
+ /// The distance at which the light stops, 0 for no limit.
+ distance: f32,
+ decay: f32,
+ },
+ Spot {
+ position: Vec3,
+ direction: Vec3,
+ distance: f32,
+ decay: f32,
+ /// The cosine of the angle at which the cone ends.
+ cos_outer: f32,
+ /// The cosine of the angle at which the soft edge of the cone starts.
+ cos_inner: f32,
+ },
+}
+
+/// A direct light.
+pub(crate) struct LightInfo {
+ /// The color times the intensity.
+ pub color: Vec3,
+ pub kind: LightKind,
+}
+
+/// The lights of a frame.
+#[derive(Default)]
+pub(crate) struct Lights {
+ pub direct: Vec<LightInfo>,
+ /// The sum of the ambient lights.
+ pub ambient: Vec3,
+ /// The sums of the sky and the ground colors of the hemisphere lights.
+ pub hemisphere: Option<(Vec3, Vec3)>,
+ /// The direction and the shadow settings of each directional light with a shadow.
+ pub shadow_casters: Vec<(Vec3, crate::Shadow)>,
+}
+
+/// The visible meshes and particles of a frame in world space.
+#[derive(Default)]
+pub(crate) struct World<'s> {
+ pub streams: Streams,
+ pub tris: Vec<WorldTri>,
+ pub draws: Vec<Draw<'s>>,
+ pub sprites: Vec<WorldSprite>,
+}
+
+/// A particle in world space.
+pub(crate) struct WorldSprite {
+ pub position: Vec3,
+ pub size: f32,
+ /// The color times the opacity.
+ pub color: Vec3,
+ pub opacity: f32,
+ pub additive: bool,
+}
+
+/// Puts the visible meshes, particles and lights of `scene` into world space.
+pub(crate) fn build_world(scene: &Scene) -> (World<'_>, Lights) {
+ let worlds = scene.world_matrices();
+ let visible = scene.visibilities();
+ let mut world = World::default();
+ let mut lights = Lights::default();
+ for (id, node) in scene.nodes() {
+ if !visible[id.index()] {
+ continue;
+ }
+ let m = worlds[id.index()];
+ match &node.object {
+ Object::Group => {}
+ Object::Mesh(mesh) => push_mesh(&mut world, mesh, &m, &worlds),
+ Object::Light(light) => push_light(&mut lights, light, &m),
+ Object::Particles(particles) => {
+ let scale = m.x_axis.truncate().length();
+ for p in &particles.items {
+ if p.opacity <= 0.0 {
+ continue;
+ }
+ world.sprites.push(WorldSprite {
+ position: m.transform_point3(p.position),
+ size: p.size * scale,
+ color: p.color.0 * p.opacity,
+ opacity: p.opacity,
+ additive: particles.blending == Blending::Additive,
+ });
+ }
+ }
+ }
+ }
+ (world, lights)
+}
+
+/// Adds `light` with the world matrix `m` to `lights`.
+pub(crate) fn push_light(lights: &mut Lights, light: &Light, m: &Mat4) {
+ let rotate = |d: Vec3| m.transform_vector3(d).normalize_or(d);
+ let position = m.w_axis.truncate();
+ match light {
+ Light::Ambient { color, intensity } => lights.ambient += color.0 * *intensity,
+ Light::Hemisphere {
+ sky,
+ ground,
+ intensity,
+ } => {
+ let (s, g) = lights.hemisphere.unwrap_or((Vec3::ZERO, Vec3::ZERO));
+ lights.hemisphere = Some((s + sky.0 * *intensity, g + ground.0 * *intensity));
+ }
+ Light::Directional(l) => {
+ let direction = rotate(l.direction);
+ let shadow = l.shadow.as_ref().map(|shadow| {
+ lights.shadow_casters.push((direction, shadow.clone()));
+ lights.shadow_casters.len() - 1
+ });
+ lights.direct.push(LightInfo {
+ color: l.color.0 * l.intensity,
+ kind: LightKind::Directional { direction, shadow },
+ });
+ }
+ Light::Point(l) => lights.direct.push(LightInfo {
+ color: l.color.0 * l.intensity,
+ kind: LightKind::Point {
+ position,
+ distance: l.distance,
+ decay: l.decay,
+ },
+ }),
+ Light::Spot(l) => lights.direct.push(LightInfo {
+ color: l.color.0 * l.intensity,
+ kind: LightKind::Spot {
+ position,
+ direction: rotate(l.direction),
+ distance: l.distance,
+ decay: l.decay,
+ cos_outer: l.angle.cos(),
+ cos_inner: (l.angle * (1.0 - l.penumbra)).cos(),
+ },
+ }),
+ }
+}
+
+/// Adds `mesh` with the world matrix `m`. `worlds` holds the world matrices of all nodes,
+/// for the joints of skinned meshes.
+fn push_mesh<'s>(world: &mut World<'s>, mesh: &'s Mesh, m: &Mat4, worlds: &[Mat4]) {
+ let g = &*mesh.geometry;
+ if g.indices.is_empty() || g.positions.is_empty() {
+ return;
+ }
+ let deformed = deformed(mesh, m, worlds);
+ // Every copy with its world matrix and color. A deformed mesh has no copies.
+ let instances = mesh.instances.as_deref().filter(|_| deformed.is_none());
+ let copies: Vec<(Mat4, Vec4)> = match instances {
+ Some(instances) => (instances.transforms.iter().enumerate())
+ .map(|(i, t)| (*m * *t, instances.color(i)))
+ .collect(),
+ None => vec![(*m, Vec4::ONE)],
+ };
+ let draw = world.draws.len() as u32;
+ world.draws.push(Draw {
+ material: &mesh.material,
+ cast_shadow: mesh.cast_shadow,
+ receive_shadow: mesh.receive_shadow,
+ has_uv: !g.uvs.is_empty(),
+ has_color: !g.colors.is_empty() || instances.is_some_and(|i| !i.colors.is_empty()),
+ });
+
+ let count = g.positions.len();
+ for (m, tint) in copies {
+ let base = world.streams.pos.len() as u32;
+ let s = &mut world.streams;
+ if let Some((pos, nrm)) = &deformed {
+ s.pos.extend_from_slice(pos);
+ s.nrm.extend_from_slice(nrm);
+ } else {
+ let normal_matrix = Mat3::from_mat4(m).inverse().transpose();
+ s.pos
+ .extend(g.positions.iter().map(|p| m.transform_point3(*p)));
+ s.nrm.extend((0..count).map(|i| {
+ (normal_matrix * g.normals.get(i).copied().unwrap_or(Vec3::Y)).normalize_or(Vec3::Y)
+ }));
+ }
+ if g.uvs.len() == count {
+ s.uv.extend_from_slice(&g.uvs);
+ } else {
+ s.uv.extend(std::iter::repeat_n(Vec2::ZERO, count));
+ }
+ if g.colors.len() == count {
+ s.col.extend(g.colors.iter().map(|c| *c * tint));
+ } else {
+ s.col.extend(std::iter::repeat_n(tint, count));
+ }
+
+ // A mirroring world matrix turns the winding around. Skinned vertices do not use it.
+ let mirrored = mesh.skin.is_none() && m.determinant() < 0.0;
+ let tris = g.indices.as_chunks::<3>().0.iter();
+ world.tris.extend(
+ tris.filter(|t| t.iter().all(|&i| (i as usize) < count))
+ .map(|t| {
+ let [a, b, c] = t.map(|i| base + i);
+ let v = if mirrored { [a, c, b] } else { [a, b, c] };
+ WorldTri { v, draw }
+ }),
+ );
+ }
+}
+
+/// The world space positions and normals of a skinned or morphed mesh. `None` for a rigid
+/// mesh, which its world matrix `m` places.
+pub(crate) fn deformed(mesh: &Mesh, m: &Mat4, worlds: &[Mat4]) -> Option<(Vec<Vec3>, Vec<Vec3>)> {
+ let g = &*mesh.geometry;
+ let count = g.positions.len();
+ let morphing = mesh.morph_weights.iter().any(|w| *w != 0.0) && !g.morph_targets.is_empty();
+ let skinning = mesh.skin.is_some() && g.skin.is_some();
+ if !morphing && !skinning {
+ return None;
+ }
+ let mut pos = g.positions.clone();
+ let mut nrm: Vec<Vec3> = (0..count)
+ .map(|i| g.normals.get(i).copied().unwrap_or(Vec3::Y))
+ .collect();
+ if morphing {
+ for (target, &w) in g.morph_targets.iter().zip(&mesh.morph_weights) {
+ if w == 0.0 {
+ continue;
+ }
+ for (p, d) in pos.iter_mut().zip(&target.positions) {
+ *p += *d * w;
+ }
+ for (n, d) in nrm.iter_mut().zip(&target.normals) {
+ *n += *d * w;
+ }
+ }
+ }
+ if let (Some(skin), Some(weights)) = (&mesh.skin, &g.skin) {
+ let joints: Vec<Mat4> = skin
+ .joints
+ .iter()
+ .enumerate()
+ .map(|(i, joint)| {
+ let world = worlds.get(joint.index()).copied().unwrap_or(Mat4::IDENTITY);
+ let inverse_bind = skin.inverse_bind_matrices.get(i).copied();
+ world * inverse_bind.unwrap_or(Mat4::IDENTITY)
+ })
+ .collect();
+ for i in 0..count {
+ let vertex_joints = weights.joints.get(i).copied().unwrap_or_default();
+ let vertex_weights = weights.weights.get(i).copied();
+ let mut skin_m = Mat4::ZERO;
+ for (&joint, &w) in vertex_joints
+ .iter()
+ .zip(&vertex_weights.unwrap_or([1.0, 0.0, 0.0, 0.0]))
+ {
+ if w != 0.0 {
+ skin_m += joints
+ .get(joint as usize)
+ .copied()
+ .unwrap_or(Mat4::IDENTITY)
+ * w;
+ }
+ }
+ pos[i] = skin_m.transform_point3(pos[i]);
+ nrm[i] = (Mat3::from_mat4(skin_m) * nrm[i]).normalize_or(Vec3::Y);
+ }
+ } else {
+ let normal_matrix = Mat3::from_mat4(*m).inverse().transpose();
+ for (p, n) in pos.iter_mut().zip(&mut nrm) {
+ *p = m.transform_point3(*p);
+ *n = (normal_matrix * *n).normalize_or(Vec3::Y);
+ }
+ }
+ Some((pos, nrm))
+}
+
+/// Pixel bounds, half open: `x0..x1` and `y0..y1`.
+#[derive(Clone, Copy)]
+pub(crate) struct Rect {
+ pub x0: usize,
+ pub y0: usize,
+ pub x1: usize,
+ pub y1: usize,
+}
+
+impl Rect {
+ /// The pixels that the box from `min` to `max` touches on a screen of `size` pixels.
+ /// `None` when the box touches no pixel.
+ fn covering(min: Vec2, max: Vec2, size: Vec2) -> Option<Rect> {
+ let lo = min.floor().max(Vec2::ZERO);
+ let hi = max.ceil().min(size);
+ (lo.x < hi.x && lo.y < hi.y).then_some(Rect {
+ x0: lo.x as usize,
+ y0: lo.y as usize,
+ x1: hi.x as usize,
+ y1: hi.y as usize,
+ })
+ }
+
+ /// The pixels that are in both rectangles.
+ pub fn intersect(self, other: Rect) -> Rect {
+ Rect {
+ x0: self.x0.max(other.x0),
+ y0: self.y0.max(other.y0),
+ x1: self.x1.min(other.x1),
+ y1: self.y1.min(other.y1),
+ }
+ }
+}
+
+/// A triangle in screen space, ready to rasterize.
+#[derive(Clone, Copy)]
+pub(crate) struct ScreenTri {
+ /// The barycentric planes: the barycentrics at `x`, `y` are `a * x + b * y + c`.
+ pub a: Vec3,
+ pub b: Vec3,
+ pub c: Vec3,
+ /// The depth key plane, larger is nearer. The key is `1 / w` for perspective cameras
+ /// and `1 - z` for orthographic cameras. Both are affine in screen space. The plane is
+ /// relative to the first vertex at `ox`, `oy`. With absolute pixel coordinates, the
+ /// constant term cancels most of the precision. Then touching surfaces flicker.
+ pub kx: f32,
+ pub ky: f32,
+ pub k0: f32,
+ pub ox: f32,
+ pub oy: f32,
+ pub inv_w: Vec3,
+ pub v: [u32; 3],
+ pub draw: u32,
+ /// The clip plane distance of each vertex times its `1 / w`. At a pixel, the sum
+ /// weighted by the barycentrics has the sign of the distance.
+ pub clip: Option<Vec3>,
+ pub bounds: Rect,
+ /// The average `view_depth` of the vertices, for the order of blended triangles.
+ pub depth: f32,
+}
+
+impl ScreenTri {
+ #[inline]
+ pub fn key(&self, x: f32, y: f32) -> f32 {
+ self.k0 + self.kx * (x - self.ox) + self.ky * (y - self.oy)
+ }
+
+ #[inline]
+ pub fn bary(&self, x: f32, y: f32) -> Vec3 {
+ self.a * x + self.b * y + self.c
+ }
+
+ /// Whether the screen point is behind the clip plane.
+ #[inline]
+ pub fn clipped(&self, x: f32, y: f32) -> bool {
+ self.clip.is_some_and(|e| self.bary(x, y).dot(e) < 0.0)
+ }
+
+ /// The perspective correct barycentrics at a screen point.
+ #[inline]
+ pub fn perspective_bary(&self, x: f32, y: f32) -> Vec3 {
+ let p = self.bary(x, y) * self.inv_w;
+ let sum = p.element_sum();
+ if sum.abs() < 1e-20 {
+ return Vec3::splat(1.0 / 3.0);
+ }
+ p / sum
+ }
+}
+
+/// The clipping planes in clip space: `dot(plane, clip) >= 0` is inside. They are the near
+/// plane, a guard band and the far plane. The guard band keeps screen coordinates in a range
+/// where the `f32` edge functions stay exact. The GPU also clips at the far plane.
+const GUARD: f32 = 32.0;
+const PLANES: [Vec4; 6] = [
+ Vec4::new(0.0, 0.0, 1.0, 0.0),
+ Vec4::new(-1.0, 0.0, 0.0, GUARD),
+ Vec4::new(1.0, 0.0, 0.0, GUARD),
+ Vec4::new(0.0, -1.0, 0.0, GUARD),
+ Vec4::new(0.0, 1.0, 0.0, GUARD),
+ Vec4::new(0.0, 0.0, -1.0, 1.0),
+];
+
+/// Bit `i` is set when the clip space point `c` is outside `PLANES[i]`, with the guard
+/// band scaled to `guard`. With `guard` 1 the guard planes are the sides of the frustum.
+fn outcode(c: Vec4, guard: f32) -> u8 {
+ u8::from(c.z < 0.0)
+ | (u8::from(c.x > c.w * guard) << 1)
+ | (u8::from(c.x < -c.w * guard) << 2)
+ | (u8::from(c.y > c.w * guard) << 3)
+ | (u8::from(c.y < -c.w * guard) << 4)
+ | (u8::from(c.z > c.w) << 5)
+}
+
+/// A view of the scene.
+pub(crate) struct Viewport {
+ /// The size in pixels.
+ pub size: Vec2,
+ pub view_proj: Mat4,
+ pub ortho: bool,
+ /// The view is a mirror image (the reflection): front and back faces swap.
+ pub mirrored: bool,
+ /// Only what is in front of this plane (`xyz` normal, `w` offset) is drawn. The rest
+ /// of a reflection is behind the mirror.
+ pub clip_plane: Option<Vec4>,
+}
+
+/// Projects and clips the triangles of the draws that pass `filter`. Returns the screen
+/// triangles of the opaque draws and of the blended draws. Back faces are culled for the
+/// side of each material. Clipping adds vertices to `world.streams`.
+pub(crate) fn setup_triangles(
+ world: &mut World,
+ viewport: &Viewport,
+ filter: impl Fn(&Draw) -> bool,
+) -> (Vec<ScreenTri>, Vec<ScreenTri>) {
+ let streams = &mut world.streams;
+ let mut clip: Vec<Vec4> = streams
+ .pos
+ .iter()
+ .map(|p| viewport.view_proj * p.extend(1.0))
+ .collect();
+ let mut opaque = Vec::with_capacity(world.tris.len());
+ let mut blended = Vec::new();
+ for tri in &world.tris {
+ let draw = &world.draws[tri.draw as usize];
+ if !filter(draw) {
+ continue;
+ }
+ let out = if draw.material.is_blended() {
+ &mut blended
+ } else {
+ &mut opaque
+ };
+ let side = draw.material.side;
+ let c = tri.v.map(|i| clip[i as usize]);
+ // All three vertices are outside the same plane of the frustum.
+ let outside = c.map(|c| outcode(c, 1.0));
+ if outside[0] & outside[1] & outside[2] != 0 {
+ continue;
+ }
+ let codes = c.map(|c| outcode(c, GUARD));
+ let crossed = codes[0] | codes[1] | codes[2];
+ if crossed == 0 {
+ out.extend(screen_tri(tri.v, c, &streams.pos, tri.draw, side, viewport));
+ continue;
+ }
+ // Sutherland-Hodgman against the planes that the triangle crosses
+ let mut poly: Vec<u32> = tri.v.to_vec();
+ for (bit, plane) in PLANES.iter().enumerate() {
+ if crossed & (1 << bit) == 0 {
+ continue;
+ }
+ let mut next = Vec::with_capacity(poly.len() + 2);
+ for i in 0..poly.len() {
+ let a = poly[i];
+ let b = poly[(i + 1) % poly.len()];
+ let da = plane.dot(clip[a as usize]);
+ let db = plane.dot(clip[b as usize]);
+ if da >= 0.0 {
+ next.push(a);
+ }
+ if (da >= 0.0) != (db >= 0.0) {
+ let t = da / (da - db);
+ next.push(streams.lerp(a, b, t));
+ clip.push(clip[a as usize].lerp(clip[b as usize], t));
+ }
+ }
+ poly = next;
+ if poly.len() < 3 {
+ break;
+ }
+ }
+ for i in 1..poly.len().saturating_sub(1) {
+ let v = [poly[0], poly[i], poly[i + 1]];
+ let c = v.map(|i| clip[i as usize]);
+ out.extend(screen_tri(v, c, &streams.pos, tri.draw, side, viewport));
+ }
+ }
+ (opaque, blended)
+}
+
+/// The screen triangle of the vertices `v` at the clip space positions `clip`. `None` when
+/// it is culled or covers no pixel.
+fn screen_tri(
+ v: [u32; 3],
+ clip: [Vec4; 3],
+ positions: &[Vec3],
+ draw: u32,
+ side: Side,
+ vp: &Viewport,
+) -> Option<ScreenTri> {
+ let inv_w = Vec3::from_array(clip.map(|c| 1.0 / c.w));
+ let clip_plane = vp.clip_plane.map(|plane| {
+ Vec3::from_array(
+ [0, 1, 2]
+ .map(|i| (plane.truncate().dot(positions[v[i] as usize]) + plane.w) * inv_w[i]),
+ )
+ });
+ let p = [0, 1, 2].map(|i| {
+ let ndc = Vec2::new(clip[i].x, clip[i].y) * inv_w[i];
+ Vec2::new(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5) * vp.size
+ });
+ let key = if vp.ortho {
+ Vec3::ONE - Vec3::new(clip[0].z, clip[1].z, clip[2].z) * inv_w
+ } else {
+ inv_w
+ };
+ let area2 = (p[1] - p[0]).perp_dot(p[2] - p[0]);
+ if !area2.is_finite() || area2.abs() < 1e-9 {
+ return None;
+ }
+ // Counter-clockwise in the world (y up) is clockwise on the screen (y down). A mirror
+ // swaps the two.
+ let back_facing = (area2 > 0.0) != vp.mirrored;
+ match side {
+ Side::Front if back_facing => return None,
+ Side::Back if !back_facing => return None,
+ _ => {}
+ }
+ let bounds = Rect::covering(p[0].min(p[1]).min(p[2]), p[0].max(p[1]).max(p[2]), vp.size)?;
+ // Barycentric `i` is the area to the edge from vertex `i + 1` to `i + 2`, over the
+ // triangle area.
+ let inv_area = 1.0 / area2;
+ let (mut a, mut b, mut c) = (Vec3::ZERO, Vec3::ZERO, Vec3::ZERO);
+ for i in 0..3 {
+ let (j, k) = (p[(i + 1) % 3], p[(i + 2) % 3]);
+ let edge = k - j;
+ a[i] = -edge.y * inv_area;
+ b[i] = edge.x * inv_area;
+ c[i] = j.perp_dot(edge) * inv_area;
+ }
+ Some(ScreenTri {
+ a,
+ b,
+ c,
+ // The barycentric slopes add up to zero, so the differences to vertex 0 are enough.
+ kx: a.y * (key.y - key.x) + a.z * (key.z - key.x),
+ ky: b.y * (key.y - key.x) + b.z * (key.z - key.x),
+ k0: key.x,
+ ox: p[0].x,
+ oy: p[0].y,
+ inv_w,
+ v,
+ draw,
+ clip: clip_plane,
+ bounds,
+ depth: view_depth(vp, (clip[0] + clip[1] + clip[2]) / 3.0),
+ })
+}
+
+/// A number that grows with the view distance of a clip space point, to order blended items
+/// from back to front. It is `w` for perspective cameras. For orthographic cameras `w` is 1
+/// and `z` grows with the distance.
+fn view_depth(vp: &Viewport, clip: Vec4) -> f32 {
+ if vp.ortho { clip.z } else { clip.w }
+}
+
+/// A particle projected to the screen: a round blob.
+pub(crate) struct ScreenSprite {
+ pub center: Vec2,
+ /// The depth key, larger is nearer.
+ pub z: f32,
+ pub radius: f32,
+ /// The color times the opacity.
+ pub color: Vec3,
+ /// The part of the pixel that a blended sprite covers at its center.
+ pub opacity: f32,
+ pub additive: bool,
+ pub bounds: Rect,
+ /// The `view_depth`, for the order of blended particles.
+ pub depth: f32,
+}
+
+/// Projects the particles to the screen of `vp`.
+pub(crate) fn setup_sprites(
+ sprites: &[WorldSprite],
+ camera: &Camera,
+ vp: &Viewport,
+) -> Vec<ScreenSprite> {
+ // The screen position, the depth key and the clip space point. `None` in front of the
+ // near plane (`z < 0`, also for orthographic cameras) or beyond the far plane, where the
+ // GPU clips the particle.
+ let project = |p: Vec3| -> Option<(Vec2, f32, Vec4)> {
+ let c = vp.view_proj * p.extend(1.0);
+ if c.w <= 0.0 || c.z < 0.0 || c.z > c.w {
+ return None;
+ }
+ let screen = Vec2::new(c.x / c.w * 0.5 + 0.5, 0.5 - c.y / c.w * 0.5) * vp.size;
+ let key = if vp.ortho { 1.0 - c.z / c.w } else { 1.0 / c.w };
+ Some((screen, key, c))
+ };
+ // pixels per world unit, at a distance of 1 for perspective cameras
+ let focal = match camera.ortho_height {
+ Some(h) => vp.size.y / h,
+ None => vp.size.y / (2.0 * (camera.fov.to_radians() * 0.5).tan()),
+ };
+ let project_sprite = |s: &WorldSprite| {
+ let (center, z, clip) = project(s.position)?;
+ let radius = if camera.ortho_height.is_some() {
+ s.size * focal
+ } else {
+ s.size * focal / clip.w
+ };
+ // Sprites smaller than a pixel get a radius of 0.6 pixels and keep their energy.
+ let drawn = radius.max(0.6);
+ let energy = (radius / drawn).powi(2);
+ let opacity = s.opacity * energy;
+ if opacity <= 1e-5 {
+ return None;
+ }
+ Some(ScreenSprite {
+ center,
+ z,
+ radius: drawn,
+ color: s.color * energy,
+ opacity,
+ additive: s.additive,
+ bounds: Rect::covering(center - drawn, center + drawn, vp.size)?,
+ depth: view_depth(vp, clip),
+ })
+ };
+ sprites.iter().filter_map(project_sprite).collect()
+}
diff --git a/fframes-three-d/src/render/raster.rs b/fframes-three-d/src/render/raster.rs
new file mode 100644
index 00000000..ae23f6f0
--- /dev/null
+++ b/fframes-three-d/src/render/raster.rs
@@ -0,0 +1,404 @@
+//! Tiled rasterization with 4x multisampling.
+//!
+//! The screen is split into tiles of 32x32 pixels that render in parallel. Each tile first
+//! rasterizes the opaque triangles into a visibility buffer: the nearest triangle of each
+//! sample. Then it shades each visible triangle once per pixel, at the centroid of the
+//! samples that the triangle covers. Last, the blended triangles and particles blend into
+//! the samples from back to front, with a depth test against the opaque samples.
+
+use glam::{Mat4, Vec2, Vec3, Vec4};
+use rayon::prelude::*;
+
+use super::prepare::{Draw, Rect, ScreenSprite, ScreenTri, Streams};
+use super::shade::{ShadeContext, Surface, shade, uv_directions};
+use crate::Blending;
+use crate::scene::Background;
+
+/// The width and height of a tile in pixels.
+pub(crate) const TILE: usize = 32;
+/// The triangle of a sample that no opaque triangle covers.
+const NO_TRI: u32 = u32::MAX;
+
+/// Sample offsets from the pixel center: the standard D3D 4x rotated grid.
+const SAMPLES_4X: [Vec2; 4] = [
+ Vec2::new(-2.0 / 16.0, -6.0 / 16.0),
+ Vec2::new(6.0 / 16.0, -2.0 / 16.0),
+ Vec2::new(-6.0 / 16.0, 2.0 / 16.0),
+ Vec2::new(2.0 / 16.0, 6.0 / 16.0),
+];
+const SAMPLES_1X: [Vec2; 1] = [Vec2::ZERO];
+
+/// A blended triangle or particle.
+#[derive(Clone, Copy)]
+pub(crate) enum Blended<'a> {
+ Tri(&'a ScreenTri),
+ Sprite(&'a ScreenSprite),
+}
+
+impl Blended<'_> {
+ /// The view depth, for the order from back to front.
+ pub fn depth(self) -> f32 {
+ match self {
+ Blended::Tri(t) => t.depth,
+ Blended::Sprite(s) => s.depth,
+ }
+ }
+
+ fn bounds(self) -> Rect {
+ match self {
+ Blended::Tri(t) => t.bounds,
+ Blended::Sprite(s) => s.bounds,
+ }
+ }
+}
+
+/// A view that is ready to rasterize.
+pub(crate) struct Frame<'a> {
+ pub width: usize,
+ pub height: usize,
+ pub streams: &'a Streams,
+ pub draws: &'a [Draw<'a>],
+ pub opaque: &'a [ScreenTri],
+ /// The blended triangles and particles, from back to front.
+ pub blended: &'a [Blended<'a>],
+ pub shade: &'a ShadeContext<'a>,
+ /// Clip space to world space, for the rays of the environment background.
+ pub inverse_view_proj: Mat4,
+ pub multisample: bool,
+}
+
+/// Renders the frame into premultiplied linear HDR, `width * height` pixels. Also returns
+/// the depth key of the nearest opaque surface of each pixel, 0 where there is none.
+pub(crate) fn rasterize(frame: &Frame) -> (Vec<Vec4>, Vec<f32>) {
+ let (w, h) = (frame.width, frame.height);
+ let tiles_x = w.div_ceil(TILE);
+ let tiles = tiles_x * h.div_ceil(TILE);
+ let opaque_bins = bin(frame.opaque.iter().map(|t| t.bounds), tiles_x, tiles);
+ let blended_bins = bin(frame.blended.iter().map(|b| b.bounds()), tiles_x, tiles);
+
+ let mut out = vec![Vec4::ZERO; w * h];
+ let mut depth_out = vec![0.0f32; w * h];
+ let target = SharedMut::new(&mut out);
+ let depth_target = SharedMut::new(&mut depth_out);
+ (0..tiles).into_par_iter().for_each(|tile| {
+ let (x0, y0) = (tile % tiles_x * TILE, tile / tiles_x * TILE);
+ let rect = Rect {
+ x0,
+ y0,
+ x1: (x0 + TILE).min(w),
+ y1: (y0 + TILE).min(h),
+ };
+ render_tile(
+ frame,
+ &opaque_bins[tile],
+ &blended_bins[tile],
+ rect,
+ |x, y, color, depth| {
+ // SAFETY: the tiles do not overlap, so only one tile writes each pixel
+ unsafe {
+ target.write(y * w + x, color);
+ depth_target.write(y * w + x, depth);
+ }
+ },
+ );
+ });
+ (out, depth_out)
+}
+
+/// The indices of the items that touch each tile, from the pixel bounds of the items.
+fn bin(bounds: impl Iterator<Item = Rect>, tiles_x: usize, tiles: usize) -> Vec<Vec<u32>> {
+ let mut bins = vec![Vec::new(); tiles];
+ for (i, r) in bounds.enumerate() {
+ for ty in r.y0 / TILE..r.y1.div_ceil(TILE) {
+ for tx in r.x0 / TILE..r.x1.div_ceil(TILE) {
+ bins[ty * tiles_x + tx].push(i as u32);
+ }
+ }
+ }
+ bins
+}
+
+/// Whether the barycentrics `l` are in the triangle, edges included.
+#[inline]
+fn inside(l: Vec3) -> bool {
+ l.cmpge(Vec3::ZERO).all()
+}
+
+/// Renders the pixels of `tile`. `opaque` and `blended` hold the indices of the items that
+/// touch the tile. `write` stores the color and the depth key of a pixel.
+fn render_tile(
+ frame: &Frame,
+ opaque: &[u32],
+ blended: &[u32],
+ tile: Rect,
+ mut write: impl FnMut(usize, usize, Vec4, f32),
+) {
+ let samples: &[Vec2] = if frame.multisample {
+ &SAMPLES_4X
+ } else {
+ &SAMPLES_1X
+ };
+ let ns = samples.len();
+ let tw = tile.x1 - tile.x0;
+ let th = tile.y1 - tile.y0;
+ // the index of the first sample of a pixel
+ let first_sample = |x: usize, y: usize| ((y - tile.y0) * tw + x - tile.x0) * ns;
+ // The depth key (larger is nearer, 0 is the far plane) and the triangle of each sample.
+ let mut depth = vec![0.0f32; tw * th * ns];
+ let mut ids = vec![NO_TRI; tw * th * ns];
+
+ // Visibility: the nearest opaque triangle of each sample.
+ for &ti in opaque {
+ let t = &frame.opaque[ti as usize];
+ let r = t.bounds.intersect(tile);
+ // the steps of the barycentrics and the depth key from the pixel center to the samples
+ let mut dl = [Vec3::ZERO; 4];
+ let mut dz = [0.0f32; 4];
+ for (s, o) in samples.iter().enumerate() {
+ dl[s] = t.a * o.x + t.b * o.y;
+ dz[s] = t.kx * o.x + t.ky * o.y;
+ }
+ for y in r.y0..r.y1 {
+ let cy = y as f32 + 0.5;
+ for x in r.x0..r.x1 {
+ let cx = x as f32 + 0.5;
+ if t.clipped(cx, cy) {
+ continue;
+ }
+ let l = t.bary(cx, cy);
+ let z = t.key(cx, cy);
+ let base = first_sample(x, y);
+ for s in 0..ns {
+ if inside(l + dl[s]) {
+ let zs = z + dz[s];
+ if zs > depth[base + s] {
+ depth[base + s] = zs;
+ ids[base + s] = ti;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Resolve: shade each triangle of a pixel once and give its color to its samples.
+ let mut colors = vec![Vec4::ZERO; tw * th * ns];
+ for y in tile.y0..tile.y1 {
+ for x in tile.x0..tile.x1 {
+ let base = first_sample(x, y);
+ let px = &ids[base..base + ns];
+ let mut background_color = None;
+ for (s, &id) in px.iter().enumerate() {
+ if id == NO_TRI {
+ colors[base + s] =
+ *background_color.get_or_insert_with(|| background(frame, x, y));
+ continue;
+ }
+ // an earlier sample of the same triangle shaded it already
+ if px[..s].contains(&id) {
+ continue;
+ }
+ let mut centroid = Vec2::ZERO;
+ let mut count = 0;
+ for (k, &other) in px.iter().enumerate().skip(s) {
+ if other == id {
+ centroid += samples[k];
+ count += 1;
+ }
+ }
+ let at = Vec2::new(x as f32 + 0.5, y as f32 + 0.5) + centroid / count as f32;
+ let color = shade_tri(frame, &frame.opaque[id as usize], at);
+ for (k, &other) in px.iter().enumerate().skip(s) {
+ if other == id {
+ colors[base + k] = color;
+ }
+ }
+ }
+ }
+ }
+
+ // Blended triangles and particles, from back to front, blended into each sample.
+ for &bi in blended {
+ match frame.blended[bi as usize] {
+ Blended::Tri(t) => {
+ let additive = frame.draws[t.draw as usize].material.blending == Blending::Additive;
+ let r = t.bounds.intersect(tile);
+ for y in r.y0..r.y1 {
+ for x in r.x0..r.x1 {
+ let base = first_sample(x, y);
+ let center = Vec2::new(x as f32 + 0.5, y as f32 + 0.5);
+ if t.clipped(center.x, center.y) {
+ continue;
+ }
+ let mut centroid = Vec2::ZERO;
+ let mut mask = 0u8;
+ for (s, o) in samples.iter().enumerate() {
+ let q = center + *o;
+ if inside(t.bary(q.x, q.y)) && t.key(q.x, q.y) > depth[base + s] {
+ centroid += *o;
+ mask |= 1 << s;
+ }
+ }
+ if mask == 0 {
+ continue;
+ }
+ let src = shade_tri(frame, t, center + centroid / mask.count_ones() as f32);
+ for s in 0..ns {
+ if mask & (1 << s) != 0 {
+ colors[base + s] = blend(colors[base + s], src, additive);
+ }
+ }
+ }
+ }
+ }
+ Blended::Sprite(s) => {
+ let r = s.bounds.intersect(tile);
+ for y in r.y0..r.y1 {
+ for x in r.x0..r.x1 {
+ let base = first_sample(x, y);
+ let d = Vec2::new(x as f32 + 0.5, y as f32 + 0.5).distance(s.center);
+ if d >= s.radius + 0.5 {
+ continue;
+ }
+ // a soft core with an antialiased edge
+ let r = s.radius;
+ let falloff = 1.0 - ((d - r * 0.3) / (r * 0.7 + 0.5)).clamp(0.0, 1.0);
+ let a = falloff * falloff;
+ let src =
+ (s.color * a).extend(if s.additive { 0.0 } else { a * s.opacity });
+ for k in 0..ns {
+ if s.z > depth[base + k] {
+ colors[base + k] = blend(colors[base + k], src, s.additive);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ let weight = 1.0 / ns as f32;
+ for y in tile.y0..tile.y1 {
+ for x in tile.x0..tile.x1 {
+ let base = first_sample(x, y);
+ let sum: Vec4 = colors[base..base + ns].iter().copied().sum();
+ let nearest = depth[base..base + ns].iter().copied().fold(0.0, f32::max);
+ write(x, y, sum * weight, nearest);
+ }
+ }
+}
+
+/// Blends `src` over `dst`. Additive light adds its color and leaves the coverage.
+#[inline]
+fn blend(dst: Vec4, src: Vec4, additive: bool) -> Vec4 {
+ if additive {
+ (dst.truncate() + src.truncate()).extend(dst.w)
+ } else {
+ src + dst * (1.0 - src.w)
+ }
+}
+
+/// Shades the triangle `t` at the screen point `at`.
+fn shade_tri(frame: &Frame, t: &ScreenTri, at: Vec2) -> Vec4 {
+ let b = t.perspective_bary(at.x, at.y);
+ // the next pixel right and down, for the derivatives of the normal and the UV (as the
+ // GPU computes them)
+ let b_right = t.perspective_bary(at.x + 1.0, at.y);
+ let b_down = t.perspective_bary(at.x, at.y + 1.0);
+ let s = frame.streams;
+ let [i0, i1, i2] = t.v.map(|v| v as usize);
+ let position = s.pos[i0] * b.x + s.pos[i1] * b.y + s.pos[i2] * b.z;
+ let normal_at =
+ |b: Vec3| (s.nrm[i0] * b.x + s.nrm[i1] * b.y + s.nrm[i2] * b.z).normalize_or(Vec3::Y);
+ let normal = normal_at(b);
+ let right = normal_at(b_right) - normal;
+ let down = normal_at(b_down) - normal;
+ let cross = (s.pos[i1] - s.pos[i0]).cross(s.pos[i2] - s.pos[i0]);
+ let draw = &frame.draws[t.draw as usize];
+ let uv_at = |b: Vec3| s.uv[i0] * b.x + s.uv[i1] * b.y + s.uv[i2] * b.z;
+ let (uv, uv_dx, uv_dy) = if draw.has_uv {
+ let uv = uv_at(b);
+ (uv, uv_at(b_right) - uv, uv_at(b_down) - uv)
+ } else {
+ (Vec2::ZERO, Vec2::ZERO, Vec2::ZERO)
+ };
+ let (dpdu, dpdv) = if draw.has_uv
+ && let Some(normal_map) = &draw.material.normal_map
+ {
+ // the directions on the normal map, which a negative repeat mirrors
+ uv_directions(
+ s.pos[i1] - s.pos[i0],
+ s.pos[i2] - s.pos[i0],
+ (s.uv[i1] - s.uv[i0]) * normal_map.repeat,
+ (s.uv[i2] - s.uv[i0]) * normal_map.repeat,
+ )
+ } else {
+ (Vec3::ZERO, Vec3::ZERO)
+ };
+ let surface = Surface {
+ position,
+ normal,
+ face_normal: cross.normalize_or(normal),
+ uv,
+ color: if draw.has_color {
+ s.col[i0] * b.x + s.col[i1] * b.y + s.col[i2] * b.z
+ } else {
+ Vec4::ONE
+ },
+ uv_dx,
+ uv_dy,
+ dpdu,
+ dpdv,
+ normal_variation: right.length_squared() + down.length_squared(),
+ screen: Vec2::new(at.x.floor() + 0.5, at.y.floor() + 0.5),
+ };
+ shade(frame.shade, draw, &surface)
+}
+
+/// The background of the pixel `x`, `y`.
+fn background(frame: &Frame, x: usize, y: usize) -> Vec4 {
+ match frame.shade.background {
+ Background::Transparent => Vec4::ZERO,
+ Background::Color(c) => c.0.extend(1.0),
+ Background::Environment { blur } => {
+ let dir = ray(frame, x as f32 + 0.5, y as f32 + 0.5);
+ frame.shade.env_radiance(dir, *blur).extend(1.0)
+ }
+ }
+}
+
+/// The world direction of the ray through the screen point `x`, `y`.
+///
+/// Do not inline it. When it is inlined, the compiler computes the ray for every pixel, also
+/// for the other backgrounds. With a transparent background, the tiles then executed 17%
+/// more instructions.
+#[inline(never)]
+fn ray(frame: &Frame, x: f32, y: f32) -> Vec3 {
+ let ndc_x = x / frame.width as f32 * 2.0 - 1.0;
+ let ndc_y = 1.0 - y / frame.height as f32 * 2.0;
+ let inverse = frame.inverse_view_proj;
+ let near = inverse.project_point3(Vec3::new(ndc_x, ndc_y, 0.0));
+ let far = inverse.project_point3(Vec3::new(ndc_x, ndc_y, 1.0));
+ (far - near).normalize_or(Vec3::NEG_Z)
+}
+
+/// A pointer into a buffer that several threads write at the same time. Each thread must
+/// write a different set of indices.
+#[derive(Clone, Copy)]
+pub(crate) struct SharedMut<T>(*mut T);
+
+unsafe impl<T: Send> Send for SharedMut<T> {}
+unsafe impl<T: Send> Sync for SharedMut<T> {}
+
+impl<T> SharedMut<T> {
+ pub(crate) fn new(data: &mut [T]) -> Self {
+ Self(data.as_mut_ptr())
+ }
+
+ /// # Safety
+ /// `index` must be in bounds. No other thread may access `index` at the same time.
+ #[inline]
+ pub(crate) unsafe fn write(self, index: usize, value: T) {
+ unsafe { self.0.add(index).write(value) }
+ }
+}
diff --git a/fframes-three-d/src/render/reflection.rs b/fframes-three-d/src/render/reflection.rs
new file mode 100644
index 00000000..e4c87bdf
--- /dev/null
+++ b/fframes-three-d/src/render/reflection.rs
@@ -0,0 +1,60 @@
+//! The scene mirrored in its [`crate::Reflector`]. The surfaces on the reflector's plane
+//! sample it, blurred by their roughness.
+
+use glam::{Vec2, Vec4};
+
+use super::post::Image;
+
+/// The largest number of levels. The last level is 1/32 of the size of the first.
+pub(crate) const MAX_LEVELS: usize = 6;
+
+/// The number of levels of an image of this size. The size halves from level to level
+/// while both sides are larger than 8 pixels.
+pub(crate) fn level_count(width: usize, height: usize) -> usize {
+ let (mut w, mut h, mut levels) = (width, height, 1);
+ while levels < MAX_LEVELS && w > 8 && h > 8 {
+ w = (w / 2).max(1);
+ h = (h / 2).max(1);
+ levels += 1;
+ }
+ levels
+}
+
+/// The level for a roughness: the sharpest level for mirrors, the last level for rough
+/// surfaces.
+pub(crate) fn level_of(roughness: f32, levels: usize) -> f32 {
+ let last = (levels - 1) as f32;
+ (roughness.clamp(0.0, 1.0).sqrt() * last).min(last)
+}
+
+/// The mirrored frame and its blurred levels.
+pub(crate) struct ReflectionMap {
+ levels: Vec<Image>,
+}
+
+impl ReflectionMap {
+ /// Makes the levels from the mirrored frame: premultiplied color, coverage in `w`.
+ pub(crate) fn new(width: usize, height: usize, data: Vec<Vec4>) -> Self {
+ let frame = Image {
+ width,
+ height,
+ data,
+ };
+ Self {
+ levels: frame.mip_chain(),
+ }
+ }
+
+ /// Premultiplied color and coverage at `uv` (`0..1` over the frame), blurred for
+ /// `roughness`.
+ pub(crate) fn sample(&self, uv: Vec2, roughness: f32) -> Vec4 {
+ let lod = level_of(roughness, self.levels.len());
+ let l0 = lod.floor() as usize;
+ let l1 = (l0 + 1).min(self.levels.len() - 1);
+ let a = self.levels[l0].sample(uv.x, uv.y);
+ if l1 == l0 {
+ return a;
+ }
+ a.lerp(self.levels[l1].sample(uv.x, uv.y), lod - l0 as f32)
+ }
+}
diff --git a/fframes-three-d/src/render/shade.rs b/fframes-three-d/src/render/shade.rs
new file mode 100644
index 00000000..a97de5fb
--- /dev/null
+++ b/fframes-three-d/src/render/shade.rs
@@ -0,0 +1,372 @@
+//! Physically based shading of one surface point.
+
+use std::f32::consts::PI;
+
+use glam::{Vec2, Vec3, Vec4};
+
+use super::prepare::{Draw, LightKind, Lights};
+use super::reflection::ReflectionMap;
+use super::shadow::ShadowMap;
+use crate::material::Shading;
+use crate::math::smoothstep;
+use crate::scene::{Background, Fog};
+use crate::{Blending, Environment};
+
+/// What the shading of one view needs: the lights, the environment and the camera.
+pub(crate) struct ShadeContext<'a> {
+ pub lights: &'a Lights,
+ /// The shadow map of each of [`Lights::shadow_casters`], `None` where nothing casts a
+ /// shadow.
+ pub shadows: &'a [Option<ShadowMap>],
+ pub environment: &'a Environment,
+ /// The radiance of the studio as a panorama, see [`crate::Environment::baked`].
+ pub baked: Option<&'a crate::EnvironmentMap>,
+ pub fog: Option<Fog>,
+ pub background: &'a Background,
+ pub camera_position: Vec3,
+ /// The view direction of an orthographic camera.
+ pub ortho_forward: Option<Vec3>,
+ /// The scene mirrored in its reflector, see [`crate::Reflector`].
+ pub reflection: Option<&'a ReflectionMap>,
+ /// The size of the view in pixels. The reflection has the same alignment.
+ pub viewport: Vec2,
+}
+
+impl ShadeContext<'_> {
+ /// The shadow map at `index` in [`ShadeContext::shadows`].
+ fn shadow(&self, index: Option<usize>) -> Option<&ShadowMap> {
+ self.shadows.get(index?)?.as_ref()
+ }
+
+ /// The light that arrives from `dir`, blurred for `roughness`.
+ pub(crate) fn env_radiance(&self, dir: Vec3, roughness: f32) -> Vec3 {
+ match (self.environment, self.baked) {
+ (Environment::Studio(studio), Some(map)) => {
+ map.sample(
+ crate::environment::rotate_y(dir, -studio.rotation),
+ roughness,
+ ) * studio.intensity
+ }
+ (environment, _) => environment.radiance(dir, roughness),
+ }
+ }
+}
+
+/// A point on a triangle, interpolated from its vertices.
+pub(crate) struct Surface {
+ pub position: Vec3,
+ pub normal: Vec3,
+ pub face_normal: Vec3,
+ pub uv: Vec2,
+ pub color: Vec4,
+ /// The UV changes to the next pixel right and down, to filter the textures.
+ pub uv_dx: Vec2,
+ pub uv_dy: Vec2,
+ /// The directions of +U and +V on the triangle, for the normal map. Zero without one.
+ pub dpdu: Vec3,
+ pub dpdv: Vec3,
+ /// How much the smooth normal turns to the next pixel right and down: the sum of the
+ /// squared differences. The specular antialiasing uses it.
+ pub normal_variation: f32,
+ /// The center of the pixel on the view.
+ pub screen: Vec2,
+}
+
+/// The premultiplied linear color and the coverage of a surface point.
+pub(crate) fn shade(ctx: &ShadeContext, draw: &Draw, s: &Surface) -> Vec4 {
+ let m = draw.material;
+ let to_camera = ctx.camera_position - s.position;
+ let distance = to_camera.length();
+ let v = match ctx.ortho_forward {
+ Some(forward) => -forward,
+ None => to_camera / distance.max(1e-6),
+ };
+ let face = if s.face_normal.dot(v) < 0.0 {
+ -s.face_normal
+ } else {
+ s.face_normal
+ };
+ let mut n = if m.flat_shading { face } else { s.normal };
+ let sample = |map: &crate::Texture| map.sample_grad(s.uv, s.uv_dx, s.uv_dy);
+ if draw.has_uv
+ && let Some(map) = &m.normal_map
+ {
+ n = bend(n, s.dpdu, s.dpdv, sample(map), m.normal_scale);
+ }
+ // A back face, or a smooth normal that points away from the camera near a silhouette,
+ // turns around. A normal map bends the normal before, as for the front face.
+ if n.dot(face) < 0.0 {
+ n = -n;
+ }
+ let n_dot_v = n.dot(v).max(1e-4);
+
+ let mut base = m.color.0;
+ let mut alpha = m.opacity;
+ if draw.has_color {
+ base *= s.color.truncate();
+ alpha *= s.color.w;
+ }
+ if draw.has_uv
+ && let Some(map) = &m.map
+ {
+ let texel = sample(map);
+ base *= texel.truncate();
+ alpha *= texel.w;
+ }
+
+ let mut emissive = m.emissive.0 * m.emissive_intensity;
+ if draw.has_uv
+ && let Some(map) = &m.emissive_map
+ {
+ emissive *= sample(map).truncate();
+ }
+
+ let mut rgb = match m.shading {
+ Shading::Unlit => base + emissive,
+ Shading::Normals => n * 0.5 + 0.5,
+ Shading::ShadowCatcher => {
+ let mut lit = 1.0;
+ for light in &ctx.lights.direct {
+ if let LightKind::Directional { direction, shadow } = &light.kind
+ && let Some(map) = ctx.shadow(*shadow)
+ {
+ lit *= map.visibility(s.position, face, face.dot(-*direction));
+ }
+ }
+ return Vec4::new(0.0, 0.0, 0.0, (1.0 - lit) * m.opacity);
+ }
+ Shading::Standard => standard(ctx, draw, s, base, n, face, v, n_dot_v) + emissive,
+ };
+
+ if m.fog
+ && let Some(fog) = ctx.fog
+ {
+ let f = fog.factor(distance);
+ rgb = match m.blending {
+ Blending::Additive => rgb * (1.0 - f),
+ Blending::Normal => rgb.lerp(fog.color().0, f),
+ };
+ }
+
+ // As on the GPU, whose 16 bit float target would overflow to infinity.
+ let rgb = rgb.clamp(Vec3::ZERO, Vec3::splat(30000.0));
+ // An opaque surface covers its pixels whatever the alpha of its texture, as in three.js.
+ let alpha = if m.is_blended() { alpha } else { 1.0 };
+ match m.blending {
+ // additive light has no coverage
+ Blending::Additive => (rgb * alpha).extend(0.0),
+ Blending::Normal => (rgb * alpha).extend(alpha),
+ }
+}
+
+/// The normal `n` bent by the normal map `texel`. `dpdu` and `dpdv` are the directions of
+/// +U and +V. Green points up in the image, that is to -V.
+fn bend(n: Vec3, dpdu: Vec3, dpdv: Vec3, texel: Vec4, scale: f32) -> Vec3 {
+ let m = texel.truncate() * 2.0 - 1.0;
+ let t = (dpdu - n * n.dot(dpdu)).normalize_or_zero();
+ let b = (dpdv - n * n.dot(dpdv)).normalize_or_zero();
+ (t * (m.x * scale) - b * (m.y * scale) + n * m.z).normalize_or(n)
+}
+
+/// The directions of +U and +V on a triangle with the edges `e1` and `e2` and the UV edges
+/// `d1` and `d2`. Their lengths are not normalized. Mirrored UVs give mirrored directions.
+pub(crate) fn uv_directions(e1: Vec3, e2: Vec3, d1: Vec2, d2: Vec2) -> (Vec3, Vec3) {
+ let det = d1.perp_dot(d2);
+ let sign = if det == 0.0 { 0.0 } else { det.signum() };
+ (
+ (e1 * d2.y - e2 * d1.y) * sign,
+ (e2 * d1.x - e1 * d2.x) * sign,
+ )
+}
+
+/// The metal and roughness PBR color of a surface: the direct light, then the ambient
+/// light and the environment. `n` is the shading normal, `face` the normal of the
+/// triangle, `v` the direction to the camera.
+#[allow(clippy::too_many_arguments)]
+fn standard(
+ ctx: &ShadeContext,
+ draw: &Draw,
+ s: &Surface,
+ base: Vec3,
+ n: Vec3,
+ face: Vec3,
+ v: Vec3,
+ n_dot_v: f32,
+) -> Vec3 {
+ let m = draw.material;
+ let mut metalness = m.metalness;
+ let mut roughness = m.roughness;
+ if draw.has_uv
+ && let Some(map) = &m.metal_rough_map
+ {
+ let texel = map.sample_grad(s.uv, s.uv_dx, s.uv_dy);
+ roughness *= texel.y;
+ metalness *= texel.z;
+ }
+ let mut roughness = roughness.clamp(0.045, 1.0);
+ let metalness = metalness.clamp(0.0, 1.0);
+ let mut alpha = roughness * roughness;
+ let clearcoat = m.clearcoat.clamp(0.0, 1.0);
+ let mut cc_roughness = m.clearcoat_roughness;
+ let mut cc_alpha = cc_roughness.clamp(0.045, 1.0).powi(2);
+ // Specular antialiasing: a normal that turns in the pixel widens the highlight, so it
+ // does not sparkle (Kaplanyan 2016, with the constants of Filament).
+ let kernel = (0.3 * s.normal_variation).min(0.04);
+ if kernel > 0.0 {
+ alpha = (alpha * alpha + kernel).min(1.0).sqrt();
+ roughness = alpha.sqrt();
+ cc_alpha = (cc_alpha * cc_alpha + kernel).min(1.0).sqrt();
+ cc_roughness = cc_alpha.sqrt();
+ }
+ let f0 = Vec3::splat(0.04).lerp(base, metalness);
+ let diffuse = base * (1.0 - metalness);
+
+ let mut direct = Vec3::ZERO;
+ for light in &ctx.lights.direct {
+ let (l, radiance) = match &light.kind {
+ LightKind::Directional { direction, shadow } => {
+ let l = -*direction;
+ let mut radiance = light.color;
+ let n_dot_l = face.dot(l);
+ if draw.receive_shadow
+ && n_dot_l > 0.0
+ && let Some(map) = ctx.shadow(*shadow)
+ {
+ radiance *= map.visibility(s.position, face, n_dot_l);
+ }
+ (l, radiance)
+ }
+ LightKind::Point {
+ position,
+ distance,
+ decay,
+ } => {
+ let d = *position - s.position;
+ let dist = d.length();
+ (
+ d / dist.max(1e-6),
+ light.color * attenuation(dist, *distance, *decay),
+ )
+ }
+ LightKind::Spot {
+ position,
+ direction,
+ distance,
+ decay,
+ cos_outer,
+ cos_inner,
+ } => {
+ let d = *position - s.position;
+ let dist = d.length();
+ let l = d / dist.max(1e-6);
+ let cone = smoothstep(*cos_outer, *cos_inner, (-l).dot(*direction));
+ (l, light.color * attenuation(dist, *distance, *decay) * cone)
+ }
+ };
+ let n_dot_l = n.dot(l);
+ if n_dot_l <= 0.0 || radiance.max_element() <= 0.0 {
+ continue;
+ }
+ let h = (l + v).normalize_or(n);
+ let n_dot_h = n.dot(h).max(0.0);
+ let v_dot_h = v.dot(h).max(0.0);
+ let fresnel = f0 + (Vec3::ONE - f0) * (1.0 - v_dot_h).powi(5);
+ let specular = fresnel * (ggx(n_dot_h, alpha) * smith_visibility(n_dot_l, n_dot_v, alpha));
+ let mut lit = (diffuse * (Vec3::ONE - fresnel) / PI + specular) * radiance * n_dot_l;
+ if clearcoat > 0.0 {
+ let fc = (0.04 + 0.96 * (1.0 - v_dot_h).powi(5)) * clearcoat;
+ let coat = ggx(n_dot_h, cc_alpha) * smith_visibility(n_dot_l, n_dot_v, cc_alpha) * fc;
+ lit = lit * (1.0 - fc) + radiance * (coat * n_dot_l);
+ }
+ direct += lit;
+ }
+
+ // ambient and hemisphere lights (three.js divides their irradiance by pi)
+ let mut irradiance = ctx.lights.ambient / PI;
+ if let Some((sky, ground)) = ctx.lights.hemisphere {
+ irradiance += ground.lerp(sky, n.y * 0.5 + 0.5) / PI;
+ }
+ let env = ctx.environment;
+ let has_env = !matches!(env, Environment::None);
+ if has_env {
+ irradiance += env.irradiance(n) * m.env_intensity;
+ }
+ let mut indirect = diffuse * irradiance;
+ let occlusion = match &m.ao_map {
+ Some(map) if draw.has_uv => map.sample_grad(s.uv, s.uv_dx, s.uv_dy).x,
+ _ => 1.0,
+ };
+
+ if has_env {
+ let mirror = (-v).reflect(n);
+ // the main direction of a rough reflection moves to the normal
+ let r = mirror.lerp(n, alpha).normalize_or(n);
+ // reflections from below the surface are hidden
+ let horizon = (1.0 + r.dot(face)).clamp(0.0, 1.0).powi(2);
+ let (scale, bias) = env_brdf(roughness, n_dot_v);
+ let reflection = ctx.reflection.filter(|_| m.reflection > 0.0);
+ let uv = s.screen / ctx.viewport;
+ let env = ctx.env_radiance(r, roughness) * m.env_intensity;
+ let mut radiance = env * horizon;
+ if let Some(map) = reflection {
+ // the reflection of the scene over the environment, where it covers the pixel
+ let p = map.sample(uv, roughness);
+ radiance = radiance.lerp((p.truncate() + env * (1.0 - p.w)) * horizon, m.reflection);
+ }
+ indirect += radiance * (f0 * scale + Vec3::splat(bias));
+ if clearcoat > 0.0 {
+ let (cs, cb) = env_brdf(cc_roughness, n_dot_v);
+ let fc = (0.04 * cs + cb) * clearcoat;
+ let mut coat = ctx.env_radiance(mirror, cc_roughness) * m.env_intensity;
+ if let Some(map) = reflection {
+ let p = map.sample(uv, cc_roughness);
+ coat = coat.lerp(p.truncate() + coat * (1.0 - p.w), m.reflection);
+ }
+ indirect = indirect * (1.0 - fc) + coat * (horizon * fc);
+ }
+ } else {
+ // without an environment, ambient light still gives a little sheen
+ let (scale, bias) = env_brdf(roughness, n_dot_v);
+ indirect += irradiance * (f0 * scale + Vec3::splat(bias)) * 0.5;
+ }
+
+ direct + indirect * occlusion
+}
+
+/// three.js `getDistanceAttenuation`.
+pub(crate) fn attenuation(distance: f32, cutoff: f32, decay: f32) -> f32 {
+ let d = distance.max(0.01);
+ // `powf` is slow, and the physically correct decay is the common case.
+ let mut att = 1.0 / if decay == 2.0 { d * d } else { d.powf(decay) };
+ if cutoff > 0.0 {
+ let x = (1.0 - (distance / cutoff).powi(4)).clamp(0.0, 1.0);
+ att *= x * x;
+ }
+ att
+}
+
+#[inline]
+fn ggx(n_dot_h: f32, alpha: f32) -> f32 {
+ let a2 = alpha * alpha;
+ let d = n_dot_h * n_dot_h * (a2 - 1.0) + 1.0;
+ a2 / (PI * d * d)
+}
+
+/// The height correlated Smith visibility, with the 1 / (4 `NdotL` `NdotV`) term.
+#[inline]
+fn smith_visibility(n_dot_l: f32, n_dot_v: f32, alpha: f32) -> f32 {
+ let a2 = alpha * alpha;
+ let gv = n_dot_l * (n_dot_v * n_dot_v * (1.0 - a2) + a2).sqrt();
+ let gl = n_dot_v * (n_dot_l * n_dot_l * (1.0 - a2) + a2).sqrt();
+ 0.5 / (gv + gl).max(1e-6)
+}
+
+/// The analytic fit of the split sum environment BRDF (Karis, for mobile).
+#[inline]
+fn env_brdf(roughness: f32, n_dot_v: f32) -> (f32, f32) {
+ let c0 = Vec4::new(-1.0, -0.0275, -0.572, 0.022);
+ let c1 = Vec4::new(1.0, 0.0425, 1.04, -0.04);
+ let r = c0 * roughness + c1;
+ let a004 = (r.x * r.x).min((-9.28 * n_dot_v).exp2()) * r.x + r.y;
+ (a004 * -1.04 + r.z, a004 * 1.04 + r.w)
+}
diff --git a/fframes-three-d/src/render/shadow.rs b/fframes-three-d/src/render/shadow.rs
new file mode 100644
index 00000000..5bc7588a
--- /dev/null
+++ b/fframes-three-d/src/render/shadow.rs
@@ -0,0 +1,277 @@
+//! Shadow maps of directional lights. Each is an orthographic depth map around the shadow
+//! casters, read with a smooth percentage closer filter.
+
+use glam::{Mat4, Vec3};
+use rayon::prelude::*;
+
+use super::prepare::{World, WorldTri};
+use crate::Shadow;
+use crate::material::Shading;
+use crate::math::Aabb;
+
+/// The view of the light on the box that receives shadows.
+pub(crate) struct ShadowFit {
+ pub view_proj: Mat4,
+ /// The world size of one texel.
+ pub texel_world: f32,
+ /// The depth units in a world distance of one texel.
+ pub depth_per_texel: f32,
+}
+
+/// An orthographic light camera around `bounds` that looks along `direction`. The map has
+/// `size` x `size` texels.
+///
+/// The map stays still in the world while the box moves, so that shadow edges do not crawl
+/// when the box follows the camera: the light view turns about the world
+/// origin and does not move with the box, the extent grows in steps of 1/64 of a power of
+/// two, and the edges of the map are on whole texels of the world grid.
+pub(crate) fn fit(direction: Vec3, bounds: &Aabb, size: usize) -> ShadowFit {
+ let radius = (bounds.size().length() * 0.5).max(1e-3);
+ let up = if direction.y.abs() > 0.99 {
+ Vec3::Z
+ } else {
+ Vec3::Y
+ };
+ // Only a turn: light space has the world origin at its origin, so its X and Y keep the
+ // precision of the world positions.
+ let view = Mat4::look_at_rh(Vec3::ZERO, direction, up);
+ let light_bounds = bounds.transformed(&view);
+ let pad = light_bounds.size().truncate().max_element() * 0.02 + 1e-3;
+ let (min, max) = (light_bounds.min, light_bounds.max);
+ let extent = quantize_up((max.x - min.x).max(max.y - min.y) + pad * 2.0);
+ let texel_world = extent / size as f32;
+ let snap = |v: f32| (v / texel_world).floor() * texel_world;
+ let left = snap(f32::midpoint(min.x, max.x) - extent * 0.5);
+ let bottom = snap(f32::midpoint(min.y, max.y) - extent * 0.5);
+ // Casters outside explicit bounds can be between the light and the box. The depth
+ // range moves in steps too, so that the depth of a still caster does not change.
+ let depth_step = extent / 16.0;
+ let near = ((-max.z - radius * 4.0) / depth_step).floor() * depth_step;
+ let far = ((-min.z + pad) / depth_step).ceil() * depth_step;
+ let projection = Mat4::orthographic_rh(left, left + extent, bottom, bottom + extent, near, far);
+ ShadowFit {
+ view_proj: projection * view,
+ texel_world,
+ depth_per_texel: texel_world / (far - near).max(1e-6),
+ }
+}
+
+/// Rounds `v` up to a multiple of 1/64 of the power of two below it.
+fn quantize_up(v: f32) -> f32 {
+ let step = v.max(1e-6).log2().floor().exp2() / 64.0;
+ (v / step).ceil() * step
+}
+
+/// The shadow of a directional light.
+pub(crate) struct ShadowMap {
+ size: usize,
+ /// The nearest caster depth of each texel, row major.
+ depth: Vec<f32>,
+ fit: ShadowFit,
+ softness: f32,
+ strength: f32,
+ bias: f32,
+}
+
+/// The rows of the map that one task rasterizes.
+const BAND: usize = 16;
+
+impl ShadowMap {
+ /// Rasterizes the shadow casters of `world` as the light along `direction` sees them.
+ /// `None` when nothing casts a shadow.
+ pub(crate) fn build(direction: Vec3, settings: &Shadow, world: &World) -> Option<Self> {
+ let casts = |tri: &&WorldTri| {
+ let draw = &world.draws[tri.draw as usize];
+ draw.cast_shadow
+ && !draw.material.is_blended()
+ && draw.material.shading != Shading::ShadowCatcher
+ };
+ let casters = || world.tris.iter().filter(casts);
+ let bounds = settings.bounds.unwrap_or_else(|| {
+ Aabb::from_points(
+ casters().flat_map(|tri| tri.v.map(|v| world.streams.pos[v as usize])),
+ )
+ });
+ if bounds.is_empty() {
+ return None;
+ }
+
+ let size = settings.map_size.clamp(64, 8192) as usize;
+ let fit = fit(direction, &bounds, size);
+
+ // the casters in map space
+ struct MapTri {
+ x: [f32; 3],
+ y: [f32; 3],
+ z: [f32; 3],
+ y0: usize,
+ y1: usize,
+ }
+ let s = size as f32;
+ let map_tris: Vec<MapTri> = casters()
+ .filter_map(|tri| {
+ let p = tri
+ .v
+ .map(|v| fit.view_proj.project_point3(world.streams.pos[v as usize]));
+ let x = p.map(|p| (p.x * 0.5 + 0.5) * s);
+ let y = p.map(|p| (0.5 - p.y * 0.5) * s);
+ // A caster beyond the near plane, between the light and the box, still
+ // throws its shadow: its depth clamps to the near plane in each texel, as
+ // on the GPU. A caster beyond the far plane is behind every receiver.
+ let z = p.map(|p| p.z);
+ let y0 = y[0].min(y[1]).min(y[2]).floor().max(0.0) as usize;
+ let y1 = (y[0].max(y[1]).max(y[2]).ceil().max(0.0) as usize).min(size);
+ let x0 = x[0].min(x[1]).min(x[2]);
+ let x1 = x[0].max(x[1]).max(x[2]);
+ let in_depth = z.iter().any(|&z| z <= 1.0);
+ (y0 < y1 && x1 >= 0.0 && x0 < s && in_depth).then_some(MapTri { x, y, z, y0, y1 })
+ })
+ .collect();
+
+ let bands = size.div_ceil(BAND);
+ let mut bins: Vec<Vec<u32>> = vec![Vec::new(); bands];
+ for (i, t) in map_tris.iter().enumerate() {
+ for band in t.y0 / BAND..t.y1.div_ceil(BAND).min(bands) {
+ bins[band].push(i as u32);
+ }
+ }
+
+ let mut depth = vec![1.0f32; size * size];
+ depth
+ .par_chunks_mut(size * BAND)
+ .enumerate()
+ .for_each(|(band, rows)| {
+ let row0 = band * BAND;
+ for &ti in &bins[band] {
+ let t = &map_tris[ti as usize];
+ let area = (t.x[1] - t.x[0]) * (t.y[2] - t.y[0])
+ - (t.y[1] - t.y[0]) * (t.x[2] - t.x[0]);
+ if area.abs() < 1e-12 {
+ continue;
+ }
+ let inv = 1.0 / area;
+ let edge = |i: usize, px: f32, py: f32| {
+ let (j, k) = ((i + 1) % 3, (i + 2) % 3);
+ ((t.x[k] - t.x[j]) * (py - t.y[j]) - (t.y[k] - t.y[j]) * (px - t.x[j]))
+ * inv
+ };
+ let x_min = t.x[0].min(t.x[1]).min(t.x[2]);
+ let x_max = t.x[0].max(t.x[1]).max(t.x[2]);
+ for y in t.y0.max(row0)..t.y1.min(row0 + rows.len() / size) {
+ let py = y as f32 + 0.5;
+ // The texels between the points where the row crosses the edges. A thin
+ // triangle covers a small part of its bounding box. The test below
+ // decides each texel, so the span has a margin of one texel.
+ let (mut lo, mut hi) = (f32::INFINITY, f32::NEG_INFINITY);
+ for j in 0..3 {
+ let k = (j + 1) % 3;
+ let dy = t.y[k] - t.y[j];
+ let s = (py - t.y[j]) / dy;
+ if dy.abs() >= 1e-3 && (0.0..=1.0).contains(&s) {
+ let x = t.x[j] + (t.x[k] - t.x[j]) * s;
+ lo = lo.min(x);
+ hi = hi.max(x);
+ }
+ }
+ if lo > hi {
+ (lo, hi) = (x_min, x_max);
+ }
+ let x0 = (lo.max(x_min) - 1.0).floor().max(0.0) as usize;
+ let x1 = ((hi.min(x_max) + 1.0).ceil().max(0.0) as usize).min(size);
+ let row = &mut rows[(y - row0) * size..(y - row0 + 1) * size];
+ for (x, d) in row.iter_mut().enumerate().take(x1).skip(x0) {
+ let px = x as f32 + 0.5;
+ let l0 = edge(0, px, py);
+ let l1 = edge(1, px, py);
+ let l2 = 1.0 - l0 - l1;
+ if l0 >= 0.0 && l1 >= 0.0 && l2 >= 0.0 {
+ let z = (l0 * t.z[0] + l1 * t.z[1] + l2 * t.z[2]).max(0.0);
+ if z < *d {
+ *d = z;
+ }
+ }
+ }
+ }
+ }
+ });
+
+ Some(Self {
+ size,
+ depth,
+ fit,
+ softness: settings.softness.max(0.0),
+ strength: settings.strength.clamp(0.0, 1.0),
+ bias: settings.bias,
+ })
+ }
+
+ /// How much light reaches `position`: 1 when lit, `1 - strength` in full shadow. The
+ /// point moves out along `normal` against shadow acne. It moves farther where the
+ /// light grazes the surface (a small `n_dot_l`).
+ pub(crate) fn visibility(&self, position: Vec3, normal: Vec3, n_dot_l: f32) -> f32 {
+ let offset = normal * self.fit.texel_world * (1.0 + 2.0 * (1.0 - n_dot_l.clamp(0.0, 1.0)));
+ let Some((u, v, z)) = self.project(position + offset) else {
+ return 1.0;
+ };
+ let r = self.softness;
+ if r <= 0.0 {
+ return 1.0 - self.strength * (1.0 - self.tap(u, v, z));
+ }
+ // The corners first: fully lit and fully shadowed areas need only these four taps.
+ let corners = self.tap(u - r, v - r, z)
+ + self.tap(u + r, v - r, z)
+ + self.tap(u - r, v + r, z)
+ + self.tap(u + r, v + r, z);
+ let lit = if corners == 0.0 || corners == 4.0 {
+ corners / 4.0
+ } else {
+ let mut sum = 0.0;
+ for j in 0..4 {
+ for i in 0..4 {
+ let du = (i as f32 - 1.5) / 1.5 * r;
+ let dv = (j as f32 - 1.5) / 1.5 * r;
+ sum += self.tap(u + du, v + dv, z);
+ }
+ }
+ sum / 16.0
+ };
+ 1.0 - self.strength * (1.0 - lit)
+ }
+
+ /// The texel position and the biased depth of `position` in the map. `None` outside
+ /// the map.
+ fn project(&self, position: Vec3) -> Option<(f32, f32, f32)> {
+ let p = self.fit.view_proj.project_point3(position);
+ let s = self.size as f32;
+ let u = (p.x * 0.5 + 0.5) * s - 0.5;
+ let v = (0.5 - p.y * 0.5) * s - 0.5;
+ ((0.0..s).contains(&u) && (0.0..s).contains(&v) && p.z <= 1.0).then_some((
+ u,
+ v,
+ p.z - self.bias * self.fit.depth_per_texel,
+ ))
+ }
+
+ /// The bilinear depth comparison at the texel position `u`, `v`: 1 when `z` is lit.
+ #[inline]
+ fn tap(&self, u: f32, v: f32, z: f32) -> f32 {
+ let max = self.size as i32 - 1;
+ let x0 = u.floor();
+ let y0 = v.floor();
+ let (fx, fy) = (u - x0, v - y0);
+ let xi = (x0 as i32).clamp(0, max) as usize;
+ let yi = (y0 as i32).clamp(0, max) as usize;
+ let xi1 = (x0 as i32 + 1).clamp(0, max) as usize;
+ let yi1 = (y0 as i32 + 1).clamp(0, max) as usize;
+ let lit = |x: usize, y: usize| {
+ if z <= self.depth[y * self.size + x] {
+ 1.0
+ } else {
+ 0.0
+ }
+ };
+ let top = lit(xi, yi) * (1.0 - fx) + lit(xi1, yi) * fx;
+ let bottom = lit(xi, yi1) * (1.0 - fx) + lit(xi1, yi1) * fx;
+ top * (1.0 - fy) + bottom * fy
+ }
+}
diff --git a/fframes-three-d/src/scene.rs b/fframes-three-d/src/scene.rs
new file mode 100644
index 00000000..f8b0ad09
--- /dev/null
+++ b/fframes-three-d/src/scene.rs
@@ -0,0 +1,702 @@
+use std::ops::{Index, IndexMut};
+use std::sync::Arc;
+
+use glam::{Mat4, Quat, Vec3, Vec4};
+
+use crate::math::{Aabb, euler};
+use crate::{Blending, Environment, Geometry, Light, Material, Rgb};
+
+/// The handle of a node in a [`Scene`].
+///
+/// An id stays valid in its scene and in all clones of the scene. Keep the ids of the
+/// animated parts next to a template scene. Use them on the clone of each frame.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub struct NodeId(pub u32);
+
+impl NodeId {
+ /// The position of the node in the node list of its scene.
+ pub fn index(self) -> usize {
+ self.0 as usize
+ }
+}
+
+/// The content of a [`Node`].
+#[derive(Debug, Clone)]
+pub enum Object {
+ /// A transform only, three.js `Group` / `Object3D`.
+ Group,
+ /// A geometry with a material, three.js `Mesh`.
+ Mesh(Mesh),
+ /// A light source.
+ Light(Light),
+ /// Glowing sprites, three.js `Points`.
+ Particles(Particles),
+}
+
+/// A geometry drawn with a material, three.js `Mesh`.
+#[derive(Debug, Clone)]
+pub struct Mesh {
+ /// The shape. All clones of a scene share it.
+ pub geometry: Arc<Geometry>,
+ pub material: Material,
+ /// Whether the mesh casts shadows. Default `true`.
+ pub cast_shadow: bool,
+ /// Whether shadows fall on the mesh. Default `true`.
+ pub receive_shadow: bool,
+ /// The bones of a skinned mesh (glTF skins).
+ pub skin: Option<Skin>,
+ /// The weights of the morph targets of the geometry, in target order.
+ pub morph_weights: Vec<f32>,
+ /// Copies of the mesh, see [`Instances`]. `None` draws the mesh once.
+ pub instances: Option<Arc<Instances>>,
+}
+
+impl Mesh {
+ /// The bounds of the mesh and all its copies, with the world matrix `m` of the node.
+ pub fn bounds(&self, m: &Mat4) -> Aabb {
+ let local = self.geometry.bounds();
+ match &self.instances {
+ Some(instances) => instances.transforms.iter().fold(Aabb::EMPTY, |aabb, t| {
+ aabb.union(local.transformed(&(*m * *t)))
+ }),
+ None => local.transformed(m),
+ }
+ }
+}
+
+/// Copies of one mesh in one draw, three.js `InstancedMesh`: a forest, a crowd, a factory of
+/// machines. The copies share the geometry and the material.
+///
+/// ```rust
+/// use fframes::three_d::*;
+///
+/// let posts = Instances::new((0..100).map(|i| Mat4::from_translation(vec3(i as f32, 0.0, 0.0))));
+/// let fence = Node::instanced(Geometry::cuboid(0.1, 1.0, 0.1), Material::standard(0x806040), posts);
+/// ```
+///
+/// The copies are rigid. A skinned or morphed mesh ignores them.
+#[derive(Debug, Clone, Default)]
+pub struct Instances {
+ /// The transform of each copy, in the space of the node. A transform must not mirror.
+ pub transforms: Vec<Mat4>,
+ /// Empty, or one color for each copy. It multiplies the color of the material, like a
+ /// vertex color (three.js `instanceColor`).
+ pub colors: Vec<Rgb>,
+}
+
+impl Instances {
+ /// Copies at `transforms`, with no colors.
+ pub fn new(transforms: impl IntoIterator<Item = Mat4>) -> Self {
+ Self {
+ transforms: transforms.into_iter().collect(),
+ colors: Vec::new(),
+ }
+ }
+
+ /// One color for each copy, in the order of the transforms.
+ pub fn colors(mut self, colors: impl IntoIterator<Item = Rgb>) -> Self {
+ self.colors = colors.into_iter().collect();
+ self
+ }
+
+ /// The color of copy `i`, white without colors.
+ pub(crate) fn color(&self, i: usize) -> Vec4 {
+ self.colors.get(i).map_or(Vec4::ONE, |c| c.0.extend(1.0))
+ }
+}
+
+/// The joints of a skinned mesh.
+///
+/// A vertex moves by the world matrices of its joints times their inverse bind matrices.
+/// The transform of the mesh node has no effect, as in glTF.
+#[derive(Debug, Clone)]
+pub struct Skin {
+ pub joints: Vec<NodeId>,
+ /// One matrix for each joint, from mesh space to the rest space of the joint.
+ pub inverse_bind_matrices: Arc<Vec<Mat4>>,
+}
+
+/// Round sprites that emit light, three.js `Points` with `sizeAttenuation`: sparks, embers,
+/// dust, stars.
+///
+/// The renderer draws them after the opaque geometry, and the geometry hides them. The
+/// positions are in the space of the node.
+#[derive(Debug, Clone, Default)]
+pub struct Particles {
+ pub items: Vec<Particle>,
+ pub blending: Blending,
+}
+
+/// One sprite of [`Particles`].
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct Particle {
+ pub position: Vec3,
+ /// The radius in meters. The renderer draws at least about half a pixel.
+ pub size: f32,
+ /// The emitted light. Values above 1 bloom.
+ pub color: Rgb,
+ /// The opacity, `0..1`. Default 1.
+ pub opacity: f32,
+}
+
+impl Particle {
+ /// A round dot at `position` with the radius `size` in meters.
+ pub fn new(position: Vec3, size: f32, color: impl Into<Rgb>) -> Self {
+ Self {
+ position,
+ size,
+ color: color.into(),
+ opacity: 1.0,
+ }
+ }
+
+ /// Sets the opacity, `0..1`.
+ pub fn opacity(mut self, opacity: f32) -> Self {
+ self.opacity = opacity;
+ self
+ }
+}
+
+/// An object in a [`Scene`], three.js `Object3D`.
+///
+/// A node has a transform relative to its parent and an [`Object`] to draw. Build it with
+/// chained methods:
+///
+/// ```rust
+/// use fframes::three_d::{Geometry, Material, Node, deg};
+///
+/// let wheel = Node::mesh(Geometry::cylinder(0.4, 0.4, 0.2, 32), Material::standard(0x222222))
+/// .at(1.0, 0.4, 0.8)
+/// .rotate_x(deg(90.0))
+/// .named("wheel_fl");
+/// ```
+#[derive(Debug, Clone)]
+pub struct Node {
+ /// The name for [`Scene::find`]. glTF models keep the names from the file.
+ pub name: Option<Arc<str>>,
+ /// The position relative to the parent, in meters.
+ pub position: Vec3,
+ /// The rotation relative to the parent.
+ pub rotation: Quat,
+ /// The scale relative to the parent. Default 1.
+ pub scale: Vec3,
+ /// An invisible node hides its whole subtree. Default `true`.
+ pub visible: bool,
+ pub object: Object,
+ pub(crate) parent: Option<NodeId>,
+ pub(crate) children: Vec<NodeId>,
+}
+
+impl Node {
+ /// A node at the origin with no rotation and a scale of 1.
+ pub fn new(object: Object) -> Self {
+ Self {
+ name: None,
+ position: Vec3::ZERO,
+ rotation: Quat::IDENTITY,
+ scale: Vec3::ONE,
+ visible: true,
+ object,
+ parent: None,
+ children: Vec::new(),
+ }
+ }
+
+ /// An empty transform that groups and pivots its children, three.js `Group`.
+ pub fn group() -> Self {
+ Self::new(Object::Group)
+ }
+
+ /// A mesh that casts and receives shadows, three.js `Mesh`.
+ pub fn mesh(geometry: impl Into<Arc<Geometry>>, material: Material) -> Self {
+ Self::new(Object::Mesh(Mesh {
+ geometry: geometry.into(),
+ material,
+ cast_shadow: true,
+ receive_shadow: true,
+ skin: None,
+ morph_weights: Vec::new(),
+ instances: None,
+ }))
+ }
+
+ /// Copies of a mesh in one draw, see [`Instances`].
+ pub fn instanced(
+ geometry: impl Into<Arc<Geometry>>,
+ material: Material,
+ instances: impl Into<Arc<Instances>>,
+ ) -> Self {
+ let mut node = Self::mesh(geometry, material);
+ if let Some(mesh) = node.mesh_mut() {
+ mesh.instances = Some(instances.into());
+ }
+ node
+ }
+
+ /// A light source, see [`Light`].
+ pub fn light(light: Light) -> Self {
+ Self::new(Object::Light(light))
+ }
+
+ /// Glowing sprites, three.js `Points`. See [`Particles`].
+ pub fn particles(items: Vec<Particle>, blending: Blending) -> Self {
+ Self::new(Object::Particles(Particles { items, blending }))
+ }
+
+ /// Sets the name for [`Scene::find`].
+ pub fn named(mut self, name: &str) -> Self {
+ self.name = Some(name.into());
+ self
+ }
+
+ /// Sets the position in meters, three.js `position.set(x, y, z)`.
+ pub fn at(self, x: f32, y: f32, z: f32) -> Self {
+ self.with_position(Vec3::new(x, y, z))
+ }
+
+ /// Sets the position in meters.
+ pub fn with_position(mut self, position: Vec3) -> Self {
+ self.position = position;
+ self
+ }
+
+ /// Sets the rotation.
+ pub fn with_rotation(mut self, rotation: Quat) -> Self {
+ self.rotation = rotation;
+ self
+ }
+
+ /// Sets the rotation from Euler angles in radians, in XYZ order as in three.js.
+ pub fn euler(self, x: f32, y: f32, z: f32) -> Self {
+ self.with_rotation(euler(x, y, z))
+ }
+
+ /// Turns the node by `angle` radians around its local X axis.
+ pub fn rotate_x(mut self, angle: f32) -> Self {
+ self.rotation *= Quat::from_rotation_x(angle);
+ self
+ }
+
+ /// Turns the node by `angle` radians around its local Y axis.
+ pub fn rotate_y(mut self, angle: f32) -> Self {
+ self.rotation *= Quat::from_rotation_y(angle);
+ self
+ }
+
+ /// Turns the node by `angle` radians around its local Z axis.
+ pub fn rotate_z(mut self, angle: f32) -> Self {
+ self.rotation *= Quat::from_rotation_z(angle);
+ self
+ }
+
+ /// Sets the same scale on all axes.
+ pub fn scaled(self, scale: f32) -> Self {
+ self.scaled3(scale, scale, scale)
+ }
+
+ /// Sets the scale of each axis.
+ pub fn scaled3(mut self, x: f32, y: f32, z: f32) -> Self {
+ self.scale = Vec3::new(x, y, z);
+ self
+ }
+
+ /// Hides the node and its subtree.
+ pub fn hidden(mut self) -> Self {
+ self.visible = false;
+ self
+ }
+
+ /// Sets whether a mesh casts and receives shadows. Other nodes ignore it.
+ pub fn shadows(mut self, cast: bool, receive: bool) -> Self {
+ if let Some(mesh) = self.mesh_mut() {
+ mesh.cast_shadow = cast;
+ mesh.receive_shadow = receive;
+ }
+ self
+ }
+
+ /// The transform relative to the parent.
+ pub fn local_matrix(&self) -> Mat4 {
+ Mat4::from_scale_rotation_translation(self.scale, self.rotation, self.position)
+ }
+
+ /// The parent node. `None` for a node at the root.
+ pub fn parent(&self) -> Option<NodeId> {
+ self.parent
+ }
+
+ /// The child nodes, in the order they were added.
+ pub fn children(&self) -> &[NodeId] {
+ &self.children
+ }
+
+ /// The mesh of a mesh node.
+ pub fn as_mesh(&self) -> Option<&Mesh> {
+ match &self.object {
+ Object::Mesh(mesh) => Some(mesh),
+ _ => None,
+ }
+ }
+
+ /// The mesh of a mesh node, mutable.
+ pub fn mesh_mut(&mut self) -> Option<&mut Mesh> {
+ match &mut self.object {
+ Object::Mesh(mesh) => Some(mesh),
+ _ => None,
+ }
+ }
+
+ /// The material of a mesh node, mutable.
+ pub fn material_mut(&mut self) -> Option<&mut Material> {
+ self.mesh_mut().map(|mesh| &mut mesh.material)
+ }
+
+ /// The light of a light node, mutable.
+ pub fn light_mut(&mut self) -> Option<&mut Light> {
+ match &mut self.object {
+ Object::Light(light) => Some(light),
+ _ => None,
+ }
+ }
+}
+
+/// What the renderer draws where there is no geometry.
+#[derive(Debug, Clone, Default, PartialEq)]
+pub enum Background {
+ /// Alpha 0, the default. The SVG behind the `<image>` shows through. Glows and bloom
+ /// stay visible on it.
+ #[default]
+ Transparent,
+ /// A solid color.
+ Color(Rgb),
+ /// The environment, blurred as a surface of roughness `blur` (`0..1`) reflects it,
+ /// three.js `scene.background = scene.environment` with `backgroundBlurriness`.
+ Environment { blur: f32 },
+}
+
+/// Distance fog, three.js `Fog` and `FogExp2`.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub enum Fog {
+ /// No fog closer than `near` meters, full fog beyond `far` meters, three.js `Fog`.
+ Linear { color: Rgb, near: f32, far: f32 },
+ /// Fog that grows as `1 - exp(-(density * distance)²)`, three.js `FogExp2`.
+ Exp2 { color: Rgb, density: f32 },
+}
+
+impl Fog {
+ /// The amount of fog at `distance` meters from the camera, `0..1`.
+ pub(crate) fn factor(&self, distance: f32) -> f32 {
+ match *self {
+ Fog::Linear { near, far, .. } => {
+ ((distance - near) / (far - near).max(1e-6)).clamp(0.0, 1.0)
+ }
+ Fog::Exp2 { density, .. } => 1.0 - (-(density * distance).powi(2)).exp(),
+ }
+ }
+
+ pub(crate) fn color(&self) -> Rgb {
+ match *self {
+ Fog::Linear { color, .. } | Fog::Exp2 { color, .. } => color,
+ }
+ }
+}
+
+/// A scene graph, three.js `Scene`.
+///
+/// Build a template scene once and keep the [`NodeId`]s of the parts that you animate. For
+/// each frame, clone the template, set the transforms and render the clone. The clones
+/// share the geometry, so a clone is cheap.
+///
+/// ```rust
+/// use fframes::three_d::*;
+///
+/// let mut scene = Scene::new().environment(Environment::studio());
+/// let cube = scene.add(Node::mesh(Geometry::rounded_box(1.0, 1.0, 1.0, 0.1, 3), Material::metal(0xd0d4dc, 0.25)));
+/// scene.add(Node::light(Light::sun(Rgb::WHITE, 3.0, vec3(3.0, 6.0, 4.0))));
+///
+/// // in render_frame
+/// let t = 0.5;
+/// let mut frame_scene = scene.clone();
+/// frame_scene[cube].rotation = euler(t, t * 1.3, 0.0);
+/// let camera = Camera::perspective(40.0).at(0.0, 1.5, 4.0).look_at(Vec3::ZERO);
+/// let image = Renderer::new(640, 360).render(&frame_scene, &camera);
+/// ```
+#[derive(Debug, Clone, Default)]
+pub struct Scene {
+ /// All nodes. A parent always comes before its children.
+ nodes: Vec<Node>,
+ /// Default [`Background::Transparent`].
+ pub background: Background,
+ /// The light around the scene. Default [`Environment::None`].
+ pub environment: Environment,
+ /// Default `None`.
+ pub fog: Option<Fog>,
+ /// The plane that materials with [`Material::reflection`] mirror. Default `None`.
+ pub reflector: Option<Reflector>,
+}
+
+/// A plane that mirrors the scene, three.js `Reflector`.
+///
+/// Use it for a floor, a table top or a mirror wall. Surfaces on the plane with
+/// [`Material::reflection`] show the mirrored scene, blurred by their roughness. A scene
+/// has one reflector at most.
+///
+/// ```rust
+/// use fframes::three_d::*;
+///
+/// let mut scene = Scene::new().reflector(Reflector::floor());
+/// scene.add(Node::mesh(Geometry::floor(20.0, 20.0), Material::standard(0x303236).roughness(0.3).reflection(0.8)));
+/// ```
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct Reflector {
+ /// A point on the plane, in meters.
+ pub point: Vec3,
+ /// The unit normal of the plane, on the side of the viewer.
+ pub normal: Vec3,
+ /// The resolution of the reflection relative to the frame, `0.1..=1`. Default 0.5.
+ /// Roughness blurs most reflections, so only mirror finishes need more.
+ pub scale: f32,
+}
+
+impl Reflector {
+ /// A plane through `point` with the normal `normal`. A zero normal becomes +Y.
+ pub fn new(point: Vec3, normal: Vec3) -> Self {
+ Self {
+ point,
+ normal: normal.normalize_or(Vec3::Y),
+ scale: 0.5,
+ }
+ }
+
+ /// The ground plane `y = 0`, facing up.
+ pub fn floor() -> Self {
+ Self::new(Vec3::ZERO, Vec3::Y)
+ }
+
+ /// Sets the resolution relative to the frame, clamped to `0.1..=1`.
+ pub fn scale(mut self, scale: f32) -> Self {
+ self.scale = scale.clamp(0.1, 1.0);
+ self
+ }
+
+ /// The plane as `(normal, offset)`. `dot(normal, p) + offset` is the distance of `p` in
+ /// front of the plane.
+ pub(crate) fn plane(&self) -> Vec4 {
+ self.normal.extend(-self.normal.dot(self.point))
+ }
+
+ /// The transform that mirrors the world in the plane.
+ pub(crate) fn matrix(&self) -> Mat4 {
+ let n = self.normal;
+ let mirror = |v: Vec3| v - 2.0 * n * n.dot(v);
+ Mat4::from_cols(
+ mirror(Vec3::X).extend(0.0),
+ mirror(Vec3::Y).extend(0.0),
+ mirror(Vec3::Z).extend(0.0),
+ (2.0 * n * n.dot(self.point)).extend(1.0),
+ )
+ }
+}
+
+impl Scene {
+ /// An empty scene with a transparent background and no environment light.
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Sets the background.
+ pub fn background(mut self, background: Background) -> Self {
+ self.background = background;
+ self
+ }
+
+ /// Sets the environment light.
+ pub fn environment(mut self, environment: Environment) -> Self {
+ self.environment = environment;
+ self
+ }
+
+ /// Sets the plane that the scene reflects in, see [`Reflector`].
+ pub fn reflector(mut self, reflector: Reflector) -> Self {
+ self.reflector = Some(reflector);
+ self
+ }
+
+ /// Sets the fog.
+ pub fn fog(mut self, fog: Fog) -> Self {
+ self.fog = Some(fog);
+ self
+ }
+
+ /// Adds a node at the root and returns its id.
+ pub fn add(&mut self, node: Node) -> NodeId {
+ self.insert(None, node)
+ }
+
+ /// Adds a node as a child of `parent` and returns its id. The transform of the node is
+ /// relative to the parent.
+ pub fn add_to(&mut self, parent: NodeId, node: Node) -> NodeId {
+ self.insert(Some(parent), node)
+ }
+
+ /// Adds a node below `parent`, or at the root for `None`, and returns its id.
+ pub(crate) fn insert(&mut self, parent: Option<NodeId>, mut node: Node) -> NodeId {
+ let id = NodeId(self.nodes.len() as u32);
+ node.parent = parent;
+ node.children.clear();
+ if let Some(parent) = parent {
+ self.nodes[parent.index()].children.push(id);
+ }
+ self.nodes.push(node);
+ id
+ }
+
+ /// Copies all nodes of `other` with their hierarchy below `parent`, or to the root for
+ /// `None`. Returns the id offset: node `NodeId(i)` of `other` becomes
+ /// `NodeId(i + offset)`. The copies of skins point to the copied joints.
+ /// [`Model::add_to`](crate::Model::add_to) uses it.
+ pub fn append(&mut self, parent: Option<NodeId>, other: &Scene) -> u32 {
+ let offset = self.nodes.len() as u32;
+ let shift = |id: &mut NodeId| id.0 += offset;
+ for node in &other.nodes {
+ let mut node = node.clone();
+ node.children.iter_mut().for_each(shift);
+ if let Some(skin) = node.mesh_mut().and_then(|mesh| mesh.skin.as_mut()) {
+ skin.joints.iter_mut().for_each(shift);
+ }
+ if let Some(own) = &mut node.parent {
+ shift(own);
+ } else if let Some(parent) = parent {
+ node.parent = Some(parent);
+ let id = NodeId(self.nodes.len() as u32);
+ self.nodes[parent.index()].children.push(id);
+ }
+ self.nodes.push(node);
+ }
+ offset
+ }
+
+ /// The number of nodes.
+ pub fn len(&self) -> usize {
+ self.nodes.len()
+ }
+
+ /// Whether the scene has no nodes.
+ pub fn is_empty(&self) -> bool {
+ self.nodes.is_empty()
+ }
+
+ /// All nodes with their ids. A parent always comes before its children.
+ pub fn nodes(&self) -> impl Iterator<Item = (NodeId, &Node)> {
+ (0..).map(NodeId).zip(&self.nodes)
+ }
+
+ /// The node with this id. `None` when the id is out of range.
+ pub fn get(&self, id: NodeId) -> Option<&Node> {
+ self.nodes.get(id.index())
+ }
+
+ /// The node with this id, mutable. `None` when the id is out of range.
+ pub fn get_mut(&mut self, id: NodeId) -> Option<&mut Node> {
+ self.nodes.get_mut(id.index())
+ }
+
+ /// The id of the first node with this name.
+ pub fn find(&self, name: &str) -> Option<NodeId> {
+ self.nodes()
+ .find(|(_, n)| n.name.as_deref() == Some(name))
+ .map(|(id, _)| id)
+ }
+
+ /// The first node with this name, mutable.
+ pub fn find_mut(&mut self, name: &str) -> Option<&mut Node> {
+ self.nodes
+ .iter_mut()
+ .find(|n| n.name.as_deref() == Some(name))
+ }
+
+ /// `id` and all nodes below it, breadth first.
+ pub fn descendants(&self, id: NodeId) -> Vec<NodeId> {
+ let mut out = vec![id];
+ let mut i = 0;
+ while i < out.len() {
+ out.extend_from_slice(&self.nodes[out[i].index()].children);
+ i += 1;
+ }
+ out
+ }
+
+ /// The transform from the space of the node to world space.
+ pub fn world_matrix(&self, id: NodeId) -> Mat4 {
+ let node = &self.nodes[id.index()];
+ match node.parent {
+ Some(parent) => self.world_matrix(parent) * node.local_matrix(),
+ None => node.local_matrix(),
+ }
+ }
+
+ /// The world position of the origin of the node. Give it to
+ /// [`Camera::project`](crate::Camera::project) to put SVG on the node.
+ pub fn world_position(&self, id: NodeId) -> Vec3 {
+ self.world_matrix(id).w_axis.truncate()
+ }
+
+ /// Converts a point from the space of the node to world space.
+ pub fn local_to_world(&self, id: NodeId, local: Vec3) -> Vec3 {
+ self.world_matrix(id).transform_point3(local)
+ }
+
+ /// The world matrices of all nodes, in node order.
+ pub fn world_matrices(&self) -> Vec<Mat4> {
+ let mut out: Vec<Mat4> = Vec::with_capacity(self.nodes.len());
+ for node in &self.nodes {
+ let local = node.local_matrix();
+ let world = match node.parent {
+ Some(parent) => out[parent.index()] * local,
+ None => local,
+ };
+ out.push(world);
+ }
+ out
+ }
+
+ /// For each node, whether the node and all its ancestors are visible.
+ pub fn visibilities(&self) -> Vec<bool> {
+ let mut out: Vec<bool> = Vec::with_capacity(self.nodes.len());
+ for node in &self.nodes {
+ let parent_visible = node.parent.is_none_or(|p| out[p.index()]);
+ out.push(parent_visible && node.visible);
+ }
+ out
+ }
+
+ /// The world bounds of the visible meshes in the subtree of `id`. Skins do not change
+ /// the result.
+ pub fn bounds(&self, id: NodeId) -> Aabb {
+ let worlds = self.world_matrices();
+ let visible = self.visibilities();
+ let mut aabb = Aabb::EMPTY;
+ for n in self.descendants(id) {
+ if visible[n.index()]
+ && let Some(mesh) = self[n].as_mesh()
+ {
+ aabb = aabb.union(mesh.bounds(&worlds[n.index()]));
+ }
+ }
+ aabb
+ }
+}
+
+impl Index<NodeId> for Scene {
+ type Output = Node;
+
+ fn index(&self, id: NodeId) -> &Node {
+ &self.nodes[id.index()]
+ }
+}
+
+impl IndexMut<NodeId> for Scene {
+ fn index_mut(&mut self, id: NodeId) -> &mut Node {
+ &mut self.nodes[id.index()]
+ }
+}
diff --git a/fframes-three-d/src/texture.rs b/fframes-three-d/src/texture.rs
new file mode 100644
index 00000000..ec032eb0
--- /dev/null
+++ b/fframes-three-d/src/texture.rs
@@ -0,0 +1,297 @@
+use std::sync::OnceLock;
+
+use glam::{Vec2, Vec4};
+
+use crate::Rgb;
+use crate::color::{linear_to_srgb, srgb_to_linear};
+
+/// An RGBA8 image that materials sample. The image repeats outside `0..1`. Sampling is
+/// trilinear between mipmap levels that match the pixel footprint, so fine detail (floor
+/// tiles, text) does not shimmer.
+#[derive(Clone)]
+pub struct Texture {
+ pub width: u32,
+ pub height: u32,
+ /// Mipmap levels. Level 0 is the image. Each next level has half the size, down to one
+ /// texel.
+ levels: Vec<Level>,
+ /// True for color data. The texture keeps it as sRGB and converts it to linear when it
+ /// samples it. False for linear data such as metalness and roughness.
+ pub srgb: bool,
+ /// UV scale applied before sampling: `uv * repeat + offset`.
+ pub repeat: Vec2,
+ /// UV offset applied before sampling, after `repeat`.
+ pub offset: Vec2,
+}
+
+#[derive(Clone)]
+struct Level {
+ width: u32,
+ height: u32,
+ data: Vec<[u8; 4]>,
+}
+
+impl std::fmt::Debug for Texture {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Texture")
+ .field("width", &self.width)
+ .field("height", &self.height)
+ .field("srgb", &self.srgb)
+ .field("levels", &self.levels.len())
+ .finish_non_exhaustive()
+ }
+}
+
+impl Texture {
+ /// Makes a texture from tightly packed rows of straight (not premultiplied) RGBA8. A
+ /// size of 0 counts as 1. Missing texels are transparent black, extra bytes are left out.
+ pub fn from_rgba8(width: u32, height: u32, rgba: &[u8], srgb: bool) -> Self {
+ let (width, height) = (width.max(1), height.max(1));
+ let mut data = rgba.as_chunks::<4>().0.to_vec();
+ data.resize((width * height) as usize, [0; 4]);
+ Self::from_level(
+ Level {
+ width,
+ height,
+ data,
+ },
+ srgb,
+ )
+ }
+
+ /// Decodes a PNG, JPEG or WebP image as a color texture. The bytes can come from
+ /// `include_bytes!` or from an embedded media file.
+ pub fn decode(bytes: &[u8]) -> Result<Self, image::ImageError> {
+ let image = image::load_from_memory(bytes)?.to_rgba8();
+ Ok(Self::from_rgba8(
+ image.width(),
+ image.height(),
+ image.as_raw(),
+ true,
+ ))
+ }
+
+ /// A color texture from an fframes image: a media file, a decoded video frame, or a
+ /// rendered frame of another video. Use a new texture for each frame of a video, so a
+ /// screen in the scene plays it. Resize large frames first (`into_resized_image`), because
+ /// the texture makes its mipmap levels on the CPU.
+ #[cfg(not(target_arch = "wasm32"))]
+ pub fn from_image(image: &fframes_media::ImageData<'_>) -> Self {
+ let source = &image.image;
+ // fframes keeps premultiplied alpha; the texture keeps straight alpha
+ let rgba: Vec<u8> = source
+ .data
+ .as_chunks::<4>()
+ .0
+ .iter()
+ .flat_map(|&[r, g, b, a]| match a {
+ 0 | 255 => [r, g, b, a],
+ _ => {
+ let straight = |c: u8| (u32::from(c) * 255 / u32::from(a)).min(255) as u8;
+ [straight(r), straight(g), straight(b), a]
+ }
+ })
+ .collect();
+ Self::from_rgba8(source.width, source.height, &rgba, true)
+ }
+
+ /// Decodes a PNG, JPEG or WebP image of linear data: a normal, roughness, metalness or
+ /// ambient occlusion map.
+ pub fn decode_linear(bytes: &[u8]) -> Result<Self, image::ImageError> {
+ let image = image::load_from_memory(bytes)?.to_rgba8();
+ Ok(Self::from_rgba8(
+ image.width(),
+ image.height(),
+ image.as_raw(),
+ false,
+ ))
+ }
+
+ /// Makes an opaque color texture from `f(u, v)`, which returns the color for `u` and `v`
+ /// in `0..1`. [`Self::from_fn_data`] makes one with alpha.
+ pub fn from_fn(width: u32, height: u32, f: impl Fn(f32, f32) -> Rgb) -> Self {
+ Self::from_fn_data(width, height, true, |u, v| {
+ let [r, g, b] = f(u, v).to_srgb8();
+ [r, g, b, 255]
+ })
+ }
+
+ /// Makes a texture from `f(u, v)`, which returns raw RGBA bytes for `u` and `v` in
+ /// `0..1`. A size of 0 counts as 1. For example, a glTF metallic-roughness map has
+ /// roughness in green and metalness in blue, with `srgb` false.
+ pub fn from_fn_data(
+ width: u32,
+ height: u32,
+ srgb: bool,
+ f: impl Fn(f32, f32) -> [u8; 4],
+ ) -> Self {
+ let (width, height) = (width.max(1), height.max(1));
+ let mut data = Vec::with_capacity((width * height) as usize);
+ for y in 0..height {
+ let v = (y as f32 + 0.5) / height as f32;
+ for x in 0..width {
+ data.push(f((x as f32 + 0.5) / width as f32, v));
+ }
+ }
+ Self::from_level(
+ Level {
+ width,
+ height,
+ data,
+ },
+ srgb,
+ )
+ }
+
+ fn from_level(level: Level, srgb: bool) -> Self {
+ let (width, height) = (level.width, level.height);
+ let mut levels = vec![level];
+ while let Some(last) = levels.last()
+ && (last.width > 1 || last.height > 1)
+ {
+ let next = downsample(last, srgb);
+ levels.push(next);
+ }
+ Self {
+ width,
+ height,
+ levels,
+ srgb,
+ repeat: Vec2::ONE,
+ offset: Vec2::ZERO,
+ }
+ }
+
+ /// The mipmap levels as width, height and RGBA8 texels, largest first.
+ #[cfg(all(feature = "gpu", not(target_arch = "wasm32")))]
+ pub(crate) fn levels(&self) -> impl Iterator<Item = (u32, u32, &[[u8; 4]])> {
+ self.levels
+ .iter()
+ .map(|l| (l.width, l.height, l.data.as_slice()))
+ }
+
+ /// Sets how many times the texture repeats along U and V.
+ pub fn repeat(mut self, u: f32, v: f32) -> Self {
+ self.repeat = Vec2::new(u, v);
+ self
+ }
+
+ /// Bilinear sample of the full-size image. Returns linear RGBA with straight alpha.
+ pub fn sample(&self, uv: Vec2) -> Vec4 {
+ self.sample_lod(uv, 0.0)
+ }
+
+ /// Trilinear sample at a mipmap level. Level 0 is the full size, each next level has
+ /// half the size. Returns linear RGBA with straight alpha.
+ pub(crate) fn sample_lod(&self, uv: Vec2, lod: f32) -> Vec4 {
+ let uv = uv * self.repeat + self.offset;
+ let max = (self.levels.len() - 1) as f32;
+ let lod = if lod.is_finite() {
+ lod.clamp(0.0, max)
+ } else {
+ 0.0
+ };
+ let l0 = lod.floor() as usize;
+ let a = self.bilinear(&self.levels[l0], uv);
+ let f = lod - l0 as f32;
+ if f < 1e-3 || l0 + 1 >= self.levels.len() {
+ return a;
+ }
+ a.lerp(self.bilinear(&self.levels[l0 + 1], uv), f)
+ }
+
+ /// Anisotropic sample like the GPU sampler (`anisotropy_clamp` 8). `dx` and `dy` are the
+ /// UV changes to the next pixel right and down, measured before `repeat`. Up to 8
+ /// trilinear samples along the long axis of the pixel footprint, at the mipmap level of
+ /// its short axis, so that a surface seen at a low angle stays as sharp as on the GPU.
+ pub(crate) fn sample_grad(&self, uv: Vec2, dx: Vec2, dy: Vec2) -> Vec4 {
+ const MAX_ANISOTROPY: f32 = 8.0;
+ let texels = Vec2::new(self.width as f32, self.height as f32) * self.repeat;
+ let (x, y) = ((dx * texels).length(), (dy * texels).length());
+ let (major, minor, axis) = if x >= y { (x, y, dx) } else { (y, x, dy) };
+ let count = (major / minor.max(1e-6)).ceil().clamp(1.0, MAX_ANISOTROPY);
+ let lod = (major / count).max(1e-6).log2();
+ if count <= 1.0 || !count.is_finite() {
+ return self.sample_lod(uv, lod);
+ }
+ let sum = (0..count as usize).fold(Vec4::ZERO, |sum, i| {
+ let t = (i as f32 + 0.5) / count - 0.5;
+ sum + self.sample_lod(uv + axis * t, lod)
+ });
+ sum / count
+ }
+
+ fn bilinear(&self, level: &Level, uv: Vec2) -> Vec4 {
+ let x = uv.x * level.width as f32 - 0.5;
+ let y = uv.y * level.height as f32 - 0.5;
+ let (x0, y0) = (x.floor(), y.floor());
+ let (fx, fy) = (x - x0, y - y0);
+ let (w, h) = (level.width as i32, level.height as i32);
+ let xi = (x0 as i32).rem_euclid(w);
+ let yi = (y0 as i32).rem_euclid(h);
+ let xi1 = (xi + 1) % w;
+ let yi1 = (yi + 1) % h;
+ let lut = self.srgb.then(srgb_lut);
+ let texel = |x: i32, y: i32| decode(level.data[(y * w + x) as usize], lut);
+ let top = texel(xi, yi).lerp(texel(xi1, yi), fx);
+ let bottom = texel(xi, yi1).lerp(texel(xi1, yi1), fx);
+ top.lerp(bottom, fy)
+ }
+}
+
+/// Converts a stored texel to linear RGBA in `0..1`. `lut` converts sRGB color channels;
+/// without it the texel is linear data. Alpha is always linear.
+#[inline]
+fn decode(c: [u8; 4], lut: Option<&[f32; 256]>) -> Vec4 {
+ match lut {
+ Some(lut) => Vec4::new(
+ lut[c[0] as usize],
+ lut[c[1] as usize],
+ lut[c[2] as usize],
+ f32::from(c[3]) / 255.0,
+ ),
+ None => Vec4::from_array(c.map(f32::from)) / 255.0,
+ }
+}
+
+/// Makes the next mipmap level: half the size, each texel the mean of four texels in
+/// linear light.
+fn downsample(level: &Level, srgb: bool) -> Level {
+ let width = (level.width / 2).max(1);
+ let height = (level.height / 2).max(1);
+ let lut = srgb.then(srgb_lut);
+ let encode = |v: f32, srgb: bool| {
+ let v = v.clamp(0.0, 1.0);
+ let v = if srgb { linear_to_srgb(v) } else { v };
+ (v * 255.0 + 0.5) as u8
+ };
+ let mut data = Vec::with_capacity((width * height) as usize);
+ for y in 0..height {
+ for x in 0..width {
+ let mut sum = Vec4::ZERO;
+ for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
+ let sx = (x * 2 + dx).min(level.width - 1);
+ let sy = (y * 2 + dy).min(level.height - 1);
+ sum += decode(level.data[(sy * level.width + sx) as usize], lut);
+ }
+ let mean = sum / 4.0;
+ data.push([
+ encode(mean.x, srgb),
+ encode(mean.y, srgb),
+ encode(mean.z, srgb),
+ encode(mean.w, false),
+ ]);
+ }
+ }
+ Level {
+ width,
+ height,
+ data,
+ }
+}
+
+/// sRGB to linear conversion for every 8-bit value.
+fn srgb_lut() -> &'static [f32; 256] {
+ static LUT: OnceLock<[f32; 256]> = OnceLock::new();
+ LUT.get_or_init(|| std::array::from_fn(|i| srgb_to_linear(i as f32 / 255.0)))
+}
diff --git a/fframes-three-d/tests/common/mod.rs b/fframes-three-d/tests/common/mod.rs
new file mode 100644
index 00000000..edf8d992
--- /dev/null
+++ b/fframes-three-d/tests/common/mod.rs
@@ -0,0 +1,221 @@
+//! The scene and the image output that the render tests share.
+#![allow(clippy::unreadable_literal)]
+use std::path::PathBuf;
+
+use fframes_three_d::*;
+
+/// Writes `name.png` to `$FFRAMES_3D_OUT`, or to `fframes_three_d` in the temp directory.
+pub fn save(name: &str, pixels: &Pixels) {
+ let dir = std::env::var_os("FFRAMES_3D_OUT").map_or_else(
+ || std::env::temp_dir().join("fframes_three_d"),
+ PathBuf::from,
+ );
+ std::fs::create_dir_all(&dir).unwrap();
+ image::save_buffer(
+ dir.join(format!("{name}.png")),
+ &pixels.to_straight_rgba(),
+ pixels.width,
+ pixels.height,
+ image::ColorType::Rgba8,
+ )
+ .unwrap();
+}
+
+/// A reflective floor, objects with different geometries and materials, sparks and two
+/// lights, in front of the blurred environment.
+pub fn showcase() -> (Scene, Camera) {
+ let mut scene = Scene::new()
+ .environment(Environment::studio())
+ .background(Background::Environment { blur: 0.5 })
+ .reflector(Reflector::floor());
+ scene.add(
+ Node::mesh(
+ Geometry::floor(30.0, 30.0),
+ Material::standard(0x202228).roughness(0.6).reflection(0.7),
+ )
+ .shadows(false, true),
+ );
+ scene.add(
+ Node::mesh(
+ Geometry::rounded_box(1.0, 1.0, 1.0, 0.08, 4),
+ Material::metal(0xd4d8e0, 0.25),
+ )
+ .at(-2.2, 0.5, 0.0)
+ .rotate_y(0.5),
+ );
+ scene.add(
+ Node::mesh(
+ Geometry::sphere(0.6, 48, 24),
+ Material::standard(0xff4d1a).roughness(0.35).clearcoat(1.0),
+ )
+ .at(-0.8, 0.6, 0.6),
+ );
+ scene.add(
+ Node::mesh(
+ Geometry::cylinder(0.4, 0.5, 1.2, 40),
+ Material::metal(0xffb84d, 0.4),
+ )
+ .at(0.6, 0.6, -0.2),
+ );
+ scene.add(
+ Node::mesh(
+ Geometry::torus(0.45, 0.15, 24, 64),
+ Material::standard(0x2a6dff).roughness(0.2),
+ )
+ .at(2.0, 0.6, 0.4)
+ .rotate_x(-0.4),
+ );
+ scene.add(
+ Node::mesh(
+ Geometry::extrude(&Geometry::polygon(0.5, 6), 0.25, 0.05),
+ Material::metal(0x9aa3ad, 0.5),
+ )
+ .at(0.0, 1.6, -1.2),
+ );
+ scene.add(
+ Node::mesh(
+ Geometry::icosahedron(0.35, 0),
+ Material::standard(0x44dd88).flat(),
+ )
+ .at(1.4, 0.35, 1.3),
+ );
+ scene.add(
+ Node::mesh(
+ Geometry::capsule(0.18, 0.5, 6, 24),
+ Material::standard(0x111111).emissive(0x33ddff, 6.0),
+ )
+ .at(2.9, 0.45, -0.8),
+ );
+ scene.add(
+ Node::mesh(
+ Geometry::sphere(0.5, 32, 16),
+ Material::standard(0x99ccff).opacity(0.35),
+ )
+ .at(-1.4, 1.6, -1.0),
+ );
+ // a shell of sparks on a golden angle spiral
+ let sparks: Vec<Particle> = (0..80)
+ .map(|i| {
+ let y = 1.0 - (i as f32 + 0.5) / 40.0;
+ let (sin, cos) = (i as f32 * 2.399_963).sin_cos();
+ let d = vec3(cos, 0.0, sin) * (1.0 - y * y).sqrt() + Vec3::Y * y;
+ let distance = 0.4 + (i % 9) as f32 * 0.1;
+ Particle::new(
+ vec3(2.9, 0.9, -0.8) + d * distance,
+ 0.015,
+ Rgb::hex(0xffaa33) * 10.0,
+ )
+ })
+ .collect();
+ scene.add(Node::particles(sparks, Blending::Additive));
+ scene.add(Node::light(Light::sun(
+ Rgb::WHITE,
+ 2.5,
+ vec3(3.0, 6.0, 4.0),
+ )));
+ scene.add(Node::light(Light::point(0x3399ff, 6.0, 0.0)).at(-3.0, 1.5, 2.0));
+ let camera = Camera::perspective(40.0)
+ .at(0.5, 3.0, 7.5)
+ .look_at(vec3(0.3, 0.6, 0.0));
+ (scene, camera)
+}
+
+/// A grid of cubes as one instanced mesh, or as separate meshes with the same transforms
+/// and colors, lit by the sun, on a floor.
+pub fn cubes(instanced: bool) -> (Scene, Camera) {
+ let mut scene = Scene::new()
+ .environment(Environment::studio())
+ .background(Background::Color(Rgb::hex(0x101216)));
+ scene.add(Node::mesh(
+ Geometry::floor(20.0, 20.0),
+ Material::standard(0x707478),
+ ));
+ scene.add(Node::light(Light::sun(
+ Rgb::WHITE,
+ 2.5,
+ vec3(3.0, 6.0, 4.0),
+ )));
+ let cube = std::sync::Arc::new(Geometry::rounded_box(0.5, 0.5, 0.5, 0.06, 3));
+ let material = Material::standard(0xffffff).roughness(0.35);
+ let copies: Vec<(Mat4, Rgb)> = (0..49)
+ .map(|i| {
+ let (x, z) = ((i % 7) as f32 - 3.0, (i / 7) as f32 - 3.0);
+ let turn = Quat::from_rotation_y(i as f32 * 0.37);
+ let place = Mat4::from_rotation_translation(turn, vec3(x * 0.8, 0.3, z * 0.8));
+ let color = Rgb::linear(0.2 + 0.1 * (i % 5) as f32, 0.4, 0.9 - 0.1 * (i % 7) as f32);
+ (place, color)
+ })
+ .collect();
+ if instanced {
+ let instances =
+ Instances::new(copies.iter().map(|(m, _)| *m)).colors(copies.iter().map(|(_, c)| *c));
+ scene.add(Node::instanced(cube, material, instances));
+ } else {
+ for (m, color) in copies {
+ let (scale, rotation, position) = m.to_scale_rotation_translation();
+ let mut node = Node::mesh(cube.clone(), material.clone().color(color));
+ node.position = position;
+ node.rotation = rotation;
+ node.scale = scale;
+ scene.add(node);
+ }
+ }
+ let camera = Camera::perspective(40.0)
+ .at(4.5, 4.0, 6.0)
+ .look_at(vec3(0.0, 0.2, 0.0));
+ (scene, camera)
+}
+
+/// A floor and a sphere with a normal map of round studs and an ambient occlusion map that
+/// repeats twice as often, lit at a low angle so that the studs cast highlights.
+pub fn studs() -> (Scene, Camera) {
+ // a dome on each of 8 x 8 cells: the normal points away from the cell center
+ let dome = |u: f32, v: f32| {
+ let (x, y) = ((u * 8.0).fract() - 0.5, (v * 8.0).fract() - 0.5);
+ let r2 = (x * x + y * y) / 0.16;
+ if r2 >= 1.0 {
+ return (Vec3::Z, 1.0);
+ }
+ // up in the image is -v, so the green channel takes -y
+ let n = vec3(x, -y, 0.0) * 2.5 + Vec3::Z * (1.0 - r2).sqrt();
+ (n.normalize(), 1.0)
+ };
+ let normal = Texture::from_fn_data(256, 256, false, |u, v| {
+ let n = dome(u, v).0 * 0.5 + 0.5;
+ [
+ (n.x * 255.0) as u8,
+ (n.y * 255.0) as u8,
+ (n.z * 255.0) as u8,
+ 255,
+ ]
+ });
+ let ao = Texture::from_fn_data(256, 256, false, |u, v| {
+ let (x, y) = ((u * 8.0).fract() - 0.5, (v * 8.0).fract() - 0.5);
+ let ring = ((x * x + y * y).sqrt() - 0.42).abs();
+ let a = (180.0 + ring.min(0.06) / 0.06 * 75.0) as u8;
+ [a, a, a, 255]
+ });
+ let (normal, ao) = (
+ std::sync::Arc::new(normal),
+ std::sync::Arc::new(ao.repeat(2.0, 2.0)),
+ );
+ let material = Material::standard(0x8a6e52)
+ .roughness(0.35)
+ .normal_map(normal.clone())
+ .ao_map(ao.clone());
+ let mut scene = Scene::new()
+ .environment(Environment::studio())
+ .background(Background::Color(Rgb::hex(0x101216)));
+ scene.add(Node::mesh(Geometry::floor(8.0, 8.0), material.clone()));
+ scene
+ .add(Node::mesh(Geometry::sphere(0.8, 64, 32), material.color(0x4a6a8a)).at(0.0, 0.8, 0.0));
+ scene.add(Node::light(Light::sun(
+ Rgb::WHITE,
+ 3.0,
+ vec3(-4.0, 1.5, -1.0),
+ )));
+ let camera = Camera::perspective(40.0)
+ .at(0.0, 2.2, 4.0)
+ .look_at(vec3(0.0, 0.5, 0.0));
+ (scene, camera)
+}
diff --git a/fframes-three-d/tests/gltf.rs b/fframes-three-d/tests/gltf.rs
new file mode 100644
index 00000000..df7a34e7
--- /dev/null
+++ b/fframes-three-d/tests/gltf.rs
@@ -0,0 +1,160 @@
+#![allow(clippy::unreadable_literal)]
+
+use base64::Engine;
+use fframes_three_d::*;
+
+/// A `.gltf` without scenes: a root with a node of one primitive and a node of two
+/// primitives with a morph target, and an animation of the weights and of a translation.
+fn small_gltf() -> Vec<u8> {
+ let floats: Vec<f32> = [
+ // 0: a triangle
+ &[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0][..],
+ // 36: its morph target moves it along Z
+ &[0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0],
+ // 72: the keyframe times
+ &[0.0, 1.0],
+ // 80: the weights
+ &[0.0, 1.0],
+ // 88: the translations
+ &[0.0, 0.0, 0.0, 2.0, 0.0, 0.0],
+ ]
+ .concat();
+ let bytes: Vec<u8> = floats.iter().flat_map(|f| f.to_le_bytes()).collect();
+ let uri = base64::engine::general_purpose::STANDARD.encode(&bytes);
+ format!(
+ r#"{{
+ "asset": {{ "version": "2.0" }},
+ "buffers": [{{ "byteLength": {len}, "uri": "data:application/octet-stream;base64,{uri}" }}],
+ "bufferViews": [
+ {{ "buffer": 0, "byteOffset": 0, "byteLength": 36 }},
+ {{ "buffer": 0, "byteOffset": 36, "byteLength": 36 }},
+ {{ "buffer": 0, "byteOffset": 72, "byteLength": 8 }},
+ {{ "buffer": 0, "byteOffset": 80, "byteLength": 8 }},
+ {{ "buffer": 0, "byteOffset": 88, "byteLength": 24 }}
+ ],
+ "accessors": [
+ {{ "bufferView": 0, "componentType": 5126, "count": 3, "type": "VEC3", "min": [0, 0, 0], "max": [1, 1, 0] }},
+ {{ "bufferView": 1, "componentType": 5126, "count": 3, "type": "VEC3", "min": [0, 0, 1], "max": [0, 0, 1] }},
+ {{ "bufferView": 2, "componentType": 5126, "count": 2, "type": "SCALAR", "min": [0], "max": [1] }},
+ {{ "bufferView": 3, "componentType": 5126, "count": 2, "type": "SCALAR" }},
+ {{ "bufferView": 4, "componentType": 5126, "count": 2, "type": "VEC3" }}
+ ],
+ "materials": [{{ "pbrMetallicRoughness": {{ "baseColorFactor": [1, 0, 0, 0.5] }} }}],
+ "meshes": [
+ {{ "primitives": [{{ "attributes": {{ "POSITION": 0 }}, "material": 0 }}] }},
+ {{
+ "primitives": [
+ {{ "attributes": {{ "POSITION": 0 }}, "targets": [{{ "POSITION": 1 }}] }},
+ {{ "attributes": {{ "POSITION": 0 }}, "targets": [{{ "POSITION": 1 }}] }}
+ ],
+ "weights": [0]
+ }}
+ ],
+ "nodes": [
+ {{ "name": "Root", "children": [1, 2] }},
+ {{ "name": "Single", "mesh": 0, "translation": [0, 1, 0] }},
+ {{ "name": "Double", "mesh": 1 }}
+ ],
+ "animations": [{{
+ "name": "Go",
+ "channels": [
+ {{ "sampler": 0, "target": {{ "node": 2, "path": "weights" }} }},
+ {{ "sampler": 1, "target": {{ "node": 1, "path": "translation" }} }}
+ ],
+ "samplers": [{{ "input": 2, "output": 3 }}, {{ "input": 2, "output": 4 }}]
+ }}]
+ }}"#,
+ len = bytes.len()
+ )
+ .into_bytes()
+}
+
+#[test]
+fn loads_gltf_like_three_js() {
+ let model = Model::from_gltf(&small_gltf()).unwrap();
+ // without scenes the roots are the nodes that are nobody's child, so each node comes
+ // once: Root, Single, Double and its two primitives
+ assert_eq!(model.scene.len(), 5);
+
+ let mut scene = Scene::new();
+ let instance = model.add_to(&mut scene, None);
+ let single = instance.find(&scene, "Single").unwrap();
+ let double = instance.find(&scene, "Double").unwrap();
+
+ // a node with one primitive is the mesh, as in three.js
+ let mesh = scene[single].as_mesh().unwrap();
+ // an OPAQUE material ignores the alpha of its color
+ assert_eq!(mesh.material.opacity, 1.0);
+ assert!(!mesh.material.transparent);
+ // no normals in the file: flat shading
+ assert!(mesh.material.flat_shading);
+ // a node with two primitives is a group with a mesh for each
+ assert!(scene[double].as_mesh().is_none());
+ assert_eq!(scene[double].children().len(), 2);
+
+ instance.play(&mut scene, model.animation("Go").unwrap(), 0.5);
+ assert!((scene[single].position - vec3(1.0, 0.0, 0.0)).length() < 1e-6);
+ for &child in scene[double].children() {
+ let weights = &scene[child].as_mesh().unwrap().morph_weights;
+ assert_eq!(weights.len(), 1);
+ assert!((weights[0] - 0.5).abs() < 1e-6, "{weights:?}");
+ }
+}
+
+/// Renders three poses of `RobotExpressive.glb` from three.js (CC0, Tomás Laulhé), a model
+/// with a skin, morph targets and 14 clips. It runs when `FFRAMES_3D_ROBOT` is the path of
+/// a copy.
+#[test]
+fn renders_skinned_gltf() {
+ let Ok(path) = std::env::var("FFRAMES_3D_ROBOT") else {
+ return;
+ };
+ let model = Model::from_gltf(&std::fs::read(path).unwrap()).unwrap();
+ let names: Vec<&str> = model.animations.iter().map(|a| a.name.as_str()).collect();
+ eprintln!("clips: {names:?}, bounds {:?}", model.bounds());
+ let dance = model.animation("Dance").unwrap();
+
+ let mut stage = Scene::new()
+ .environment(Environment::studio())
+ .background(Background::Color(Rgb::hex(0x202020)));
+ stage.add(
+ Node::mesh(Geometry::floor(40.0, 40.0), Material::standard(0x404040)).shadows(false, true),
+ );
+ stage.add(Node::light(Light::hemisphere(0xffffff, 0x444444, 2.0)));
+ stage.add(Node::light(Light::sun(
+ Rgb::WHITE,
+ 2.5,
+ vec3(0.0, 20.0, 10.0),
+ )));
+ let camera = Camera::perspective(45.0)
+ .at(-5.0, 3.0, 10.0)
+ .look_at(vec3(0.0, 2.0, 0.0));
+
+ let dir = std::env::temp_dir().join("fframes_three_d");
+ std::fs::create_dir_all(&dir).unwrap();
+ for (i, t) in [0.0, 0.4, 0.8].into_iter().enumerate() {
+ let mut scene = stage.clone();
+ let robot = model.add_to(&mut scene, None);
+ robot.play(&mut scene, dance, t);
+ let pixels = Renderer::new(960, 540).render_pixels(&scene, &camera);
+ image::save_buffer(
+ dir.join(format!("robot_{i}.png")),
+ &pixels.to_straight_rgba(),
+ pixels.width,
+ pixels.height,
+ image::ColorType::Rgba8,
+ )
+ .unwrap();
+ }
+}
+
+/// A broken file whose node is its own descendant loads without recursing forever.
+#[test]
+fn a_node_cycle_loads() {
+ let json = r#"{"asset":{"version":"2.0"},"scene":0,"scenes":[{"nodes":[0]}],
+ "nodes":[{"name":"a","children":[1]},{"name":"b","children":[0]}]}"#;
+ if let Ok(model) = Model::from_gltf(json.as_bytes()) {
+ let mut scene = Scene::new();
+ model.add_to(&mut scene, None);
+ }
+}
diff --git a/fframes-three-d/tests/gpu.rs b/fframes-three-d/tests/gpu.rs
new file mode 100644
index 00000000..b49b40c9
--- /dev/null
+++ b/fframes-three-d/tests/gpu.rs
@@ -0,0 +1,235 @@
+//! Compares the GPU renderer with the CPU rasterizer. It needs the `gpu` feature and skips
+//! when no GPU is available.
+#![cfg(feature = "gpu")]
+#![allow(clippy::unreadable_literal)]
+
+use fframes_three_d::*;
+
+mod common;
+
+/// Saves both images and returns their mean difference in 8-bit steps.
+fn compare(name: &str, cpu: &Pixels, gpu: &Pixels) -> f32 {
+ let diff: f64 = cpu
+ .rgba
+ .iter()
+ .zip(&gpu.rgba)
+ .map(|(a, b)| f64::from(a.abs_diff(*b)))
+ .sum();
+ let mean = (diff / cpu.rgba.len() as f64) as f32;
+ common::save(&format!("{name}_cpu"), cpu);
+ common::save(&format!("{name}_gpu"), gpu);
+ eprintln!("{name}: mean difference {mean:.2} / 255");
+ mean
+}
+
+#[test]
+fn gpu_matches_cpu() {
+ let gpu_renderer = Renderer::new(960, 540).bloom(Bloom::default());
+ if !gpu_renderer.uses_gpu() {
+ eprintln!("no GPU, skipped");
+ return;
+ }
+ let cpu_renderer = gpu_renderer.clone().cpu();
+ let (scene, camera) = common::showcase();
+ let cpu = cpu_renderer.render_pixels(&scene, &camera);
+ let start = std::time::Instant::now();
+ let mut gpu = gpu_renderer.render_pixels(&scene, &camera);
+ eprintln!("first gpu frame {:?}", start.elapsed());
+ let start = std::time::Instant::now();
+ for _ in 0..10 {
+ gpu = gpu_renderer.render_pixels(&scene, &camera);
+ }
+ eprintln!("gpu frame {:?}", start.elapsed() / 10);
+ assert!(compare("showcase", &cpu, &gpu) < 6.0);
+
+ let focused = camera.focus_on(vec3(-0.8, 0.6, 0.6), 14.0);
+ let cpu = cpu_renderer.render_pixels(&scene, &focused);
+ let gpu = gpu_renderer.render_pixels(&scene, &focused);
+ assert!(compare("showcase_dof", &cpu, &gpu) < 8.0);
+
+ let moment = |o: f32| (scene.clone(), camera.fov(camera.fov + o * 4.0));
+ let cpu = cpu_renderer.render_motion_blur_pixels(3, moment);
+ let gpu = gpu_renderer.render_motion_blur_pixels(3, moment);
+ assert!(compare("showcase_motion_blur", &cpu, &gpu) < 6.0);
+}
+
+#[test]
+fn gpu_instances_match_cpu() {
+ let gpu_renderer = Renderer::new(960, 540).bloom(Bloom::default());
+ if !gpu_renderer.uses_gpu() {
+ eprintln!("no GPU, skipped");
+ return;
+ }
+ let (scene, camera) = common::cubes(true);
+ let cpu = gpu_renderer.clone().cpu().render_pixels(&scene, &camera);
+ let gpu = gpu_renderer.render_pixels(&scene, &camera);
+ assert!(compare("instances", &cpu, &gpu) < 6.0);
+}
+
+#[test]
+fn gpu_normal_maps_match_cpu() {
+ let gpu_renderer = Renderer::new(960, 540);
+ if !gpu_renderer.uses_gpu() {
+ eprintln!("no GPU, skipped");
+ return;
+ }
+ let (scene, camera) = common::studs();
+ let cpu = gpu_renderer.clone().cpu().render_pixels(&scene, &camera);
+ let gpu = gpu_renderer.render_pixels(&scene, &camera);
+ assert!(compare("normal_map", &cpu, &gpu) < 4.0);
+}
+
+/// A miniature of a few millimeters at `origin`: a pebble with a rod over it on a plate,
+/// lit by a sun with a shadow. The camera is 3 cm away, so a pixel is about 40
+/// micrometers wide, as in a 4K close-up of a hand. The sun has a shadow map of `map_size`.
+fn miniature(origin: Vec3, map_size: u32) -> (Scene, Camera) {
+ let mut scene = Scene::new().environment(Environment::studio());
+ let at = |p: Vec3| origin + p;
+ scene.add(
+ Node::mesh(
+ Geometry::cuboid(0.03, 0.001, 0.03),
+ Material::standard(0x8a8f99).roughness(0.7),
+ )
+ .with_position(at(vec3(0.0, -0.0005, 0.0)))
+ .shadows(false, true),
+ );
+ scene.add(
+ Node::mesh(
+ Geometry::sphere(0.004, 20, 10),
+ Material::standard(0xd08850).roughness(0.45),
+ )
+ .with_position(at(vec3(0.0, 0.004, 0.0))),
+ );
+ scene.add(
+ Node::mesh(
+ Geometry::capsule(0.0012, 0.012, 8, 16),
+ Material::standard(0x5f8fd0).roughness(0.35),
+ )
+ .with_position(at(vec3(0.002, 0.011, 0.002)))
+ .with_rotation(Quat::from_rotation_z(1.3)),
+ );
+ scene.add(Node::light(
+ Light::directional(Rgb::WHITE, 3.0, vec3(-0.4, 1.0, 0.3)).with_shadow(Shadow {
+ map_size,
+ ..Shadow::default()
+ }),
+ ));
+ scene.add(Node::light(Light::hemisphere(0x9fb4d8, 0x30281f, 0.6)));
+ let camera = Camera::perspective(30.0)
+ .clip(0.002, 1.0)
+ .position(at(vec3(0.016, 0.016, 0.022)))
+ .look_at(at(vec3(0.0, 0.004, 0.0)));
+ (scene, camera)
+}
+
+/// In a close view the steps of the surface between two pixels are micrometers. The GPU
+/// must find the normal of the triangle from them, also far from the origin. A normal lost
+/// to the precision of 32 bit floats shows as dots along the triangle edges and as patches
+/// of wrong shadow.
+#[test]
+fn gpu_close_views_match_cpu() {
+ let gpu_renderer = Renderer::new(480, 320);
+ if !gpu_renderer.uses_gpu() {
+ eprintln!("no GPU, skipped");
+ return;
+ }
+ for (name, origin) in [
+ ("miniature", Vec3::ZERO),
+ ("miniature_far", vec3(70.0, 3.0, -45.0)),
+ ] {
+ let (scene, camera) = miniature(origin, 2048);
+ let cpu = gpu_renderer.clone().cpu().render_pixels(&scene, &camera);
+ let gpu = gpu_renderer.render_pixels(&scene, &camera);
+ compare(name, &cpu, &gpu);
+ // The wrong normals cover a few percent of the picture with strong errors.
+ let wrong = (cpu.rgba.as_chunks::<4>().0.iter())
+ .zip(gpu.rgba.as_chunks::<4>().0)
+ .filter(|(a, b)| a.iter().zip(*b).any(|(a, b)| a.abs_diff(*b) > 32))
+ .count();
+ let share = wrong as f32 / (cpu.width * cpu.height) as f32;
+ eprintln!("{name}: {:.3} % of the pixels differ", share * 100.0);
+ assert!(share < 0.005, "{name}");
+ }
+}
+
+/// A frame must not depend on the frames before it. The GPU keeps its frame contexts (the
+/// targets, the shadow maps, the buffers) between frames, and an earlier shot with larger
+/// shadow maps left them larger: the next shot was shaded with a finer shadow map than on
+/// the CPU, with acne along the triangles of a close-up.
+#[test]
+fn gpu_frames_do_not_depend_on_earlier_frames() {
+ // A size of its own, so that the other tests do not share the frame contexts.
+ let renderer = Renderer::new(410, 290);
+ if !renderer.uses_gpu() {
+ eprintln!("no GPU, skipped");
+ return;
+ }
+ let (scene, camera) = miniature(Vec3::ZERO, 2048);
+ let fresh = renderer.render_pixels(&scene, &camera);
+ // Another shot with a larger shadow map and motion blur.
+ let (other, other_camera) = miniature(vec3(1.0, 0.0, 0.0), 8192);
+ let _ = renderer.render_motion_blur_pixels(3, |o| (other.clone(), other_camera.fov(30.0 + o)));
+ let after = renderer.render_pixels(&scene, &camera);
+ compare("after_other_shot", &fresh, &after);
+ assert_eq!(fresh.rgba, after.rgba);
+}
+
+/// A shadow light with small bounds far from the origin, and a caster far above them,
+/// beyond the near plane of the shadow camera. The caster still throws its shadow.
+#[test]
+fn gpu_casters_beyond_the_shadow_bounds_cast() {
+ let renderer = Renderer::new(320, 240);
+ if !renderer.uses_gpu() {
+ eprintln!("no GPU, skipped");
+ return;
+ }
+ let origin = vec3(70.0, 2.0, -12.0);
+ let mut scene = Scene::new();
+ scene.add(
+ Node::mesh(
+ Geometry::cuboid(0.7, 0.02, 0.7),
+ Material::standard(0xb0b0b0).roughness(0.8),
+ )
+ .with_position(origin - Vec3::Y * 0.01),
+ );
+ // 5 m over the plate. The shadow camera starts about 1 m over it.
+ scene.add(
+ Node::mesh(
+ Geometry::cuboid(0.3, 0.05, 0.3),
+ Material::standard(0x808080),
+ )
+ .with_position(origin + Vec3::Y * 5.0),
+ );
+ scene.add(Node::light(
+ Light::directional(Rgb::WHITE, 3.0, Vec3::Y).with_shadow(Shadow {
+ bounds: Some(Aabb {
+ min: origin - Vec3::splat(0.35),
+ max: origin + Vec3::splat(0.35),
+ }),
+ ..Shadow::default()
+ }),
+ ));
+ scene.add(Node::light(Light::ambient(Rgb::WHITE, 0.3)));
+ let camera = Camera::perspective(40.0)
+ .position(origin + vec3(0.0, 1.2, 0.9))
+ .look_at(origin);
+ let cpu = renderer.clone().cpu().render_pixels(&scene, &camera);
+ let gpu = renderer.render_pixels(&scene, &camera);
+ assert!(compare("far_caster", &cpu, &gpu) < 1.0);
+ let center = camera.project(origin, 320.0, 240.0).unwrap();
+ let corner = camera
+ .project(origin + vec3(0.3, 0.0, 0.3), 320.0, 240.0)
+ .unwrap();
+ for (name, pixels) in [("cpu", &cpu), ("gpu", &gpu)] {
+ let luma = |p: Vec3| {
+ let i = ((p.y as u32 * pixels.width + p.x as u32) * 4) as usize;
+ pixels.rgba[i..i + 3]
+ .iter()
+ .map(|&c| f32::from(c))
+ .sum::<f32>()
+ };
+ let (shaded, lit) = (luma(center), luma(corner));
+ eprintln!("{name}: under the caster {shaded}, in the light {lit}");
+ assert!(shaded < lit * 0.6, "{name}: {shaded} {lit}");
+ }
+}
diff --git a/fframes-three-d/tests/render.rs b/fframes-three-d/tests/render.rs
new file mode 100644
index 00000000..13149b98
--- /dev/null
+++ b/fframes-three-d/tests/render.rs
@@ -0,0 +1,273 @@
+#![allow(clippy::unreadable_literal)]
+
+use fframes_three_d::*;
+
+mod common;
+use common::{cubes, save, showcase, studs};
+
+#[test]
+fn renders_showcase() {
+ let (scene, camera) = showcase();
+ let start = std::time::Instant::now();
+ let pixels = Renderer::new(1920, 1080)
+ .bloom(Bloom::default())
+ .render_pixels(&scene, &camera);
+ eprintln!("showcase 1080p: {:?}", start.elapsed());
+ save("showcase", &pixels);
+ // The environment background is opaque.
+ assert_eq!(pixels.get(5, 5)[3], 255);
+}
+
+#[test]
+fn renders_text_with_holes() {
+ let Ok(font) = std::fs::read(concat!(
+ env!("CARGO_MANIFEST_DIR"),
+ "/../examples/conference-splash-screen/media/Inter_18pt-ExtraBold.ttf"
+ )) else {
+ return;
+ };
+ let text = Geometry::text(&font, "fframes aeo8B", 1.0, 0.25, 0.03).unwrap();
+ let b = text.bounds();
+ let mut scene = Scene::new()
+ .environment(Environment::studio())
+ .background(Background::Color(Rgb::hex(0xf2f2f0)));
+ scene.add(
+ Node::mesh(
+ text,
+ Material::standard(0x141414).roughness(0.3).clearcoat(1.0),
+ )
+ .at(-b.center().x, 0.0, 0.0),
+ );
+ scene.add(Node::light(Light::sun(
+ Rgb::WHITE,
+ 2.5,
+ vec3(2.0, 5.0, 4.0),
+ )));
+ let camera = Camera::perspective(30.0)
+ .at(0.0, 0.35, 5.5)
+ .look_at(vec3(0.0, 0.35, 0.0));
+ let pixels = Renderer::new(1600, 400).render_pixels(&scene, &camera);
+ save("text", &pixels);
+ assert!(b.size().x > 5.0);
+}
+
+#[test]
+fn renders_depth_of_field() {
+ let (scene, camera) = showcase();
+ let camera = camera.focus_on(vec3(-0.8, 0.6, 0.6), 14.0);
+ let start = std::time::Instant::now();
+ let pixels = Renderer::new(1920, 1080).render_pixels(&scene, &camera);
+ eprintln!("depth of field 1080p: {:?}", start.elapsed());
+ save("depth_of_field", &pixels);
+}
+
+/// Renders an STL file into `stl.png` with the lighting of the showcase. Run it with
+/// `FFRAMES_3D_STL=model.stl cargo test -p fframes_three_d --test render renders_an_stl -- --nocapture`.
+#[test]
+fn renders_an_stl() {
+ let Ok(path) = std::env::var("FFRAMES_3D_STL") else {
+ return;
+ };
+ let bytes = std::fs::read(&path).unwrap();
+ let geometry = Geometry::from_stl(&bytes).unwrap().smooth(40.0);
+ // Fits the model into a 1.6 m box on the floor, for all units and up axes.
+ let bounds = geometry.bounds();
+ let size = bounds.size().max_element();
+ let geometry = geometry
+ .translate(-bounds.center().x, -bounds.min.y, -bounds.center().z)
+ .scale(1.6 / size, 1.6 / size, 1.6 / size);
+ eprintln!(
+ "{path}: {} triangles, {} vertices after smoothing",
+ geometry.triangle_count(),
+ geometry.vertex_count()
+ );
+ let mut scene = Scene::new()
+ .environment(Environment::studio())
+ .reflector(Reflector::floor());
+ scene.add(Node::mesh(
+ Geometry::floor(20.0, 20.0),
+ Material::standard(0x2a2c30).roughness(0.35).reflection(0.6),
+ ));
+ scene.add(Node::mesh(
+ geometry,
+ Material::standard(0xd8d2c4).roughness(0.4).clearcoat(0.6),
+ ));
+ scene.add(Node::light(Light::sun(
+ Rgb::WHITE,
+ 2.5,
+ vec3(2.0, 5.0, 3.0),
+ )));
+ let camera = Camera::perspective(32.0)
+ .at(2.2, 1.6, 3.0)
+ .look_at(vec3(0.0, 0.7, 0.0));
+ let pixels = Renderer::new(960, 540)
+ .bloom(Bloom::default())
+ .render_pixels(&scene, &camera);
+ save("stl", &pixels);
+}
+
+#[test]
+fn instances_render_like_separate_meshes() {
+ let renderer = Renderer::new(480, 270).cpu();
+ let (instanced, camera) = cubes(true);
+ let (separate, _) = cubes(false);
+ let a = renderer.render_pixels(&instanced, &camera);
+ let b = renderer.render_pixels(&separate, &camera);
+ save("instances", &a);
+ let diff = a
+ .rgba
+ .iter()
+ .zip(&b.rgba)
+ .map(|(x, y)| f64::from(x.abs_diff(*y)))
+ .sum::<f64>()
+ / a.rgba.len() as f64;
+ eprintln!("instances against separate meshes: mean difference {diff:.3} / 255");
+ assert!(diff < 0.1, "{diff}");
+}
+
+#[test]
+fn renders_normal_maps() {
+ let renderer = Renderer::new(960, 540).cpu();
+ let (scene, camera) = studs();
+ let bumpy = renderer.render_pixels(&scene, &camera);
+ save("normal_map", &bumpy);
+ let mut flat = scene.clone();
+ for (id, _) in scene.nodes() {
+ if let Object::Mesh(mesh) = &mut flat[id].object {
+ mesh.material.normal_map = None;
+ }
+ }
+ let flat = renderer.render_pixels(&flat, &camera);
+ let diff = bumpy
+ .rgba
+ .iter()
+ .zip(&flat.rgba)
+ .map(|(a, b)| f64::from(a.abs_diff(*b)))
+ .sum::<f64>()
+ / bumpy.rgba.len() as f64;
+ eprintln!("normal map changes the frame by {diff:.2} / 255 on average");
+ assert!(diff > 2.0);
+}
+
+#[test]
+fn textures_from_fframes_images() {
+ use fframes_media::{ImageData, ImageMetadata};
+ use usvgr::PreloadedImageData;
+
+ // a red texel at half coverage next to an opaque blue one
+ let data = PreloadedImageData::new("pair".into(), 2, 1, &[255, 0, 0, 128, 0, 0, 255, 255]);
+ let image = ImageData::new_from_raw_data(
+ std::sync::Arc::new(data),
+ "pair".into(),
+ ImageMetadata {
+ width: 2,
+ height: 1,
+ },
+ );
+ let texture = Texture::from_image(&image);
+ let red = texture.sample(vec2(0.25, 0.5));
+ let blue = texture.sample(vec2(0.75, 0.5));
+ assert!(red.x > 0.95 && red.y < 0.05, "{red}");
+ assert!((red.w - 0.5).abs() < 0.01, "{red}");
+ assert!(blue.z > 0.95 && blue.x < 0.05, "{blue}");
+}
+
+/// A blended particle covers only its opacity: a faint dark puff must not draw as a dark
+/// disc. Both renderers (the GPU one when the `gpu` feature finds a GPU).
+#[test]
+fn faint_particles_stay_faint() {
+ let mut scene = Scene::new().background(Background::Color(Rgb::hex(0x808080)));
+ scene.add(Node::particles(
+ vec![Particle::new(Vec3::ZERO, 1.0, Rgb::hex(0x000000)).opacity(0.1)],
+ Blending::Normal,
+ ));
+ let camera = Camera::perspective(40.0)
+ .at(0.0, 0.0, 6.0)
+ .look_at(Vec3::ZERO);
+ let renderer = Renderer::new(200, 200);
+ for renderer in [renderer.clone(), renderer.cpu()] {
+ let pixels = renderer.render_pixels(&scene, &camera);
+ let (center, corner) = (pixels.get(100, 100)[0], pixels.get(5, 5)[0]);
+ assert!(
+ f32::from(center) > 0.8 * f32::from(corner),
+ "center {center}, background {corner}"
+ );
+ }
+}
+
+/// An opaque material covers its pixels whatever the alpha of its texture, as in three.js.
+/// Both renderers (the GPU one when the `gpu` feature finds a GPU).
+#[test]
+fn opaque_surfaces_ignore_texture_alpha() {
+ let clear = Texture::from_rgba8(1, 1, &[255, 255, 255, 0], true);
+ let mut scene = Scene::new();
+ scene.add(Node::mesh(
+ Geometry::plane(4.0, 4.0),
+ Material::unlit(0x808080).map(clear),
+ ));
+ let camera = Camera::perspective(40.0).at(0.0, 0.0, 3.0);
+ let renderer = Renderer::new(64, 64);
+ for renderer in [renderer.clone(), renderer.cpu()] {
+ let pixels = renderer.render_pixels(&scene, &camera);
+ assert_eq!(pixels.get(32, 32)[3], 255, "gpu: {}", renderer.uses_gpu());
+ }
+}
+
+/// A camera at its target (an orbit of radius 0) still gives a picture, not NaN.
+#[test]
+fn camera_at_its_target_renders() {
+ let mut scene = Scene::new().background(Background::Color(Rgb::hex(0x336699)));
+ scene.add(
+ Node::mesh(Geometry::cuboid(1.0, 1.0, 1.0), Material::unlit(0xffffff)).at(0.0, 0.0, -3.0),
+ );
+ let camera = Camera::perspective(40.0).orbit(Vec3::ZERO, 0.0, 0.0, 0.0);
+ assert!(camera.view_matrix().is_finite());
+ let pixels = Renderer::new(64, 64).cpu().render_pixels(&scene, &camera);
+ // it looks down -Z, at the white box in front of the blue background
+ let (center, corner) = (pixels.get(32, 32), pixels.get(1, 1));
+ assert!(center[0] > 200 && center[0] == center[2], "{center:?}");
+ assert!(corner[2] > corner[0], "{corner:?}");
+}
+
+/// An orthographic camera leaves out a particle behind it and blends transparent surfaces
+/// from back to front, like a perspective camera. Both renderers.
+#[test]
+fn orthographic_cameras_cull_and_order_like_perspective_ones() {
+ let mut scene = Scene::new().background(Background::Color(Rgb::hex(0x000000)));
+ // behind the camera: a big white glow that must not show
+ scene.add(Node::particles(
+ vec![Particle::new(Vec3::new(0.0, 0.0, 8.0), 3.0, Rgb::WHITE)],
+ Blending::Additive,
+ ));
+ // the near blue plane comes first in the scene, so the renderer has to sort
+ scene.add(
+ Node::mesh(
+ Geometry::plane(4.0, 4.0),
+ Material::unlit(0x0000ff).opacity(0.5),
+ )
+ .at(0.0, 0.0, 1.0),
+ );
+ scene.add(
+ Node::mesh(
+ Geometry::plane(4.0, 4.0),
+ Material::unlit(0xff0000).opacity(0.5),
+ )
+ .at(0.0, 0.0, -1.0),
+ );
+ let camera = Camera::orthographic(6.0).at(0.0, 0.0, 5.0);
+ let renderer = Renderer::new(64, 64).tone_mapping(ToneMapping::Linear);
+ for renderer in [renderer.clone(), renderer.cpu()] {
+ let pixels = renderer.render_pixels(&scene, &camera);
+ let [r, g, b, _] = pixels.get(32, 32);
+ assert!(
+ g < 8,
+ "gpu: {}, the particle shows: {r} {g} {b}",
+ renderer.uses_gpu()
+ );
+ assert!(
+ b > r,
+ "gpu: {}, red in front of blue: {r} {g} {b}",
+ renderer.uses_gpu()
+ );
+ }
+}
diff --git a/fframes-three-d/tests/shadow.rs b/fframes-three-d/tests/shadow.rs
new file mode 100644
index 00000000..72997d52
--- /dev/null
+++ b/fframes-three-d/tests/shadow.rs
@@ -0,0 +1,96 @@
+//! A moving shadow box must not change the frame: shadow maps stay still in the world, so
+//! shadow edges do not crawl when the box follows the camera.
+#![allow(clippy::unreadable_literal)]
+
+use fframes_three_d::*;
+
+#[allow(dead_code)]
+mod common;
+
+/// The mean brightness of the blocks of 8 x 8 pixels, so that the rounding to 8 bits
+/// averages out.
+fn blocks(p: &Pixels) -> Vec<f64> {
+ let (w, h) = (p.width as usize / 8, p.height as usize / 8);
+ let mut out = vec![0.0; w * h];
+ for y in 0..h * 8 {
+ for x in 0..w * 8 {
+ let i = (y * p.width as usize + x) * 4;
+ let sum: f64 = p.rgba[i..i + 3].iter().map(|&v| f64::from(v)).sum();
+ out[(y / 8) * w + x / 8] += sum / (3.0 * 64.0);
+ }
+ }
+ out
+}
+
+/// The mean of `|a - b|`.
+fn difference(a: &[f64], b: &[f64]) -> f64 {
+ a.iter().zip(b).map(|(a, b)| (a - b).abs()).sum::<f64>() / a.len() as f64
+}
+
+/// A box on a floor in the sun, with the shadow bounds around the point `center`.
+fn shadowed_box(center: Vec3) -> (Scene, Camera) {
+ let mut scene = Scene::new().background(Background::Color(Rgb::hex(0x202020)));
+ let grey = Material::standard(0x909090).roughness(0.8);
+ scene.add(Node::mesh(Geometry::floor(20.0, 20.0), grey.clone()));
+ scene.add(Node::mesh(Geometry::cuboid(1.0, 1.0, 1.0), grey).at(0.3, 0.5, 0.0));
+ scene.add(Node::light(
+ Light::directional(Rgb::WHITE, 3.0, vec3(-3.0, 2.5, 1.0)).with_shadow(Shadow {
+ map_size: 256,
+ bounds: Some(Aabb {
+ min: center - vec3(6.0, 1.0, 6.0),
+ max: center + vec3(6.0, 2.0, 6.0),
+ }),
+ ..Default::default()
+ }),
+ ));
+ let camera = Camera::perspective(40.0)
+ .at(3.0, 4.0, 5.0)
+ .look_at(vec3(0.3, 0.0, 0.0));
+ (scene, camera)
+}
+
+/// Moves the shadow box by a fraction of a texel, as a box that follows the camera does.
+fn shadow_change(renderer: &Renderer) -> f64 {
+ // the map is 256 texels over about 16 m: one texel is about 6 cm
+ let (scene, camera) = shadowed_box(vec3(0.0, 0.0, 0.0));
+ let a = renderer.render_pixels(&scene, &camera);
+ let (scene, camera) = shadowed_box(vec3(0.013, 0.004, -0.009));
+ let b = renderer.render_pixels(&scene, &camera);
+ common::save("temporal_shadow", &a);
+ // the shadow is in the frame
+ let mut unshadowed = scene;
+ for (id, _) in unshadowed.clone().nodes() {
+ if let Object::Light(Light::Directional(light)) = &mut unshadowed[id].object {
+ light.shadow = None;
+ }
+ }
+ let unshadowed = renderer.render_pixels(&unshadowed, &camera);
+ let shadow = difference(&blocks(&b), &blocks(&unshadowed));
+ assert!(shadow > 1.0, "{shadow}");
+ a.rgba
+ .iter()
+ .zip(&b.rgba)
+ .map(|(a, b)| f64::from(a.abs_diff(*b)))
+ .sum::<f64>()
+ / a.rgba.len() as f64
+}
+
+#[test]
+fn shadow_map_stays_still_when_its_box_moves() {
+ let change = shadow_change(&Renderer::new(320, 180).cpu());
+ eprintln!("cpu: a box moved by a fraction of a texel changes the frame by {change:.4} / 255");
+ assert!(change == 0.0, "{change}");
+}
+
+#[cfg(feature = "gpu")]
+#[test]
+fn gpu_shadow_map_stays_still_when_its_box_moves() {
+ let renderer = Renderer::new(320, 180);
+ if !renderer.uses_gpu() {
+ eprintln!("no GPU, skipped");
+ return;
+ }
+ let change = shadow_change(&renderer);
+ eprintln!("gpu: a box moved by a fraction of a texel changes the frame by {change:.4} / 255");
+ assert!(change == 0.0, "{change}");
+}
diff --git a/fframes/Cargo.toml b/fframes/Cargo.toml
index 03df1209..a4e14e00 100644
--- a/fframes/Cargo.toml
+++ b/fframes/Cargo.toml
@@ -39,6 +39,7 @@ svgr-macro.workspace = true
fframes-media.workspace = true
fframes-media-dir-macro.workspace = true
kamadak-exif.workspace = true
+fframes_three_d = { workspace = true, optional = true }
# these are renderer/encoder specific dependnecies
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
@@ -72,6 +73,11 @@ exif = ["fframes-media/exif", "fframes-media-dir-macro/exif"]
compile-time-svgtree = ["svgr-macro/compile-time-svgtree"]
# `fframes::Lottie` and `frame.play_lottie`: Lottie `.json` files in the media folder
lottie = ["dep:velato", "dep:kurbo", "dep:peniko", "dep:serde_json", "fframes-media-dir-macro/lottie"]
+# `fframes::three_d`: 3D scenes with the building blocks of three.js (the fframes_three_d crate)
+3d = ["dep:fframes_three_d"]
+# `fframes::wgpu_layer`: textures rendered with wgpu on the GPU of the rendering backend go
+# into frames without leaving the GPU. With `3d`, the 3D renders with wgpu.
+wgpu = ["fframes-media/wgpu", "fframes_three_d?/gpu"]
# Keep FFmpeg source fallbacks portable, including compile-time media decoding.
# Enable on native non-Windows targets; Windows uses a shared FFmpeg installation.
@@ -101,7 +107,7 @@ libav-agree-version3 = ["fframes-media/libav-agree-version3"]
# The codec and hardware features compile FFmpeg from source, which docs.rs cannot do (no
# network), so only the pure Rust features are documented. `--cfg fframes_docsrs` makes
# fframes-media link the FFmpeg headers of the docs.rs image instead of building FFmpeg.
-features = ["cli", "compile-time-svgtree", "exif"]
+features = ["cli", "compile-time-svgtree", "exif", "3d"]
rustc-args = ["--cfg", "fframes_docsrs"]
[lints]
diff --git a/fframes/src/color.rs b/fframes/src/color.rs
index 7344033c..4cc79d5e 100644
--- a/fframes/src/color.rs
+++ b/fframes/src/color.rs
@@ -254,6 +254,23 @@ impl From<Color> for ColorF32 {
}
}
+/// The 3D color of an sRGB color, for materials and lights in [`crate::three_d`].
+#[cfg(feature = "3d")]
+impl From<Color> for fframes_three_d::Rgb {
+ fn from(color: Color) -> Self {
+ fframes_three_d::Rgb::srgb8(color.r, color.g, color.b)
+ }
+}
+
+/// The sRGB color of a 3D color, clamped to `0..1`: an SVG overlay in the color of a material.
+#[cfg(feature = "3d")]
+impl From<fframes_three_d::Rgb> for Color {
+ fn from(color: fframes_three_d::Rgb) -> Self {
+ let [r, g, b] = color.to_srgb8();
+ Color::rgb(r, g, b)
+ }
+}
+
impl animation::Animatable for Color {
fn apply_progress(&self, to: &Self, progress: f32) -> Self {
let from = ColorF32::from(*self);
diff --git a/fframes/src/lib.rs b/fframes/src/lib.rs
index ba47882b..720f913f 100644
--- a/fframes/src/lib.rs
+++ b/fframes/src/lib.rs
@@ -84,6 +84,10 @@
//! - `compile-time-svgtree`: [`svgr!`] builds the SVG tree at compile time and hashes static
//! subtrees. Required by the Skia backend and by [`Shader`].
//! - `exif`: EXIF orientation of loaded images.
+//! - `3d`: [`three_d`], 3D scenes with the building blocks of three.js, rendered into an
+//! `<image>` of the frame. Runs on the CPU, also in the editor.
+//! - `wgpu`: `wgpu_layer` puts textures rendered with wgpu into frames, and the Skia
+//! Vulkan backend draws them without a readback. With `3d`, the 3D renders on the GPU.
//! - Codecs `h264`, `h265`, `aac`, `mp3lame`, `opus`, `vpx`: compile the library into the static
//! `FFmpeg` build. Some of them need `libav-agree-gpl`, `libav-agree-nonfree` or
//! `libav-agree-version3`, which state that you accept the corresponding `FFmpeg` license terms.
@@ -151,6 +155,10 @@ pub use font_data::*;
pub use frame::*;
#[cfg(feature = "lottie")]
pub use lottie::*;
+#[cfg(all(feature = "wgpu", not(target_arch = "wasm32")))]
+pub use media::wgpu;
+#[cfg(all(feature = "wgpu", not(target_arch = "wasm32")))]
+pub use media::wgpu_layer::*;
pub use media_provider::*;
pub use named_range::*;
pub use scenes::*;
@@ -176,5 +184,8 @@ pub use serde;
pub use ttf_parser;
pub use usvgr;
+#[cfg(feature = "3d")]
+#[doc(inline)]
+pub use fframes_three_d as three_d;
#[cfg(feature = "exif")]
pub use media::exif;
diff --git a/fframes/src/shader.rs b/fframes/src/shader.rs
index b6c121b2..0b17ba2c 100644
--- a/fframes/src/shader.rs
+++ b/fframes/src/shader.rs
@@ -240,90 +240,20 @@ pub fn resolve_shader_draw(image: &Arc<usvgr::PreloadedImageData>) -> Option<Arc
#[cfg(not(target_arch = "wasm32"))]
mod registry {
- use std::collections::HashMap;
- use std::sync::atomic::{AtomicU64, Ordering};
- use std::sync::{Arc, Mutex, Weak};
-
use super::ShaderDraw;
- use crate::media::{ImageData, ImageMetadata};
-
- const MARKER_PREFIX: &str = "fframes-shader:";
- /// A single transparent pixel: renderers that do not execute shaders draw
- /// nothing in their place.
- static MARKER_PIXEL: [u8; 4] = [0, 0, 0, 0];
- /// Dead entries are swept every this many insertions.
- const SWEEP_INTERVAL: usize = 256;
-
- struct Entry {
- image: Weak<usvgr::PreloadedImageData>,
- draw: Arc<ShaderDraw>,
- }
-
- #[derive(Default)]
- struct Registry {
- entries: HashMap<usize, Entry>,
- inserts: usize,
- }
+ use crate::media::ImageData;
+ use crate::media::markers::Markers;
- static REGISTRY: Mutex<Option<Registry>> = Mutex::new(None);
- static NEXT_MARKER: AtomicU64 = AtomicU64::new(0);
+ static MARKERS: Markers<ShaderDraw> = Markers::new("fframes-shader:");
pub(super) fn create_marker(draw: ShaderDraw) -> ImageData<'static> {
- // Unique per draw so no id-keyed cache can hand a previous frame's
- // placeholder (and so its uniforms) to this one.
- let sequence = NEXT_MARKER.fetch_add(1, Ordering::Relaxed);
- let id = format!("{MARKER_PREFIX}{}:{sequence}", draw.shader.id());
- let image = Arc::new(usvgr::PreloadedImageData {
- data: std::borrow::Cow::Borrowed(&MARKER_PIXEL),
- width: 1,
- height: 1,
- id: id.clone(),
- });
-
- let mut guard = REGISTRY
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- let registry = guard.get_or_insert_with(Registry::default);
- registry.inserts += 1;
- if registry.inserts.is_multiple_of(SWEEP_INTERVAL) {
- registry
- .entries
- .retain(|_, entry| entry.image.strong_count() > 0);
- }
- registry.entries.insert(
- Arc::as_ptr(&image) as usize,
- Entry {
- image: Arc::downgrade(&image),
- draw: Arc::new(draw),
- },
- );
- drop(guard);
-
- ImageData::new_from_raw_data(
- image,
- id,
- ImageMetadata {
- width: 1,
- height: 1,
- },
- )
+ MARKERS.create(draw, 1, 1)
}
- pub(super) fn resolve(image: &Arc<usvgr::PreloadedImageData>) -> Option<Arc<ShaderDraw>> {
- // Cheap reject for every regular image without touching the lock.
- if !image.id.starts_with(MARKER_PREFIX) {
- return None;
- }
-
- let guard = REGISTRY
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- let entry = guard
- .as_ref()?
- .entries
- .get(&(Arc::as_ptr(image) as usize))?;
-
- Weak::ptr_eq(&entry.image, &Arc::downgrade(image)).then(|| Arc::clone(&entry.draw))
+ pub(super) fn resolve(
+ image: &std::sync::Arc<usvgr::PreloadedImageData>,
+ ) -> Option<std::sync::Arc<ShaderDraw>> {
+ MARKERS.resolve(image)
}
}
diff --git a/scripts/build-skills-index.mjs b/scripts/build-skills-index.mjs
index 2604fcc0..a5353ee8 100644
--- a/scripts/build-skills-index.mjs
+++ b/scripts/build-skills-index.mjs
@@ -1,6 +1,6 @@
#!/usr/bin/env node
// Publishes skills/ on fframes.studio as an agent-skills well-known index, so
-// `npx skills add https://fframes.studio` downloads four markdown files instead of
+// `npx skills add https://fframes.studio` downloads a few markdown files instead of
// cloning the whole repository with its example media. Runs as the wrangler build
// step (see wrangler.jsonc); the output directory is generated and gitignored.
import { cpSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
diff --git a/scripts/publish.sh b/scripts/publish.sh
index cc46d72d..a16ccaad 100755
--- a/scripts/publish.sh
+++ b/scripts/publish.sh
@@ -25,6 +25,7 @@ for crate in \
svgr-macro \
fframes-media \
media-dir-macro \
+ fframes-three-d \
fframes \
fframes-editor-controller \
fframes-skia-renderer \
diff --git a/skills/fframes-video/SKILL.md b/skills/fframes-video/SKILL.md
index 69964886..84147446 100644
--- a/skills/fframes-video/SKILL.md
+++ b/skills/fframes-video/SKILL.md
@@ -5,10 +5,10 @@ description: >-
encoding, Skia GPU rendering). Use whenever the user wants a video, animation, motion graphic,
explainer, promo, social clip, title card, podcast visual, lyric/caption video or any rendered
.mp4/.webm made programmatically, or asks to change, fix, speed up or check an fframes video.
- Covers installing fframes, creating a project, designing good-looking motion, sound (music,
- voice, SFX, loudness), watching it in a real-time preview window, and checking the result
- without watching it: frames and contact sheets as PNG, automatic problem detection, loudness
- numbers, fast draft and range renders.
+ Covers installing fframes, creating a project, designing good-looking motion, 3D shots
+ (`fframes::three_d`, three.js style scenes), sound (music, voice, SFX, loudness), watching it in a
+ real-time preview window, and checking the result without watching it: frames and contact
+ sheets as PNG, automatic problem detection, loudness numbers, fast draft and range renders.
---
# Making videos with fframes
@@ -22,7 +22,8 @@ and ffmpeg encodes the result.
Each project gets a command line (from `fframes::cli`). Use it for everything: render a video,
open the real-time preview window, and look at frames, contact sheets and loudness numbers as
files you can read. Read `references/design.md` before designing, `references/api.md` while
-writing code and `references/audio.md` for sound.
+writing code, `references/audio.md` for sound and `references/3d.md` for 3D shots
+(`fframes::three_d`).
When matching a supplied video, first follow the reference-analysis guidance in
`references/design.md`. Its cuts, pacing and motion take precedence over the design defaults
@@ -273,6 +274,9 @@ impl Video for MyVideo<'_> {
- GPU shaders (SkSL or Shadertoy GLSL) run on the Skia backend through `fframes::Shader`; they
take images and synced video frames as input (green-screen keying, color grading). See
`references/api.md`.
+- 3D shots (products, devices, logos in a material, camera moves through a set) come from
+ `fframes::three_d` (feature `3d`), a three.js style scene graph that renders into an `<image>` with SVG below
+ and above it. Build the scene once, pose it per frame. See `references/3d.md`.
## 5. Making it look good
diff --git a/skills/fframes-video/references/3d.md b/skills/fframes-video/references/3d.md
new file mode 100644
index 00000000..53007eb4
--- /dev/null
+++ b/skills/fframes-video/references/3d.md
@@ -0,0 +1,179 @@
+# 3D in fframes videos (`fframes::three_d`)
+
+`fframes::three_d` (the `fframes_three_d` crate, feature `3d`) is a three.js style scene graph
+with its own renderer. It renders a frame of a 3D scene into an image for an `<image href>`
+in the `svgr!` tree, so SVG can go below it, above it and around it like with any image.
+Read the crate docs (`fframes::three_d` on docs.rs, or `fframes-three-d/src/lib.rs`) for the full
+API and the three.js name of every type.
+
+Use 3D when depth, light or a moving camera is the point: a product shot, a device that
+assembles, a logo in a real material, a camera move through a set. Titles, cards, charts and UI
+stay SVG: they are sharper, cached across frames and much cheaper. A good 3D video usually is
+an SVG video with one or two 3D shots, or a 3D shot with SVG text over it.
+
+The repository's [arm example](https://github.com/dmtrKovalenko/fframes/tree/main/examples/arm)
+is a 37 second film that uses most of the crate. Its `src/effects.rs` builds camera shake, a
+light beam in hazy air, spark streaks and a printed grid from the building blocks.
+
+## Setup
+
+```toml
+[dependencies]
+# `3d`: fframes::three_d; `wgpu`: the 3D renders on the GPU
+fframes = { version = "<the version of fframes>", features = ["3d", "wgpu"] }
+```
+
+| backend of the video | where the 3D renders |
+| --- | --- |
+| Skia on Vulkan (Linux, Windows) with `fframes_skia_renderer = { features = ["vulkan", "wgpu"] }` | on Skia's own GPU device. The 3D frame is a texture that Skia draws in place, nothing is read back |
+| Skia on Metal (macOS), Skia on Vulkan without `wgpu` | on the GPU through wgpu (Metal, Vulkan, DX12), read back as pixels (a few ms per 1080p frame) |
+| the CPU backend, or no usable GPU | the CPU rasterizer, 60 to 150 ms per 1080p frame on 28 threads |
+| the web editor (wasm) | the CPU rasterizer at half size |
+
+Without the `wgpu` feature everything renders on the CPU. `Renderer::cpu()` forces the CPU for
+one renderer. With a GPU, a 1080p frame with shadows, reflections, depth of field and 4x
+MSAA takes 5 to 20 ms on an integrated GPU; the arm film (2216 frames) renders in 14 s on an
+M4 Max.
+
+## The pattern: build once, pose per frame
+
+```rust
+use fframes::three_d::*;
+
+pub struct ProductShot {
+ scene: Scene,
+ hinge: NodeId,
+ renderer: Renderer,
+}
+
+impl ProductShot {
+ pub fn new() -> Self {
+ // Everything heavy happens once: geometry, textures, fonts, models.
+ let mut scene = Scene::new()
+ .environment(Environment::studio())
+ .background(Background::Transparent); // the SVG behind shows through
+ let body = scene.add(
+ Node::mesh(Geometry::rounded_box(1.2, 0.5, 0.8, 0.06, 4), Material::metal(0xc9ccd1, 0.3))
+ .at(0.0, 0.25, 0.0),
+ );
+ // A group at the back edge is the hinge: the lid turns around it, not its center.
+ let hinge = scene.add_to(body, Node::group().at(0.0, 0.25, -0.4));
+ scene.add_to(hinge, Node::mesh(
+ Geometry::rounded_box(1.2, 0.08, 0.8, 0.03, 3),
+ Material::standard(0xff4a00).roughness(0.35).clearcoat(1.0),
+ ).at(0.0, 0.04, 0.4));
+ // Only shadows: the floor itself stays invisible over the SVG background.
+ scene.add(Node::mesh(Geometry::floor(20.0, 20.0), Material::shadow_catcher(0.5)).shadows(false, true));
+ scene.add(Node::light(Light::sun(Rgb::WHITE, 2.5, vec3(2.0, 6.0, 3.0))));
+ let renderer = Renderer::new(1920, 1080).tone_mapping(ToneMapping::Neutral).bloom(Bloom::default());
+ Self { scene, hinge, renderer }
+ }
+
+ pub fn image(&self, t: f32, open: f32) -> fframes::media::ImageData<'static> {
+ // Per frame: clone (the geometry is shared by `Arc`), pose, render.
+ let mut scene = self.scene.clone();
+ scene[self.hinge].rotation = euler(-open * deg(70.0), 0.0, 0.0);
+ let camera = Camera::perspective(30.0)
+ .orbit(vec3(0.0, 0.3, 0.0), 4.5, 25.0 + t * 8.0, 18.0)
+ .focus_on(vec3(0.0, 0.3, 0.0), 4.0);
+ self.renderer.render(&scene, &camera)
+ }
+}
+```
+
+In `render_frame`: `let image = self.shot.image(t, frame.animate(&self.open));` then
+`<image href={image.href()} x="0" y="0" width="1920" height="1080" />`.
+
+- Y is up, the camera looks down -Z, units are meters, angles are radians (`deg()`,
+ `euler_deg()`). Hex and `&str` colors are sRGB. Multiply an `Rgb` above 1 for light that
+ blooms (`Rgb::hex(0x22e8ff) * 6.0`).
+- Keep the `NodeId`s of everything you animate. A child turns around its parent's origin, so
+ put a group where the pivot is (a hinge, a joint). Set `position`, `rotation`, `scale`,
+ `visible`, a material's `emissive_intensity` or `opacity`, or a light's `intensity_mut()`.
+- Drive poses and the camera with the same tools as the SVG: `frame.animate(&timeline)` with
+ `f32` values, springs, and the time constants the sound uses. A turntable is
+ `orbit(target, distance, azimuth_degrees, elevation_degrees)` with an animated azimuth.
+- `Camera::focus_on(point, blur)` adds depth of field (blur in pixels at 1080p; 4 to 9 is
+ natural, 16 is macro). `Renderer::render_motion_blur(3, |o| build(t + o * 0.5 / FPS))`
+ blurs fast shots with a half open shutter; use it only where things move fast.
+
+## Composing 3D with the rest of the video
+
+- **Layers.** `Background::Transparent` (the default) lets the SVG behind show through, so
+ gradients, photos and brand backgrounds stay SVG. `Material::shadow_catcher` on a floor
+ keeps only the shadows, and the object sits on the SVG. Text and UI go above the `<image>`.
+- **Insets.** A 3D object in part of the frame gets a renderer of that size
+ (`Renderer::new(600, 600)`) and `<image x=.. y=.. width="600" height="600">`. Do not render
+ a full frame for a small box.
+- **SVG on 3D.** `camera.project(world_point, w, h)` gives the pixel of a 3D point in the
+ renderer's image (`None` behind the camera) and `camera.pixel_size(point, meters, h)` sizes
+ a bracket. Add the `<image>`'s `x`/`y` and scale by `width / w` when the image is not full
+ frame. `scene.local_to_world(id, local)` and `scene.world_position(id)` find the point on an
+ animated node. Labels then stay on the object while the camera moves.
+- **Transforms, clips, opacity.** The `<image>` is an image: `opacity`, `transform`,
+ `clip-path` and masks apply to it like to a photo, also on the GPU path. Cross-fade or wipe
+ a 3D shot with them.
+- **Scenes.** Put a 3D shot in its own `Scene` and keep its `Scene` and `Renderer` in the
+ struct. `ctx.render_scenes` renders only the scenes that are on screen; during an
+ `Overlap` both scenes render, so two 3D shots that overlap cost two renders.
+- **Media in 3D.** `Texture::from_image(&image)` puts an fframes image on a material
+ (`.map(texture)`, `.emissive_map(texture)` for a glowing screen). For a video playing on a
+ screen, make a new texture from each synced frame, resized to the screen first.
+- **Fonts and models.** `Geometry::text(include_bytes!("../media/Inter.ttf"), "Hi", 0.5, 0.1,
+ 0.01)?` (size, depth and bevel in meters) makes extruded text from the same font file as
+ the SVG. `Model::from_gltf(include_bytes!(..))`
+ loads a `.glb` (`model.add_to(&mut scene, None)` returns an instance; `instance.play(&mut
+ scene, clip, t)` animates it, `instance.root` moves it). STL files are often millimeters with
+ Z up: `Geometry::from_stl(bytes)?.scale(0.001, 0.001, 0.001).rotate_x(-FRAC_PI_2)`.
+- **Matching the look.** Pick one lighting setup per video: `Environment::studio()` for
+ products, an HDR panorama (`Environment::map`) for real places. `ToneMapping::Neutral`
+ keeps brand colors, ACES (the default) is filmic and shifts saturated colors. Match the SVG
+ palette with `fframes::Color::from(rgb)` of the material colors.
+
+## Do
+
+- Build geometry, textures, models and text in the constructor. The GPU caches meshes and
+ textures by their `Arc`; new ones every frame upload again every frame.
+- Clone the scene in `render_frame` and change only what moves.
+- Set `.shadows(false, ..)` on floors, walls and far scenery and give `Shadow::bounds` a box
+ around what casts shadows, so the shadow map stays sharp. Only `Light::sun` (or
+ `Light::with_shadow`) casts shadows; point and spot lights shine through objects.
+- Use `Reflector::floor()` with `Material::reflection(..)` and a roughness map for polished
+ floors, one reflector per scene.
+- Give small glowing particles a few pixels of size, or keep them in focus: out of focus, a
+ very bright single-pixel dot turns into a pattern of dots in the depth of field.
+- Look at the result: `strip` and `frame` show the 3D as pixels; `inspect` cannot see inside
+ the 3D image, but `inspect --pops` still finds objects that appear or vanish in one frame.
+ A renderer with `.cpu()` draws the same shot on the CPU rasterizer to compare.
+- Make random things deterministic: hash the frame or the index, never use time or a random
+ number generator, because frames render out of order on several threads.
+
+## Do not
+
+- Do not use 3D for flat things (text cards, charts, UI) or as decoration that has nothing to
+ do with the subject. A spinning logo for no reason is slop.
+- Do not shake or zoom the camera on every beat, or move it all the time. Hold, then move with
+ a purpose; small camera shake only on real impacts.
+- Do not read files, decode models or build geometry in `render_frame`.
+- Do not render a huge floor with shadows from the whole world in the shadow map: shadows get
+ blurry and blocky.
+- Do not draw gradients or vignettes in 3D: put them in SVG behind or above the transparent
+ 3D image.
+- Do not expect real volumetric light. `Fog`, a glowing cone (`Material::glow` on nested
+ cones, as in `examples/arm/src/effects.rs`) and particles inside the beam look like haze.
+- Do not render motion blur, high sample counts or 4K 3D in the web editor: it renders on the
+ CPU. Check `ctx.mode` (`FFramesMode::Renderer`) to turn expensive parts on only for renders.
+
+## Building blocks
+
+| three.js | `fframes::three_d` |
+| --- | --- |
+| `Scene`, `Group`, `Mesh`, `InstancedMesh`, `Points` | `Scene`, `Node::group`, `Node::mesh`, `Node::instanced`, `Node::particles` |
+| Box, Sphere, Cylinder, Cone, Capsule, Torus, Plane, Circle, Ring, Lathe, Extrude, Tube, Icosahedron, Text, RoundedBox geometry | `Geometry::cuboid`, `sphere`, `cylinder`, `cone`, `capsule`, `torus`, `plane`, `floor`, `circle`, `ring`, `lathe`, `extrude`, `tube`, `icosahedron`, `text`, `rounded_box`; `merge`, `translate`, `rotate_*`, `scale`, `smooth`, `flat` |
+| `MeshStandardMaterial`, clearcoat, `MeshBasicMaterial`, `ShadowMaterial`, `MeshNormalMaterial` | `Material::standard`, `metal`, `.clearcoat`, `unlit`, `glow` (additive), `shadow_catcher`, `normals` |
+| `map`, `normalMap`, `aoMap`, `emissiveMap`, metal-roughness map | `.map`, `.normal_map`, `.ao_map`, `.emissive_map`, `metal_rough_map`; `Texture::decode`, `from_fn`, `from_image` |
+| `AmbientLight`, `HemisphereLight`, `DirectionalLight` + shadow, `PointLight`, `SpotLight` | `Light::ambient`, `hemisphere`, `directional`, `sun`, `point`, `spot` |
+| `RoomEnvironment`, `RGBELoader`, `Fog`, `FogExp2`, `Reflector` | `Environment::studio`, `Environment::map`, `Fog::Linear`, `Fog::Exp2`, `Reflector::floor` |
+| `GLTFLoader` + `AnimationMixer`, `STLLoader` | `Model::from_gltf`, `ModelInstance::play`, `Geometry::from_stl` |
+| `UnrealBloomPass`, `BokehPass`, tone mapping | `Bloom`, `Camera::focus`, `ToneMapping::{Aces, Neutral, Linear}`, `Renderer::render_motion_blur` |
+| `vector.project(camera)` | `Camera::project`, `Camera::pixel_size` |
diff --git a/typos.toml b/typos.toml
index d377f82f..a7383002 100644
--- a/typos.toml
+++ b/typos.toml
@@ -6,3 +6,7 @@ extend-exclude = ["*.snapshot.txt", "sessions.json", "examples/the-why/landing/v
hd = "hd"
# "PNGs" is split into "PN" + "Gs"
PN = "PN"
+# graphics terms of fframes_three_d: PBR metalness (three.js), level of detail, integer y next to ix
+metalness = "metalness"
+lod = "lod"
+iy = "iy"