Skip to content

armgit / raea

Public Imported from GitHub
0

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

R3F22: three's compute and storage buffers run in the engine. raea-sys-shader shared.rs keeps a storage buffer by key (Bevy's ShaderBuffer, made once with its size and first contents, kept on the GPU, reset by a fresh three session; the empty one for an unused slot), the facility the computes that write it and the node materials that read it share. raea-sys-compute three.rs reads a <Compute kernels shared runs>: each kernel three's own WGSL with its storage bindings by key and its uniforms packed by three's struct, and the frame's runs queued once each by (epoch, seq) and dispatched in order before the other computes, a run whose pipeline or buffer isn't ready held. raea-sys-three-shader storage.rs binds two read-only shared buffers to a node material (bindings 11 and 12), and repeats a BufferMesh with copies count times with each copy's number, matrix and attributes (not frustum-culled). Two fixes the parity render found: runtime-scene keys a compute row's kernels, shared and runs frame by frame (a run after frame 0 never reached the engine), and three-shader's unlit entry premultiplies an additive material's colour with no alpha (three_blend in tone.wesl), since Bevy blends AlphaMode::Add as premultiplied alpha. compute lib.rs's groups_of and column serve the written, inline and three computes alike. docs/r3f.feature: R3F22 done, in-tsl-particles SSIM 0.9510

shinyobjectzfef9a1bd3838
diff --git a/Cargo.lock b/Cargo.lock
index 63b5cb0a..8315bdf6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -16214,6 +16214,7 @@ dependencies = [
"naga",
"raea-sys-material",
"raea-sys-sampler",
+ "raea-sys-shader",
"serde_json",
]
diff --git a/docs/r3f.feature b/docs/r3f.feature
index 8092353a..e68c69f8 100644
--- a/docs/r3f.feature
+++ b/docs/r3f.feature
@@ -412,12 +412,13 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composi
raea-sys-three-shader's surface test; tools/parity.sh runs in-tsl-lit. A displaced mesh's shadow is still its
undisplaced shape (three-shader's shadow pass is the standard one), and a fragmentNode keeps three's output
+ @done
Scenario: R3F22. TSL compute and storage buffers
Given the plan
| crate | file | lines | job |
- | raea-sys-material | systems/material/src/storage.rs | 80 | storage buffers shared by key, kept, reset to their first contents |
+ | raea-sys-shader | systems/shader/src/shared.rs | 130 | storage buffers shared by key, kept, reset to their first contents |
| raea-sys-compute | systems/compute/src/three.rs | 220 | three's kernels: the frame's dispatches run once, in order |
- | raea-sys-three-shader | systems/three-shader/src/storage.rs | 120 | a node material's storage reads; a mesh drawn as copies |
+ | raea-sys-three-shader | systems/three-shader/src/storage.rs | 200 | a node material's storage reads; a mesh drawn as copies |
| sdk/r3f | sdk/r3f/src/input/tsl-compute.ts | 200 | a ComputeNode's WGSL, each dispatch recorded, the Compute part |
| sdk/r3f | sdk/r3f/src/input/tsl-storage.ts | 90 | a storage attribute's key; a material reading it |
| sdk/r3f | sdk/r3f/src/input/tsl-instances.ts | 90 | a node material on an InstancedMesh as one mesh of copies |
@@ -425,14 +426,15 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composi
# on a seek back (runtime/plugins steps(): a compute isn't frame-pure; engine catch_up), so the engine runs each
# frame's dispatches once, in order, and a still at frame F runs all of them. What's missing is three's WGSL as a
# compute, buffers a compute and a material share, and the dispatches as a list a frame.
- # R3F22a. Engine, compute: a storage buffer shared by key (raea-sys-material storage.rs: Bevy's ShaderBuffer, made
+ # R3F22a. Engine, compute: a storage buffer shared by key (raea-sys-shader shared.rs: Bevy's ShaderBuffer, made
# with its size and first contents, kept from frame to frame, reset to them; a 16-byte one for an empty slot).
# A <Compute kernels> (three.rs): each kernel three's own WGSL, its `@group(0)` storage buffers keys of the
# shared ones and its uniforms packed by the struct three declares (raea-sys-shader uniform_slots). Its keyed
- # `runs` column each frame: {epoch, frame, fresh, runs: [[kernel, [x, y, z], {UNIFORM: {field: value}}]]}, run
- # once for each (epoch, frame) in the frame's compute pass, a fresh one (a new three session's first) resetting
- # the buffers first; a run whose pipeline or buffer isn't on the GPU yet is held, never dropped. The computes
- # there are (game_of_life, compute_mesh, bevy-ts compute, sdk/web's) are unchanged.
+ # `runs` column each frame: {epoch, seq, fresh, runs: [[kernel, [x, y, z], {UNIFORM: {field: value}}]]}
+ # (seq: the session's parts in turn), run once for each (epoch, seq) in the frame's compute pass, a fresh one
+ # (a new three session's first) resetting the buffers first; a run whose pipeline or buffer isn't on the GPU
+ # yet is held, never dropped. The computes there are (game_of_life, compute_mesh, bevy-ts compute, sdk/web's)
+ # are unchanged.
# R3F22b. Engine, three shader: ThreeShader binds two read-only storage buffers (bindings 11 and 12, the empty
# one when unused); a node material's spec lists `storage: [{name, key, size}]` and each stage's
# `var<storage, read> NAME` takes its binding (storage.rs). A BufferMesh with `copies` (count, per-copy
@@ -455,8 +457,9 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composi
# instancedParts before copyParts (agreed with r3f-gpu, 11-15).
# R3F22e. in-tsl-particles: 65,536 particles in a disc, placed by an init compute and orbited each frame by an
# update compute at a speed by radius, drawn as one InstancedMesh of small quads (positionNode their storage
- # position, coloured by radius), additive; against three.js on WebGPU in Chrome (its WebGL 2 backend if
- # headless Chrome has no WebGPU), frame 12, SSIM at least 0.92.
+ # position, colorNode a second buffer: one of four arms by the first angle, so the arms wind into a spiral only
+ # if every frame's update ran), additive; against three.js's WebGL 2 backend in headless Chrome (as in-tsl-lit),
+ # frame 12, SSIM at least 0.92.
Given TSL storage (`instancedArray`, `storage`, `attributeArray`), compute nodes (`Fn(...)().compute(n)`) run with
`gl.compute` / `computeAsync` in useFrame, and a material reading the buffers (`.element(instanceIndex)`,
`.toAttribute()`) on an InstancedMesh, Points or Sprite
@@ -465,6 +468,21 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composi
the order dispatched, its storage buffers kept from frame to frame and shared with the materials that read them
And a render that starts past frame 0 steps every compute from frame 0, so a render equals its play
And in-tsl-particles (65,536 particles orbited by a compute): SSIM at least 0.92 against three.js on WebGPU
+ And the status, 2026-11-15: built as planned, on an InstancedMesh. in-tsl-particles SSIM 0.9510 against three.js
+ (WebGPURenderer, its WebGL 2 backend) in Chrome at frame 12: the init and every frame's update ran on raea's GPU
+ (the arms wind into the same spiral), drawn as one mesh of 65,536 copies reading both buffers; in-tsl-lit 0.9906
+ and in-shader 0.9935 unchanged. Two engine fixes came with it: runtime-scene keys a compute row's `kernels`,
+ `shared` and `runs` frame by frame (it keyed only entry, bind and uniforms, so a run after frame 0 never reached
+ the engine), and three-shader's unlit entry premultiplies an additive material's colour with no alpha
+ (three_blend in tone.wesl: Bevy blends AlphaMode::Add as premultiplied alpha, so three's additive overlaps,
+ GLSL ShaderMaterials' too, drew as one layer). Proof: sdk/r3f test/compute.test.tsx (kernels, shared keys, runs
+ once a frame with their uniforms, workgroups as three's backend, the copies mesh and its WGSL, the parity swirl),
+ raea-sys-compute three.rs and three-shader storage.rs tests (runs packed once by (epoch, seq), copies repeated
+ with their number, matrix and values), tools/parity.sh in-tsl-particles. Not yet: Points and a Sprite with a
+ count (drawn as before), per-vertex storage reads, indirect dispatch, a compute first dispatched after frame 0
+ (runtime-scene makes compute rows from the first frame's items), and a texture bound in a compute. Dense
+ additive particles come out more saturated than three's: raea's camera without Hdr tone-maps each fragment in
+ its shader before the blend, where three tone-maps the sum
Scenario: R3F23. Render targets are drawn on the GPU
Given what an app draws into a render target itself (`gl.setRenderTarget(t); gl.render(scene, camera)`, drei's
diff --git a/runtime/scene/src/parts.rs b/runtime/scene/src/parts.rs
index b4cb63f7..c3ed953b 100644
--- a/runtime/scene/src/parts.rs
+++ b/runtime/scene/src/parts.rs
@@ -8,14 +8,14 @@ pub(crate) fn surface_shader_rows(all: &[Vec<Item>], p: &mut Program) {
}
/// the scene's <FramePass>es or <Compute>s (`kind` frame_pass or compute), from the first frame, in the order written:
-/// frame_pass0, frame_pass1, …; a compute or pass as written's `entry`, `bind` and `uniforms` keyed (strings that change
-/// frame by frame)
+/// frame_pass0, frame_pass1, …; a compute or pass as written's `entry`, `bind` and `uniforms`, and three's compute's
+/// `kernels`, `shared` and `runs` (docs/r3f.feature R3F22), keyed (strings that change frame by frame)
pub(crate) fn ordered_shader_rows(all: &[Vec<Item>], p: &mut Program, kind: &str) {
let Some(f0) = all.first() else { return };
let mut rows: Vec<_> = f0.iter().filter(|it| *it.kind == *kind).enumerate().map(|(i, it)| shader_row(format!("{kind}{i}"), it)).collect();
for (i, row) in rows.iter_mut().enumerate() {
let id = format!("{kind}{i}");
- for prop in ["entry", "bind", "uniforms"].into_iter().filter(|k| f0.iter().filter(|it| *it.kind == *kind).nth(i).is_some_and(|it| it.props.contains_key(*k))) {
+ for prop in ["entry", "bind", "uniforms", "kernels", "shared", "runs"].into_iter().filter(|k| f0.iter().filter(|it| *it.kind == *kind).nth(i).is_some_and(|it| it.props.contains_key(*k))) {
let vals: Vec<String> = all.iter().map(|f| f.iter().filter(|it| *it.kind == *kind).nth(i).and_then(|it| it.props.get(prop)?.as_str()).unwrap_or("").to_string()).collect();
keyed_strings(p, row, &id, prop, &vals);
}
diff --git a/systems/compute/src/lib.rs b/systems/compute/src/lib.rs
index 957527e4..06036684 100644
--- a/systems/compute/src/lib.rs
+++ b/systems/compute/src/lib.rs
@@ -20,6 +20,7 @@ use bevy::render::{
*,
},
renderer::{RenderContext, RenderDevice, RenderGraph},
+ storage::GpuShaderBuffer,
texture::GpuImage,
Render, RenderApp, RenderSystems,
};
@@ -28,6 +29,7 @@ use raea_sys_shader::{accessors, register, Inputs};
use serde_json::Value;
mod slab;
+pub mod three;
pub mod written;
/// Buffers and images a compute may have.
@@ -45,6 +47,8 @@ pub struct Compute {
pub images: Vec<Handle<Image>>,
/// a compute as written (a <Compute file>): its own bindings, entry and images (written.rs)
pub written: Option<written::Written>,
+ /// three.js's compute nodes (a <Compute kernels>): its kernels, shared buffers and this frame's runs (three.rs)
+ pub three: Option<three::Three>,
/// its row's id, whose keyed `uniforms` column it follows frame by frame; its uniforms' names, in slot order; the
/// column last followed
pub id: String,
@@ -82,10 +86,13 @@ pub fn module(source: &str, uniforms: &[(String, &'static str)], buffers: &[Stri
/// made storage-capable here.
pub fn build(world: &mut World, v: &Value, id: &str, mut image: impl FnMut(&mut World, &Value) -> Result<Handle<Image>, String>) -> Result<Compute, String> {
let o = v.as_object().ok_or_else(|| format!("a compute is {{wesl, workgroups, uniforms, buffers, images}}, got {v}"))?;
+ if o.contains_key("three") {
+ return Ok(three::build(id));
+ }
let workgroups = workgroups(o)?;
if o.contains_key("file") {
let (shader, w) = written::build(world, o, id, &mut image)?;
- return Ok(Compute { shader, workgroups, slots: [Vec4::ZERO; SLOTS], buffers: vec![], images: vec![], written: Some(w), id: id.to_string(), names: vec![], given: String::new() });
+ return Ok(Compute { shader, workgroups, slots: [Vec4::ZERO; SLOTS], buffers: vec![], images: vec![], written: Some(w), three: None, id: id.to_string(), names: vec![], given: String::new() });
}
let ins = Inputs::read(world, o, "a compute", &mut image)?;
if !ins.textures.is_empty() || ins.array.is_some() {
@@ -137,24 +144,34 @@ pub fn build(world: &mut World, v: &Value, id: &str, mut image: impl FnMut(&mut
let bnames: Vec<String> = buffers.iter().map(|b| b.0.clone()).collect();
let shader = register(world, module(&ins.src, &names, &bnames, &inames), &ins.defs, "raea compute", "raea_sys_compute");
let uniforms = names.iter().map(|(n, _)| n.clone()).collect();
- Ok(Compute { shader, workgroups, slots: ins.slots(), buffers, images, written: None, id: id.to_string(), names: uniforms, given: String::new() })
+ Ok(Compute { shader, workgroups, slots: ins.slots(), buffers, images, written: None, three: None, id: id.to_string(), names: uniforms, given: String::new() })
}
/// A spec's workgroups, [x(, y(, z))], each 1 to 65535.
fn workgroups(o: &serde_json::Map<String, Value>) -> Result<[u32; 3], String> {
- match o.get("workgroups").and_then(Value::as_array) {
- Some(a) if (1..=3).contains(&a.len()) && a.iter().all(|x| x.as_u64().is_some_and(|n| (1..=65535).contains(&n))) => {
- let n = |i: usize| a.get(i).and_then(Value::as_u64).unwrap_or(1) as u32;
- Ok([n(0), n(1), n(2)])
- }
- _ => Err(format!("a compute's workgroups are [x, y, z], each 1 to 65535, got {}", o.get("workgroups").unwrap_or(&Value::Null))),
+ groups_of(o.get("workgroups")).ok_or_else(|| format!("a compute's workgroups are [x, y, z], each 1 to 65535, got {}", o.get("workgroups").unwrap_or(&Value::Null)))
+}
+
+/// Workgroups as [x(, y(, z))], each 1 to 65535 (a missing one 1); None for anything else.
+pub(crate) fn groups_of(v: Option<&Value>) -> Option<[u32; 3]> {
+ let a = v?.as_array()?;
+ if !(1..=3).contains(&a.len()) || !a.iter().all(|x| x.as_u64().is_some_and(|n| (1..=65535).contains(&n))) {
+ return None;
}
+ let n = |i: usize| a.get(i).and_then(Value::as_u64).unwrap_or(1) as u32;
+ Some([n(0), n(1), n(2)])
+}
+
+/// Row `r`'s keyed string column `k` this frame ("" when it has none).
+pub(crate) fn column(frame: &raea_sys_frame::FrameRows, r: usize, k: &str) -> String {
+ raea_sys_frame::keyed(|col| frame.at(r, col), k).unwrap_or_default()
}
pub fn install(app: &mut App) {
app.init_resource::<Computes>();
+ app.init_resource::<raea_sys_shader::shared::SharedBuffers>();
app.add_plugins(ExtractResourcePlugin::<Computes>::default());
- app.add_systems(PostUpdate, (follow, stamp));
+ app.add_systems(PostUpdate, (follow, three::follow, stamp).chain());
let Some(render_app) = app.get_sub_app_mut(RenderApp) else { return };
render_app.init_resource::<State>();
render_app.add_systems(Render, queue.in_set(RenderSystems::Queue));
@@ -180,7 +197,7 @@ fn follow(frame: Option<Res<raea_sys_frame::FrameRows>>, mut c: ResMut<Computes>
let cols = &frame.cols;
for c in c.list.iter_mut() {
let Some(r) = cols.id.iter().position(|i| *i == c.id) else { continue };
- let s = |k: &str| raea_sys_frame::keyed(|col| frame.at(r, col), k).unwrap_or_default();
+ let s = |k: &str| column(&frame, r, k);
let Some(w) = c.written.as_mut() else {
if let Err(e) = inline_uniforms(c, &s("uniforms")) {
error!("Compute {}: {e}", c.id);
@@ -231,11 +248,30 @@ struct State {
buffers: HashMap<(usize, u128, String), Buffer>,
/// a compute as written's pipelines, by its shader and entry point
written: HashMap<(u128, String), (BindGroupLayoutDescriptor, CachedComputePipelineId)>,
+ /// three's kernels' pipelines by shader; the runs not yet dispatched, in order; each compute's runs last taken
+ three: HashMap<u128, (BindGroupLayoutDescriptor, CachedComputePipelineId)>,
+ backlog: Vec<three::Run>,
+ taken: HashMap<usize, (i64, i64)>,
}
fn queue(c: Option<Res<Computes>>, mut s: ResMut<State>, cache: Res<PipelineCache>) {
let Some(c) = c else { return };
- for k in &c.list {
+ for (n, k) in c.list.iter().enumerate() {
+ if let Some(t) = &k.three {
+ let new: Vec<_> = t.kernels.values().filter(|x| !s.three.contains_key(&x.shader)).cloned().collect();
+ for kernel in new {
+ let layout = BindGroupLayoutDescriptor::new("raea_compute_three", &written::layout(&kernel.decls));
+ let shader = Handle::Uuid(bevy::asset::uuid::Uuid::from_u128(kernel.shader), core::marker::PhantomData);
+ let id = cache.queue_compute_pipeline(ComputePipelineDescriptor { label: Some("raea_compute_three".into()), layout: vec![layout.clone()], shader, entry_point: Some(three::ENTRY.into()), ..default() });
+ s.three.insert(kernel.shader, (layout, id));
+ }
+ // this frame's runs onto the backlog once (a frame extracted again holds the same runs)
+ if let Some(at) = t.seen.filter(|at| !t.runs.is_empty() && s.taken.get(&n) != Some(at)) {
+ s.taken.insert(n, at);
+ s.backlog.extend(t.runs.iter().cloned());
+ }
+ continue;
+ }
if let Some(w) = &k.written {
let key = w.entry.as_ref().map(|e| (k.shader, e.clone()));
if let Some(key) = key.filter(|key| !s.written.contains_key(key)) {
@@ -270,11 +306,19 @@ fn queue(c: Option<Res<Computes>>, mut s: ResMut<State>, cache: Res<PipelineCach
}
/// Each compute whose pipeline and images are ready, dispatched in order in one compute pass.
-fn dispatch(c: Option<Res<Computes>>, mut s: ResMut<State>, cache: Res<PipelineCache>, images: Res<RenderAssets<GpuImage>>, slabs: Slabs, mut ctx: RenderContext) {
+fn dispatch(c: Option<Res<Computes>>, mut s: ResMut<State>, cache: Res<PipelineCache>, images: Res<RenderAssets<GpuImage>>, shared: Res<RenderAssets<GpuShaderBuffer>>, slabs: Slabs, mut ctx: RenderContext) {
let Some(c) = c else { return };
let device = ctx.render_device().clone();
let mut groups = vec![];
+ // three's runs first, in order, up to the first whose pipeline or buffers aren't on the GPU yet (held, with every
+ // run after it, for the next frame)
+ let ready = s.backlog.iter().map_while(|r| three_group(&device, &cache, &s.three, &shared, r)).collect::<Vec<_>>();
+ s.backlog.drain(..ready.len());
+ groups.extend(ready);
'computes: for (n, k) in c.list.iter().enumerate() {
+ if k.three.is_some() {
+ continue;
+ }
if let Some(w) = &k.written {
let Some((layout, id)) = w.entry.as_ref().and_then(|e| s.written.get(&(k.shader, e.clone()))) else { continue };
let (Some(pipeline), layout) = (cache.get_compute_pipeline(*id), cache.get_bind_group_layout(layout)) else { continue };
@@ -341,6 +385,22 @@ fn dispatch(c: Option<Res<Computes>>, mut s: ResMut<State>, cache: Res<PipelineC
}
}
+/// A three run's pipeline and bind group (its uniforms' bytes, its shared buffers) and workgroups, once all are ready.
+fn three_group<'a>(device: &RenderDevice, cache: &'a PipelineCache, pipelines: &HashMap<u128, (BindGroupLayoutDescriptor, CachedComputePipelineId)>, shared: &RenderAssets<GpuShaderBuffer>, r: &three::Run) -> Option<(&'a ComputePipeline, BindGroup, [u32; 3])> {
+ let (layout, id) = pipelines.get(&r.kernel.shader)?;
+ let pipeline = cache.get_compute_pipeline(*id)?;
+ let mut buffers: Vec<(u32, Buffer)> = Vec::new();
+ for d in &r.kernel.decls {
+ match d {
+ written::Decl::Uniform { binding, name, .. } => buffers.push((*binding, device.create_buffer_with_data(&BufferInitDescriptor { label: Some("raea_compute_three"), contents: r.uniforms.get(name)?, usage: BufferUsages::UNIFORM }))),
+ written::Decl::Buffer { binding, name, .. } => buffers.push((*binding, shared.get(*r.buffers.get(name)?)?.buffer.clone())),
+ written::Decl::Storage { .. } => return None,
+ }
+ }
+ let group = device.create_bind_group("raea_compute_three", &cache.get_bind_group_layout(layout), &raea_sys_shader::bindings::entries(&buffers, vec![]));
+ Some((pipeline, group, r.workgroups))
+}
+
/// The mesh allocator and the meshes on the GPU, for a compute that binds a mesh's slab.
type Slabs<'w> = (Res<'w, bevy::render::mesh::allocator::MeshAllocator>, Res<'w, RenderAssets<bevy::render::mesh::RenderMesh>>);
diff --git a/systems/compute/src/three.rs b/systems/compute/src/three.rs
new file mode 100644
index 00000000..efd4c4cc
--- /dev/null
+++ b/systems/compute/src/three.rs
@@ -0,0 +1,208 @@
+//! three.js's compute nodes (docs/r3f.feature R3F22): <R3F>'s gl.compute dispatches as a <Compute kernels shared runs>
+//! (sdk/r3f's tsl-compute.ts). Each kernel is three's own WGSL, compiled as written: its `@group(0)` storage buffers the
+//! shared ones by key (shared.rs: the node materials reading them bind the same buffers), its
+//! uniforms packed from each dispatch's values by the struct three declares (raea-sys-shader uniform_slots), its entry
+//! `main`. Three keyed columns follow the frame: `kernels` ({id: {wgsl, buffers: {NAME: KEY}}}) and `shared` ({KEY: {size,
+//! f32 | u32 | i32}}) change when a new kernel is dispatched, `runs` every frame: {epoch, seq, fresh, runs: [[kernel, [x,
+//! y, z], {UNIFORM: {field: value}}]]}, the dispatches since the frame before.
+//!
+//! A frame's runs are dispatched once (their (epoch, seq) is remembered), in order, in the frame's compute pass before
+//! the cameras draw; `fresh` (a three session's first frame) writes the buffers back to their first contents first. A
+//! composition with a compute steps every frame from 0 (raea-runtime-plugins steps(): a compute isn't frame-pure), so
+//! a still at frame F runs every frame's dispatches before it, and a seek back starts a new App. A run whose pipeline
+//! or buffer isn't on the GPU yet is held for the next frame, with every run after it, never dropped.
+
+use std::collections::{BTreeMap, HashMap};
+use std::sync::Arc;
+
+use bevy::prelude::*;
+use bevy::render::storage::ShaderBuffer;
+use raea_sys_shader::shared::{first_contents, SharedBuffers};
+use serde_json::Value;
+
+use crate::written::{decls, Decl};
+
+/// A kernel, built: its shader, declarations, uniforms as declared, source and each storage buffer's key by name.
+#[derive(Debug)]
+pub struct Kernel {
+ pub shader: u128,
+ pub decls: Vec<Decl>,
+ declared: Vec<(String, String)>,
+ src: String,
+ buffers: BTreeMap<String, String>,
+}
+
+/// One dispatch, packed: the kernel's shader and declarations, its workgroups, each uniform's bytes and each storage
+/// buffer's shared buffer, by name.
+#[derive(Clone, Debug)]
+pub struct Run {
+ pub kernel: Arc<Kernel>,
+ pub workgroups: [u32; 3],
+ pub uniforms: BTreeMap<String, Vec<u8>>,
+ pub buffers: BTreeMap<String, AssetId<ShaderBuffer>>,
+}
+
+/// A <Compute kernels>: its kernels by id, the columns last followed, the (epoch, seq) last run, and this frame's runs.
+#[derive(Clone, Debug, Default)]
+pub struct Three {
+ pub kernels: HashMap<u64, Arc<Kernel>>,
+ given: (String, String),
+ pub seen: Option<(i64, i64)>,
+ pub runs: Vec<Run>,
+}
+
+/// The entry point every kernel has (three's WGSLNodeBuilder writes `fn main`).
+pub const ENTRY: &str = "main";
+
+/// A kernel from its spec ({wgsl, buffers: {NAME: KEY}}): every storage buffer it declares has a key, it binds no
+/// storage texture, and its entry is `main`.
+fn kernel(world: &mut World, v: &Value) -> Result<Kernel, String> {
+ let src = v.get("wgsl").and_then(Value::as_str).ok_or("a kernel is {wgsl, buffers}")?;
+ let d = decls(src)?;
+ let keys: BTreeMap<String, String> = v.get("buffers").and_then(Value::as_object).into_iter().flatten().filter_map(|(k, x)| Some((k.clone(), x.as_str()?.to_string()))).collect();
+ for x in &d {
+ match x {
+ Decl::Buffer { name, .. } if !keys.contains_key(name) => return Err(format!("its storage buffer {name} has no key")),
+ Decl::Storage { name, .. } => return Err(format!("{name}: a kernel binds storage buffers and uniforms, not storage textures")),
+ _ => {}
+ }
+ }
+ if !src.contains(&format!("fn {ENTRY}(")) && !src.contains(&format!("fn {ENTRY} (")) {
+ return Err(format!("a kernel's entry is fn {ENTRY}"));
+ }
+ let declared = raea_sys_shader::bindings::uniforms(src)?;
+ let shader = raea_sys_shader::register(world, src.to_string(), &[], "raea three compute", "raea_sys_compute");
+ Ok(Kernel { shader, decls: d, declared, src: src.to_string(), buffers: keys })
+}
+
+/// The `kernels` and `shared` columns, when they've changed: new kernels built, new shared buffers made.
+fn follow_kernels(world: &mut World, t: &mut Three, kernels: &str, shared: &str) -> Result<(), String> {
+ if t.given.0 != kernels {
+ let all: serde_json::Map<String, Value> = serde_json::from_str(kernels).map_err(|e| format!("kernels: {e}"))?;
+ for (id, v) in &all {
+ let id: u64 = id.parse().map_err(|_| format!("a kernel's id is a number, got {id}"))?;
+ if t.kernels.get(&id).is_some_and(|k| Some(k.src.as_str()) == v.get("wgsl").and_then(Value::as_str)) {
+ continue;
+ }
+ let k = kernel(world, v).map_err(|e| format!("kernel {id}: {e}"))?;
+ t.kernels.insert(id, Arc::new(k));
+ }
+ t.given.0 = kernels.to_string();
+ }
+ if t.given.1 != shared {
+ let all: serde_json::Map<String, Value> = serde_json::from_str(shared).map_err(|e| format!("shared: {e}"))?;
+ world.resource_scope::<SharedBuffers, _>(|world, mut s| -> Result<(), String> {
+ let mut assets = world.resource_mut::<Assets<ShaderBuffer>>();
+ for (key, v) in &all {
+ s.get_or_make(&mut assets, key, first_contents(v).map_err(|e| format!("shared {key}: {e}"))?)?;
+ }
+ Ok(())
+ })?;
+ t.given.1 = shared.to_string();
+ }
+ Ok(())
+}
+
+/// This frame's `runs` packed, when its (epoch, seq) hasn't been run; a fresh one writes the buffers back first.
+fn follow_runs(world: &mut World, t: &mut Three, runs: &str) -> Result<(), String> {
+ t.runs.clear();
+ if runs.is_empty() {
+ return Ok(());
+ }
+ let v: Value = serde_json::from_str(runs).map_err(|e| format!("runs: {e}"))?;
+ let (Some(epoch), Some(seq)) = (v.get("epoch").and_then(Value::as_i64), v.get("seq").and_then(Value::as_i64)) else {
+ return Err("runs: its epoch and seq are numbers".into());
+ };
+ let at = (epoch, seq);
+ if t.seen == Some(at) {
+ return Ok(());
+ }
+ t.seen = Some(at);
+ if v.get("fresh").and_then(Value::as_bool) == Some(true) {
+ let keys: Vec<String> = t.kernels.values().flat_map(|k| k.buffers.values().cloned()).collect();
+ world.resource_scope::<SharedBuffers, _>(|world, s| s.reset(&mut world.resource_mut::<Assets<ShaderBuffer>>(), keys.iter().map(String::as_str)));
+ }
+ let shared = world.resource::<SharedBuffers>();
+ for (i, r) in v.get("runs").and_then(Value::as_array).into_iter().flatten().enumerate() {
+ let id = r.get(0).and_then(Value::as_u64).ok_or_else(|| format!("run {i}: [kernel, workgroups, uniforms]"))?;
+ let k = t.kernels.get(&id).ok_or_else(|| format!("run {i}: kernel {id} isn't one it has"))?.clone();
+ let workgroups = crate::groups_of(r.get(1)).ok_or_else(|| format!("run {i}: workgroups are [x, y, z], each 1 to 65535"))?;
+ let given = r.get(2).and_then(Value::as_object).cloned().unwrap_or_default();
+ let slots = raea_sys_shader::uniform_slots(&k.src, &k.declared, &given, &[]).map_err(|e| format!("run {i}: {e}"))?;
+ let uniforms = k.declared.iter().zip(slots).map(|((name, _), s)| (name.clone(), s.iter().flat_map(|v| v.to_array()).flat_map(f32::to_ne_bytes).collect())).collect();
+ let mut buffers = BTreeMap::new();
+ for (name, key) in &k.buffers {
+ buffers.insert(name.clone(), shared.get(key).ok_or_else(|| format!("run {i}: shared buffer {key} isn't made (the shared column names it)"))?.id());
+ }
+ t.runs.push(Run { kernel: k, workgroups, uniforms, buffers });
+ }
+ Ok(())
+}
+
+/// Each <Compute kernels>'s columns this frame (raea-sys-frame's keyed strings) followed: its kernels and shared
+/// buffers, and the runs to dispatch this frame (none when this frame's were run).
+pub fn follow(world: &mut World) {
+ // last frame's runs were extracted and taken: none until this frame's are followed
+ let Some(mut c) = world.get_resource_mut::<crate::Computes>() else { return };
+ if !c.list.iter().any(|k| k.three.is_some()) {
+ return;
+ }
+ c.list.iter_mut().filter_map(|k| k.three.as_mut()).for_each(|t| t.runs.clear());
+ let cols: Vec<(usize, [String; 3])> = {
+ let Some(frame) = world.get_resource::<raea_sys_frame::FrameRows>() else { return };
+ let Some(c) = world.get_resource::<crate::Computes>() else { return };
+ c.list.iter().enumerate().filter(|(_, k)| k.three.is_some()).filter_map(|(i, k)| {
+ let r = frame.cols.id.iter().position(|x| *x == k.id)?;
+ Some((i, ["kernels", "shared", "runs"].map(|col| crate::column(frame, r, col))))
+ }).collect()
+ };
+ if cols.is_empty() {
+ return;
+ }
+ world.init_resource::<SharedBuffers>();
+ for (i, [kernels, shared, runs]) in cols {
+ let (id, mut t) = {
+ let mut c = world.resource_mut::<crate::Computes>();
+ let k = &mut c.list[i];
+ (k.id.clone(), k.three.take().unwrap_or_default())
+ };
+ if let Err(e) = follow_kernels(world, &mut t, &kernels, &shared).and_then(|_| follow_runs(world, &mut t, &runs)) {
+ error!("Compute {id}: {e}");
+ t.runs.clear();
+ }
+ world.resource_mut::<crate::Computes>().list[i].three = Some(t);
+ }
+}
+
+/// A <Compute kernels>'s spec ({three: true}): its kernels and runs arrive in its keyed columns (follow).
+pub fn build(id: &str) -> crate::Compute {
+ crate::Compute { shader: 0, workgroups: [1, 1, 1], slots: [Vec4::ZERO; raea_sys_material::shader_material::SLOTS], buffers: vec![], images: vec![], written: None, three: Some(Three::default()), id: id.to_string(), names: vec![], given: String::new() }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_frames_runs_are_packed_once_by_epoch_and_seq() {
+ let mut app = App::new();
+ app.add_plugins((MinimalPlugins, bevy::asset::AssetPlugin::default())).init_asset::<Shader>().init_asset::<ShaderBuffer>().init_resource::<SharedBuffers>();
+ let w = app.world_mut();
+ let src = "struct B { value: array<vec4<f32>> };\n@group(0) @binding(0)\nvar<storage, read_write> NodeBuffer_1 : B;\nstruct O { nodeUniform1 : f32, nodeUniform2 : u32 };\n@group(0) @binding(1)\nvar<uniform> object : O;\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) g: vec3<u32>) { if (g.x >= object.nodeUniform2) { return; } NodeBuffer_1.value[g.x].x += object.nodeUniform1; }\n";
+ let kernels = serde_json::json!({ "7": { "wgsl": src, "buffers": { "NodeBuffer_1": "tsl:0" } } }).to_string();
+ let shared = serde_json::json!({ "tsl:0": { "size": 64 } }).to_string();
+ let runs = serde_json::json!({ "epoch": 0, "seq": 0, "fresh": true, "runs": [[7, [1, 1, 1], { "object": { "nodeUniform1": 0.5, "nodeUniform2": 4 } }]] }).to_string();
+ let mut t = Three::default();
+ follow_kernels(w, &mut t, &kernels, &shared).unwrap();
+ follow_runs(w, &mut t, &runs).unwrap();
+ assert_eq!(t.runs.len(), 1);
+ let u = &t.runs[0].uniforms["object"];
+ assert_eq!((f32::from_ne_bytes(u[0..4].try_into().unwrap()), u32::from_ne_bytes(u[4..8].try_into().unwrap())), (0.5, 4));
+ assert_eq!(t.runs[0].buffers["NodeBuffer_1"], w.resource::<SharedBuffers>().get("tsl:0").unwrap().id());
+ // the same frame drawn again runs nothing; a kernel with a storage buffer no key names is refused
+ follow_runs(w, &mut t, &runs).unwrap();
+ assert!(t.runs.is_empty());
+ let bad = serde_json::json!({ "8": { "wgsl": src, "buffers": {} } }).to_string();
+ assert!(follow_kernels(w, &mut t, &bad, &shared).unwrap_err().contains("no key"));
+ }
+}
diff --git a/systems/shader/src/lib.rs b/systems/shader/src/lib.rs
index 38c87af7..81d2fd91 100644
--- a/systems/shader/src/lib.rs
+++ b/systems/shader/src/lib.rs
@@ -37,6 +37,8 @@ pub mod own;
pub mod own_array;
mod own_images;
pub mod own_live;
+/// Storage buffers shared by key between three's computes and its node materials (docs/r3f.feature R3F22).
+pub mod shared;
mod failed;
pub mod ui;
use raea_sys_shader_wgsl::ui_bind;
diff --git a/systems/shader/src/shared.rs b/systems/shader/src/shared.rs
new file mode 100644
index 00000000..9b2af88d
--- /dev/null
+++ b/systems/shader/src/shared.rs
@@ -0,0 +1,127 @@
+//! Storage buffers shared by key (docs/r3f.feature R3F22): a three.js storage attribute (TSL's `instancedArray`) is one
+//! buffer the computes that write it (raea-sys-compute three.rs) and the node materials that read it
+//! (raea-sys-three-shader storage.rs) bind by its key ("tsl:0"). Each is Bevy's ShaderBuffer, made once with its size and
+//! first contents and kept from frame to frame on the GPU (only what the computes write changes it); a new three
+//! session's first frame writes its first contents back. A material reading fewer buffers than it binds has the empty
+//! one (16 zero bytes) in the others.
+
+use std::collections::HashMap;
+
+use bevy::asset::RenderAssetUsages;
+use bevy::prelude::*;
+use bevy::render::storage::ShaderBuffer;
+use serde_json::Value;
+
+/// The label every shared buffer has: a buffer written again with the same size and label is written in place on the
+/// GPU (GpuShaderBuffer), so the bind groups holding it stand.
+const LABEL: &str = "raea shared storage";
+
+/// One shared buffer: its asset and its first contents, kept to reset it to (the GPU upload takes the asset's own).
+struct Shared {
+ handle: Handle<ShaderBuffer>,
+ first: Vec<u32>,
+}
+
+/// The shared buffers, by key, and the empty one.
+#[derive(Resource, Default)]
+pub struct SharedBuffers {
+ by_key: HashMap<String, Shared>,
+ empty: Option<Handle<ShaderBuffer>>,
+}
+
+fn buffer(words: Vec<u32>) -> ShaderBuffer {
+ let mut b = ShaderBuffer::new(words, RenderAssetUsages::default());
+ b.label = LABEL.into();
+ b
+}
+
+/// A buffer's first contents from its spec, {size, f32 | u32 | i32}: `size` bytes (a multiple of 4, at least 4) as
+/// 32-bit words, the numbers given from the start in the kind they're given as and zeros after.
+pub fn first_contents(v: &Value) -> Result<Vec<u32>, String> {
+ let size = v.get("size").and_then(Value::as_u64).filter(|n| *n >= 4 && n % 4 == 0 && *n <= 1 << 30).ok_or_else(|| format!("a shared buffer's size is a number of bytes, a multiple of 4, got {}", v.get("size").unwrap_or(&Value::Null)))?;
+ let mut words = vec![0u32; size as usize / 4];
+ let given = [("f32", 'f'), ("u32", 'u'), ("i32", 'i')].into_iter().filter_map(|(k, c)| v.get(k).map(|x| (k, c, x))).collect::<Vec<_>>();
+ if given.len() > 1 {
+ return Err("a shared buffer's contents are f32, u32 or i32, one of them".into());
+ }
+ if let Some((k, c, x)) = given.first() {
+ let list = x.as_array().ok_or_else(|| format!("a shared buffer's {k} is a list of numbers"))?;
+ if list.len() > words.len() {
+ return Err(format!("a shared buffer of {size} bytes holds {} numbers, given {}", words.len(), list.len()));
+ }
+ for (w, n) in words.iter_mut().zip(list) {
+ let n = n.as_f64().ok_or_else(|| format!("a shared buffer's {k}: numbers, got {n}"))?;
+ *w = match c {
+ 'f' => (n as f32).to_bits(),
+ 'u' => n.max(0.0) as u32,
+ _ => n as i32 as u32,
+ };
+ }
+ }
+ Ok(words)
+}
+
+impl SharedBuffers {
+ /// The buffer `key` names, made with `first` if it's new; one already made with another size is refused (a
+ /// compute and a material disagreeing on what they share). One made all zeros given contents takes them as its
+ /// first (a material reading it built before the compute that gave them).
+ pub fn get_or_make(&mut self, assets: &mut Assets<ShaderBuffer>, key: &str, first: Vec<u32>) -> Result<Handle<ShaderBuffer>, String> {
+ if let Some(s) = self.by_key.get_mut(key) {
+ if s.first.len() != first.len() {
+ return Err(format!("shared buffer {key} is {} bytes, given {} bytes", s.first.len() * 4, first.len() * 4));
+ }
+ if s.first != first && s.first.iter().all(|w| *w == 0) {
+ s.first = first;
+ if let Some(mut b) = assets.get_mut(&s.handle) {
+ *b = buffer(s.first.clone());
+ }
+ }
+ return Ok(s.handle.clone());
+ }
+ let handle = assets.add(buffer(first.clone()));
+ self.by_key.insert(key.to_string(), Shared { handle: handle.clone(), first });
+ Ok(handle)
+ }
+
+ /// The buffer `key` names, if it's made.
+ pub fn get(&self, key: &str) -> Option<&Handle<ShaderBuffer>> {
+ self.by_key.get(key).map(|s| &s.handle)
+ }
+
+ /// The buffers `keys` name written back to their first contents (on the GPU before the frame's computes run).
+ pub fn reset<'a>(&self, assets: &mut Assets<ShaderBuffer>, keys: impl IntoIterator<Item = &'a str>) {
+ for k in keys {
+ if let Some(s) = self.by_key.get(k)
+ && let Some(mut b) = assets.get_mut(&s.handle)
+ {
+ *b = buffer(s.first.clone());
+ }
+ }
+ }
+
+ /// 16 zero bytes, bound where a material reads no buffer.
+ pub fn empty(&mut self, assets: &mut Assets<ShaderBuffer>) -> Handle<ShaderBuffer> {
+ self.empty.get_or_insert_with(|| assets.add(buffer(vec![0; 4]))).clone()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn a_shared_buffer_is_made_once_by_key_with_its_first_contents() {
+ assert_eq!(first_contents(&json!({"size": 16, "f32": [1.5, 2]})).unwrap(), vec![1.5f32.to_bits(), 2f32.to_bits(), 0, 0]);
+ assert_eq!(first_contents(&json!({"size": 8, "i32": [-1]})).unwrap(), vec![u32::MAX, 0]);
+ assert!(first_contents(&json!({"size": 6})).unwrap_err().contains("multiple of 4"));
+ assert!(first_contents(&json!({"size": 4, "u32": [1, 2]})).unwrap_err().contains("holds 1"));
+ let mut assets = Assets::<ShaderBuffer>::default();
+ let mut s = SharedBuffers::default();
+ let a = s.get_or_make(&mut assets, "tsl:0", vec![0; 4]).unwrap();
+ assert_eq!(s.get_or_make(&mut assets, "tsl:0", vec![0; 4]).unwrap(), a);
+ assert!(s.get_or_make(&mut assets, "tsl:0", vec![0; 8]).unwrap_err().contains("16 bytes"));
+ assert_ne!(s.empty(&mut assets), a);
+ assert_eq!(assets.get(&a).unwrap().buffer_size(), 16);
+ }
+}
diff --git a/systems/three-shader/Cargo.toml b/systems/three-shader/Cargo.toml
index 4a9ed727..b9383d27 100644
--- a/systems/three-shader/Cargo.toml
+++ b/systems/three-shader/Cargo.toml
@@ -16,3 +16,5 @@ bevy = { version = "=0.20.0", default-features = false, features = ["std", "defa
# wgsl-in on; raea-web had nothing that did)
naga = { version = "=30.0.1", features = ["glsl-in", "wgsl-in", "wgsl-out"] }
serde_json = "1"
+# the storage buffers a node material reads, the same ones by key the computes write (docs/r3f.feature R3F22)
+raea-sys-shader = { path = "../shader" }
diff --git a/systems/three-shader/src/lib.rs b/systems/three-shader/src/lib.rs
index 56c7905f..ac4541d1 100644
--- a/systems/three-shader/src/lib.rs
+++ b/systems/three-shader/src/lib.rs
@@ -26,6 +26,7 @@ pub mod scan;
pub mod linear;
pub mod module;
mod row;
+pub mod storage;
pub mod surface;
pub use row::{fitted, of_row};
@@ -41,7 +42,8 @@ pub const ATTRIBUTE: [MeshVertexAttribute; ATTRIBUTES] = [
pub fn install(app: &mut App) {
app.add_plugins(MaterialPlugin::<ThreeShader>::default());
- app.add_systems(PostUpdate, follow_tonemapping);
+ app.init_resource::<raea_sys_shader::shared::SharedBuffers>();
+ app.add_systems(PostUpdate, (follow_tonemapping, storage::unbounded));
app.add_systems(PreUpdate, linear::sync);
}
@@ -66,6 +68,13 @@ pub struct ThreeShader {
#[texture(9, dimension = "3d")]
#[sampler(10)]
lut: Option<Handle<Image>>,
+ /// the shared buffers a node material reads (storage.rs: tsl_s0, tsl_s1), the empty one where it reads fewer
+ #[storage(11, read_only)]
+ st0: Handle<bevy::render::storage::ShaderBuffer>,
+ #[storage(12, read_only)]
+ st1: Handle<bevy::render::storage::ShaderBuffer>,
+ /// whether it reads one: its vertices are where the computes put them, not inside its mesh's bounds
+ unbounded: bool,
vertex: u128,
fragment: u128,
attributes: u8,
@@ -223,6 +232,9 @@ pub fn build(world: &mut World, v: &Value, mut image: impl FnMut(&mut World, &Va
return Err("a three shader gives glsl {vertex, fragment} or wgsl {vertex, fragment, uniforms}".into());
};
let layout = module::layout(&list)?;
+ // a node material's shared buffers (storage.rs), bound in each stage that reads them
+ let (st, stored) = storage::buffers(world, o.get("wgsl"))?;
+ let (vsrc, fsrc) = (storage::bind(&vsrc, &stored), storage::bind(&fsrc, &stored));
// three's textures with flipY count v from the picture's bottom; Bevy's images from their top
let flip: Vec<String> = o.get("flipY").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).filter_map(|n| bound.iter().position(|b| b == n)).map(|k| if own_textures { format!("tex_{}", bound[k]) } else { format!("rgt{k}x") }).collect();
let (vsrc, fsrc) = (module::flip_samples(&vsrc, &flip), module::flip_samples(&fsrc, &flip));
@@ -271,6 +283,9 @@ pub fn build(world: &mut World, v: &Value, mut image: impl FnMut(&mut World, &Va
tex2: t.next().flatten(),
tex3: t.next().flatten(),
lut: None,
+ st0: st[0].clone(),
+ st1: st[1].clone(),
+ unbounded: !stored.is_empty(),
vertex,
fragment,
attributes: attrs.len() as u8,
@@ -319,13 +334,18 @@ pub fn fit_mesh(mesh: &mut Mesh, buffer: Option<&str>, own: &[String]) -> Result
if mesh.attribute(Mesh::ATTRIBUTE_NORMAL).is_none() {
mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, vec![[0f32, 0.0, 1.0]; n]);
}
- if own.is_empty() {
+ let copies = buffer.is_some_and(|b| b.contains("\"copies\""));
+ if own.is_empty() && !copies {
return Ok(());
}
let v: Value = match buffer {
Some(b) => serde_json::from_str(b).map_err(|e| format!("a buffer mesh isn't JSON: {e}"))?,
None => return Err(format!("a three shader reads the mesh's own attributes ({}): give the mesh as a BufferMesh with them", own.join(", "))),
};
+ // an InstancedMesh's copies (docs/r3f.feature R3F22): the geometry repeated, a copy's number and values its own
+ if v.get("copies").is_some() {
+ return storage::fit_copies(mesh, &v, own);
+ }
let verts = v.get("positions").and_then(Value::as_array).map(|p| p.len() / 3).unwrap_or(0);
let idx = raea_sys_material::mesh::buffer_corners(&v, verts);
for (k, name) in own.iter().enumerate() {
@@ -380,7 +400,7 @@ mod tests {
let l = super::module::layout(&[("tint".into(), super::Ty::Vec(3), None)]).unwrap();
let (v, f) = super::modules("struct ThreeVaryings { @builtin(position) clip: vec4<f32>, };\nfn three_vertex(v: ThreeVertex) -> ThreeVaryings { var o: ThreeVaryings; o.clip = three_projection() * three_view() * three_model(v.instance) * vec4(v.position, 1.0); return o; }", "struct ThreeVaryings { @builtin(position) clip: vec4<f32>, };\nfn three_fragment(in: ThreeVaryings, front: bool) -> vec4<f32> { return vec4(u_tint(), 1.0); }", &l, Some(&[]), 0, false);
assert!(v.contains("@vertex\nfn vertex(m: ThreeMeshIn) -> ThreeVaryings"));
- assert!(f.contains("return three_untone(three_fragment(in, front));"));
+ assert!(f.contains("return three_blend(three_untone(three_fragment(in, front)));"));
assert!(f.contains("@group(constants::MATERIAL_BIND_GROUP) @binding(9) var three_lut: texture_3d<f32>;"));
}
}
diff --git a/systems/three-shader/src/module.rs b/systems/three-shader/src/module.rs
index 7bca0adb..1d409964 100644
--- a/systems/three-shader/src/module.rs
+++ b/systems/three-shader/src/module.rs
@@ -240,7 +240,7 @@ pub fn vertex_entry(attributes: usize) -> String {
pub fn fragment_entry() -> String {
let mut m = String::from(TONE);
m = m.replace("GROUP", GROUP).replace("DISPLAY_SLOT", &DISPLAY_SLOT.to_string());
- m + "\n@fragment\nfn fragment(in: ThreeVaryings, @builtin(front_facing) front: bool) -> @location(0) vec4<f32> {\n return three_untone(three_fragment(in, front));\n}\n"
+ m + "\n@fragment\nfn fragment(in: ThreeVaryings, @builtin(front_facing) front: bool) -> @location(0) vec4<f32> {\n return three_blend(three_untone(three_fragment(in, front)));\n}\n"
}
const TONE: &str = include_str!("tone.wesl");
diff --git a/systems/three-shader/src/storage.rs b/systems/three-shader/src/storage.rs
new file mode 100644
index 00000000..b2d8e7a6
--- /dev/null
+++ b/systems/three-shader/src/storage.rs
@@ -0,0 +1,200 @@
+//! A node material's storage buffers and copies (docs/r3f.feature R3F22). The buffers: up to two shared buffers it reads
+//! (`tsl_s0`, `tsl_s1`, which the SDK names in its WGSL and lists in the spec's wgsl `storage`: [{name, key, size, f32?}]),
+//! bound at 11 and 12 read-only, the same buffers by key the computes write (raea-sys-compute shared.rs); the empty
+//! one where it reads fewer. The copies: a BufferMesh with `copies` ({count, attributes?: {NAME: {size, values}},
+//! matrices?}) is its geometry repeated once a copy (an InstancedMesh as three draws it, one draw), each copy's number
+//! its own attribute `tsl_copy`, a per-copy attribute on each of the copy's vertices, its matrix baked into its
+//! positions and normals. A material reading a buffer isn't culled by its mesh's bounds: what the computes write moves it.
+
+use bevy::camera::visibility::NoFrustumCulling;
+use bevy::mesh::{Indices, VertexAttributeValues};
+use bevy::prelude::*;
+use bevy::render::storage::ShaderBuffer;
+use raea_sys_shader::shared::{first_contents, SharedBuffers};
+use serde_json::Value;
+
+use crate::{ThreeShader, ATTRIBUTE};
+
+/// The buffers a node material may read, and the first one's binding.
+pub const STORAGE: usize = 2;
+pub const BINDING: u32 = 11;
+
+/// The spec's wgsl `storage`: each buffer's handle by its binding (the empty one where none), its names, in order.
+pub fn buffers(world: &mut World, wgsl: Option<&Value>) -> Result<([Handle<ShaderBuffer>; STORAGE], Vec<String>), String> {
+ let list = wgsl.and_then(|w| w.get("storage")).and_then(Value::as_array).cloned().unwrap_or_default();
+ if list.len() > STORAGE {
+ return Err(format!("a three shader reads at most {STORAGE} storage buffers, got {}", list.len()));
+ }
+ world.init_resource::<SharedBuffers>();
+ world.init_resource::<Assets<ShaderBuffer>>();
+ world.resource_scope::<SharedBuffers, _>(|world, mut s| {
+ let mut assets = world.resource_mut::<Assets<ShaderBuffer>>();
+ let empty = s.empty(&mut assets);
+ let mut out = [empty.clone(), empty];
+ let mut names = vec![];
+ for (i, b) in list.iter().enumerate() {
+ let name = format!("tsl_s{i}");
+ if b.get("name").and_then(Value::as_str) != Some(name.as_str()) {
+ return Err(format!("a three shader's storage buffer {i} is {name}, got {}", b.get("name").unwrap_or(&Value::Null)));
+ }
+ let key = b.get("key").and_then(Value::as_str).ok_or_else(|| format!("storage buffer {name} has no key"))?;
+ out[i] = s.get_or_make(&mut assets, key, first_contents(b).map_err(|e| format!("storage buffer {name}: {e}"))?)?;
+ names.push(name);
+ }
+ Ok((out, names))
+ })
+}
+
+/// Each stage's `var<storage, read> tsl_sN :` given its binding in the material's group.
+pub fn bind(src: &str, names: &[String]) -> String {
+ names.iter().enumerate().fold(src.to_string(), |s, (i, n)| {
+ s.replace(&format!("var<storage, read> {n} :"), &format!("@group(constants::MATERIAL_BIND_GROUP) @binding({}) var<storage, read> {n} :", BINDING + i as u32))
+ })
+}
+
+/// A BufferMesh's `copies` onto its mesh (one copy, as made from the geometry): the vertices and indices repeated a copy
+/// at a time, its matrix baked in, and its own attributes (`own`, a0.. in order): `tsl_copy` the copy's number, a
+/// per-copy attribute the copy's value, any other the geometry's per vertex (`v`'s attributes).
+pub fn fit_copies(mesh: &mut Mesh, v: &Value, own: &[String]) -> Result<(), String> {
+ let c = v.get("copies").ok_or("no copies")?;
+ let count = c.get("count").and_then(Value::as_u64).unwrap_or(0) as usize;
+ if !(1..=1 << 24).contains(&count) {
+ return Err(format!("a BufferMesh's copies: count, 1 to {}", 1 << 24));
+ }
+ let n = mesh.count_vertices();
+ let f4 = |a: &Option<&VertexAttributeValues>| match a {
+ Some(VertexAttributeValues::Float32x4(x)) => Some(x.clone()),
+ _ => None,
+ };
+ let get3 = |id| match mesh.attribute(id) {
+ Some(VertexAttributeValues::Float32x3(x)) => Ok(x.clone()),
+ _ => Err("a mesh of copies has positions and normals, three floats each".to_string()),
+ };
+ let (pos, nor) = (get3(Mesh::ATTRIBUTE_POSITION)?, get3(Mesh::ATTRIBUTE_NORMAL)?);
+ let uv = match mesh.attribute(Mesh::ATTRIBUTE_UV_0) {
+ Some(VertexAttributeValues::Float32x2(x)) => x.clone(),
+ _ => vec![[0.0; 2]; n],
+ };
+ let col = f4(&mesh.attribute(Mesh::ATTRIBUTE_COLOR)).unwrap_or_else(|| vec![[1.0; 4]; n]);
+ let nums = |x: &Value, what: &str| -> Result<Vec<f32>, String> { x.as_array().ok_or_else(|| format!("{what}: numbers"))?.iter().map(|x| x.as_f64().map(|f| f as f32).ok_or_else(|| format!("{what}: numbers, got {x}"))).collect() };
+ let mats: Option<Vec<Mat4>> = match c.get("matrices") {
+ None | Some(Value::Null) => None,
+ Some(x) => {
+ let m = nums(x, "copies' matrices")?;
+ if m.len() != count * 16 {
+ return Err(format!("a BufferMesh's copies' matrices: 16 numbers for each of {count} copies, got {}", m.len()));
+ }
+ Some(m.chunks(16).map(Mat4::from_cols_slice).collect())
+ }
+ };
+ // each own attribute: the copy's number, a per-copy value, or the geometry's per vertex (as fit_mesh lays it)
+ enum Own {
+ Copy,
+ PerCopy(usize, Vec<f32>),
+ PerVertex(Vec<[f32; 4]>),
+ }
+ let verts = v.get("positions").and_then(Value::as_array).map(|p| p.len() / 3).unwrap_or(0);
+ let indexed = mesh.indices().is_some();
+ let corners = if indexed { (0..verts).collect() } else { raea_sys_material::mesh::buffer_corners(v, verts) };
+ let mut owns = vec![];
+ for name in own {
+ if name == "tsl_copy" {
+ owns.push(Own::Copy);
+ } else if let Some(a) = c.get("attributes").and_then(|a| a.get(name)) {
+ let size = a.get("size").and_then(Value::as_u64).unwrap_or(1).clamp(1, 4) as usize;
+ let vals = nums(a.get("values").unwrap_or(&Value::Null), &format!("copies' attribute {name}"))?;
+ if vals.len() < count * size {
+ return Err(format!("copies' attribute {name}: {size} numbers for each of {count} copies, got {}", vals.len()));
+ }
+ owns.push(Own::PerCopy(size, vals));
+ } else {
+ let a = v.get("attributes").and_then(|a| a.get(name)).ok_or_else(|| format!("the shader reads attribute {name}, which the mesh of copies doesn't give"))?;
+ let size = a.get("size").and_then(Value::as_u64).unwrap_or(1).clamp(1, 4) as usize;
+ let vals = nums(a.get("values").unwrap_or(&Value::Null), &format!("attribute {name}"))?;
+ if vals.len() < verts * size {
+ return Err(format!("attribute {name}: {size} numbers for each of {verts} vertices, got {}", vals.len()));
+ }
+ let per: Vec<[f32; 4]> = corners.iter().map(|&i| std::array::from_fn(|k| if k < size { vals[i * size + k] } else { 0.0 })).collect();
+ if per.len() != n {
+ return Err(format!("attribute {name}: {} vertices, the mesh has {n}", per.len()));
+ }
+ owns.push(Own::PerVertex(per));
+ }
+ }
+ let total = n * count;
+ let (mut p, mut q, mut u, mut k) = (Vec::with_capacity(total), Vec::with_capacity(total), Vec::with_capacity(total), Vec::with_capacity(total));
+ let mut a: Vec<Vec<[f32; 4]>> = owns.iter().map(|_| Vec::with_capacity(total)).collect();
+ for i in 0..count {
+ let (m, nm) = match &mats {
+ Some(m) => (m[i], Mat3::from_mat4(m[i]).inverse().transpose()),
+ None => (Mat4::IDENTITY, Mat3::IDENTITY),
+ };
+ for j in 0..n {
+ p.push(m.transform_point3(Vec3::from(pos[j])).to_array());
+ q.push((nm * Vec3::from(nor[j])).normalize_or_zero().to_array());
+ u.push(uv[j]);
+ k.push(col[j]);
+ for (out, o) in a.iter_mut().zip(&owns) {
+ out.push(match o {
+ Own::Copy => [i as f32, 0.0, 0.0, 0.0],
+ Own::PerCopy(s, vals) => std::array::from_fn(|c| if c < *s { vals[i * s + c] } else { 0.0 }),
+ Own::PerVertex(per) => per[j],
+ });
+ }
+ }
+ }
+ let idx: Option<Vec<u32>> = mesh.indices().map(|ix| match ix {
+ Indices::U16(v) => v.iter().map(|&x| u32::from(x)).collect(),
+ Indices::U32(v) => v.clone(),
+ });
+ let mut out = Mesh::new(mesh.primitive_topology(), mesh.asset_usage);
+ out.insert_attribute(Mesh::ATTRIBUTE_POSITION, p);
+ out.insert_attribute(Mesh::ATTRIBUTE_NORMAL, q);
+ out.insert_attribute(Mesh::ATTRIBUTE_UV_0, u);
+ out.insert_attribute(Mesh::ATTRIBUTE_COLOR, k);
+ for (i, vals) in a.into_iter().enumerate() {
+ out.insert_attribute(ATTRIBUTE[i].clone(), vals);
+ }
+ if let Some(idx) = idx {
+ out.insert_indices(Indices::U32((0..count).flat_map(|i| idx.iter().map(move |x| x + (i * n) as u32)).collect()));
+ }
+ *mesh = out;
+ Ok(())
+}
+
+/// A mesh whose three shader reads a shared buffer isn't culled by its bounds (where the computes put its vertices).
+pub fn unbounded(mut cmd: Commands, parts: Query<(Entity, &MeshMaterial3d<ThreeShader>), (Changed<MeshMaterial3d<ThreeShader>>, Without<NoFrustumCulling>)>, mats: Res<Assets<ThreeShader>>) {
+ for (e, m) in &parts {
+ if mats.get(&m.0).is_some_and(|m| m.unbounded) {
+ cmd.entity(e).insert(NoFrustumCulling);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use bevy::asset::RenderAssetUsages;
+ use bevy::mesh::PrimitiveTopology;
+
+ #[test]
+ fn copies_repeat_the_geometry_with_their_number_matrix_and_values() {
+ let mut m = Mesh::new(PrimitiveTopology::TriangleList, RenderAssetUsages::default());
+ m.insert_attribute(Mesh::ATTRIBUTE_POSITION, vec![[0.0f32, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]);
+ m.insert_attribute(Mesh::ATTRIBUTE_NORMAL, vec![[0.0f32, 0.0, 1.0]; 3]);
+ m.insert_indices(Indices::U32(vec![0, 1, 2]));
+ let mut mats: Vec<f32> = Mat4::IDENTITY.to_cols_array().to_vec();
+ mats.extend(Mat4::from_translation(Vec3::new(5.0, 0.0, 0.0)).to_cols_array());
+ let v = serde_json::json!({ "positions": [0, 0, 0, 1, 0, 0, 0, 1, 0], "indices": [0, 1, 2], "copies": { "count": 2, "attributes": { "instanceColor": { "size": 3, "values": [1, 0, 0, 0, 1, 0] } }, "matrices": mats } });
+ fit_copies(&mut m, &v, &["tsl_copy".into(), "instanceColor".into()]).unwrap();
+ assert_eq!(m.count_vertices(), 6);
+ let Some(VertexAttributeValues::Float32x3(p)) = m.attribute(Mesh::ATTRIBUTE_POSITION) else { panic!() };
+ assert_eq!(p[4], [6.0, 0.0, 0.0]);
+ let Some(VertexAttributeValues::Float32x4(a0)) = m.attribute(ATTRIBUTE[0].clone()) else { panic!() };
+ assert_eq!((a0[2][0], a0[3][0]), (0.0, 1.0));
+ let Some(VertexAttributeValues::Float32x4(a1)) = m.attribute(ATTRIBUTE[1].clone()) else { panic!() };
+ assert_eq!(a1[5], [0.0, 1.0, 0.0, 0.0]);
+ assert_eq!(m.indices().unwrap().iter().collect::<Vec<_>>(), vec![0, 1, 2, 3, 4, 5]);
+ assert_eq!(bind("var<storage, read> tsl_s0 : B;", &["tsl_s0".into()]), "@group(constants::MATERIAL_BIND_GROUP) @binding(11) var<storage, read> tsl_s0 : B;");
+ }
+}
diff --git a/systems/three-shader/src/tone.wesl b/systems/three-shader/src/tone.wesl
index 0da7f632..7ad5fa55 100644
--- a/systems/three-shader/src/tone.wesl
+++ b/systems/three-shader/src/tone.wesl
@@ -138,3 +138,13 @@ fn three_untone(c: vec4<f32>) -> vec4<f32> {
}
return vec4(x, c.a);
}
+
+/// the colour as the blend takes it: an additive material's premultiplied with no alpha of its own, since Bevy blends
+/// AlphaMode::Add as premultiplied alpha (src + dst * (1 - src.a)) and three's AdditiveBlending adds src * src.a, so
+/// overlapping particles sum as three sums them (docs/r3f.feature R3F22). The alpha mode is surface.rs's alpha_code.
+fn three_blend(c: vec4<f32>) -> vec4<f32> {
+ if u32(three_slots.s[DISPLAY_SLOT].z + 0.5) == 4u {
+ return vec4(c.rgb * c.a, 0.0);
+ }
+ return c;
+}